answer
stringlengths
17
10.2M
package org.splevo.ui.editors; import java.io.File; import java.io.IOException; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.compare.util.ModelUtils; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.wb.swt.ResourceManager; import org.eclipse.wb.swt.SWTResourceManager; import org.splevo.project.SPLevoProject; import org.splevo.project.SPLevoProjectUtil; import org.splevo.ui.listeners.DiffSourceModelListener; import org.splevo.ui.listeners.ExtractProjectListener; import org.splevo.ui.listeners.GenerateFeatureModelListener; import org.splevo.ui.listeners.GotoTabMouseListener; import org.splevo.ui.listeners.InitVPMListener; import org.splevo.ui.listeners.MarkDirtyListener; import org.splevo.ui.listeners.ProjectDropListener; import org.splevo.ui.listeners.VPMAnalysisListener; public class SPLevoProjectEditor extends EditorPart { public static final String ID = "org.splevo.ui.editors.SPLevoProjectEditor"; //$NON-NLS-1$ private static final int TABINDEX_PROCESS_CONTROL = 0; private static final int TABINDEX_PROJECT_INFOS = 1; private static final int TABINDEX_PROJECT_SELECTION = 2; private static final int TABINDEX_SOURCE_MODELS = 3; private static final int TABINDEX_DIFFING_MODEL = 4; /** The splevo project manipulated in the editor instance. */ private SPLevoProject splevoProject = null; private TabFolder tabFolder; private TabItem tbtmProjectSelection = null; /** The table viewer for the leading source models the variant should be integrated to */ private TableViewer viewerLeadingProjects; private TableColumn tblclmnLeadingProjects; private TableViewer viewerIntegrationProjects; private Text projectNameInput; private Text infoInput; private Text workspaceInput; /** Flag identifying the dirty state of the editor. */ private boolean dirtyFlag = false; private Transfer[] transferTypes = new Transfer[] { FileTransfer.getInstance() }; private Text inputVariantNameLeading; private Text inputVariantNameIntegration; private Text sourceModelLeadingInput; private Text sourceModelIntegrationInput; private Text diffingModelInput; private Text diffingPackageFilterInput; public SPLevoProjectEditor() { setTitleImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/splevo.gif")); } /** * Create contents of the editor part. * * @param parent */ @Override public void createPartControl(Composite parent) { parent.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); GridLayout gl_parent = new GridLayout(1, false); gl_parent.verticalSpacing = 0; gl_parent.marginWidth = 0; gl_parent.marginHeight = 0; gl_parent.horizontalSpacing = 0; parent.setLayout(gl_parent); // init the data tables tabFolder = new TabFolder(parent, SWT.NONE); tabFolder.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); GridData gd_tabFolder = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_tabFolder.widthHint = 837; gd_tabFolder.heightHint = 353; tabFolder.setLayoutData(gd_tabFolder); // create tabs createProcessControlTab(); createProjectInfoTab(); createProjectSelectionTab(); createSourceModelTab(); createDiffingModelTab(); initDataBindings(); } /** * Create the tab to handle the source models. */ private void createSourceModelTab() { TabItem tabItemSourceModel = new TabItem(tabFolder, SWT.NONE, TABINDEX_SOURCE_MODELS); tabItemSourceModel.setText("Source Models"); Composite sourceModelTabComposite = new Composite(tabFolder, SWT.NONE); tabItemSourceModel.setControl(sourceModelTabComposite); sourceModelTabComposite.setLayout(null); Label lblTheSoftwareModels = new Label(sourceModelTabComposite, SWT.NONE); lblTheSoftwareModels.setBounds(10, 10, 490, 20); lblTheSoftwareModels.setText("The software models extracted from the source projects."); Label lblLeadingProjectModel = new Label(sourceModelTabComposite, SWT.NONE); lblLeadingProjectModel.setBounds(10, 44, 191, 20); lblLeadingProjectModel.setText("Leading Source Model:"); sourceModelLeadingInput = new Text(sourceModelTabComposite, SWT.BORDER); sourceModelLeadingInput.setBounds(10, 67, 490, 26); Label lblsourceModelIntegration = new Label(sourceModelTabComposite, SWT.NONE); lblsourceModelIntegration.setText("Integration Source Model:"); lblsourceModelIntegration.setBounds(10, 124, 191, 20); sourceModelIntegrationInput = new Text(sourceModelTabComposite, SWT.BORDER); sourceModelIntegrationInput.setBounds(10, 147, 490, 26); } /** * Create the tab to handle the diff model. */ private void createDiffingModelTab() { TabItem tbtmDiffingModel = new TabItem(tabFolder, SWT.NONE, TABINDEX_DIFFING_MODEL); tbtmDiffingModel.setText("Diffing Model"); Composite composite = new Composite(tabFolder, SWT.NONE); tbtmDiffingModel.setControl(composite); Label lblDiffingModelDescription = new Label(composite, SWT.NONE); lblDiffingModelDescription.setText("The diffing model extracted from the source models."); lblDiffingModelDescription.setBounds(10, 10, 490, 20); Label lblDiffingModel = new Label(composite, SWT.NONE); lblDiffingModel.setText("Diffing Model:"); lblDiffingModel.setBounds(10, 44, 191, 20); diffingModelInput = new Text(composite, SWT.BORDER); diffingModelInput.setBounds(10, 67, 490, 26); diffingPackageFilterInput = new Text(composite, SWT.BORDER | SWT.WRAP); diffingPackageFilterInput.setBounds(10, 141, 490, 158); Label lblPackageFilterRules = new Label(composite, SWT.NONE); lblPackageFilterRules.setBounds(10, 115, 266, 20); lblPackageFilterRules.setText("Package Filter Rules (one per line):"); } /** * Create the tab to select the source projects. */ private void createProjectSelectionTab() { // SOURCE PROJECT SELECTION TAB tbtmProjectSelection = new TabItem(tabFolder, SWT.NONE, TABINDEX_PROJECT_SELECTION); tbtmProjectSelection.setText("Source Projects"); Composite composite = new Composite(tabFolder, SWT.NONE); tbtmProjectSelection.setControl(composite); composite.setLayout(null); Label lblNewLabel = new Label(composite, SWT.NONE); lblNewLabel.setToolTipText("Select the source entity models of the leading projects"); lblNewLabel.setBounds(10, 10, 740, 20); lblNewLabel.setText("Define the projects to be consolidated"); // / LEADING PROJECT LIST viewerLeadingProjects = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); viewerLeadingProjects.setContentProvider(ArrayContentProvider.getInstance()); viewerLeadingProjects.setInput(getSplevoProject().getLeadingProjects()); ProjectDropListener dropListenerLeadingProjects = new ProjectDropListener(viewerLeadingProjects, splevoProject.getLeadingProjects()); viewerLeadingProjects.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, transferTypes, dropListenerLeadingProjects); Table tableLeadingProjects = viewerLeadingProjects.getTable(); tableLeadingProjects.setHeaderVisible(true); tableLeadingProjects.setLinesVisible(true); tableLeadingProjects.setBounds(10, 63, 350, 209); tblclmnLeadingProjects = new TableColumn(tableLeadingProjects, SWT.NONE); tblclmnLeadingProjects.setWidth(tblclmnLeadingProjects.getParent().getBounds().width); tblclmnLeadingProjects.setText("Leading Projects"); // / INTEGRATION PROJECT LIST viewerIntegrationProjects = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); viewerIntegrationProjects.setContentProvider(ArrayContentProvider.getInstance()); viewerIntegrationProjects.setInput(getSplevoProject().getIntegrationProjects()); ProjectDropListener dropListenerIntegrationProjects = new ProjectDropListener(viewerIntegrationProjects, splevoProject.getIntegrationProjects()); viewerIntegrationProjects.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, transferTypes, dropListenerIntegrationProjects); Table tableIntegrationProjects = viewerIntegrationProjects.getTable(); tableIntegrationProjects.setHeaderVisible(true); tableIntegrationProjects.setLinesVisible(true); tableIntegrationProjects.setBounds(430, 63, 350, 209); TableColumn tblclmnIntegrationProjects = new TableColumn(tableIntegrationProjects, SWT.NONE); tblclmnIntegrationProjects.setWidth(tblclmnIntegrationProjects.getParent().getBounds().width); tblclmnIntegrationProjects.setText("Integration Projects"); Button btnClear = new Button(composite, SWT.NONE); btnClear.setGrayed(true); btnClear.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/cross.png")); btnClear.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { getSplevoProject().getLeadingProjects().clear(); viewerLeadingProjects.refresh(); markAsDirty(); } }); btnClear.setBounds(366, 63, 30, 30); Button btnClearList = new Button(composite, SWT.NONE); btnClearList.setToolTipText("Clear the list of source projects to integrate."); btnClearList.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/cross.png")); btnClearList.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { getSplevoProject().getIntegrationProjects().clear(); viewerIntegrationProjects.refresh(); markAsDirty(); } }); btnClearList.setBounds(786, 63, 30, 30); Label labelVariantNameLeading = new Label(composite, SWT.NONE); labelVariantNameLeading.setBounds(10, 37, 106, 20); labelVariantNameLeading.setText("Variant Name:"); Label labelVariantNameIntegration = new Label(composite, SWT.NONE); labelVariantNameIntegration.setText("Variant Name:"); labelVariantNameIntegration.setBounds(430, 36, 106, 20); inputVariantNameLeading = new Text(composite, SWT.BORDER); inputVariantNameLeading.setBounds(122, 36, 238, 26); inputVariantNameIntegration = new Text(composite, SWT.BORDER); inputVariantNameIntegration.setBounds(542, 36, 238, 26); composite.setTabList(new Control[] { tableLeadingProjects, tableIntegrationProjects }); } /** * Create the tab for project information */ private void createProjectInfoTab() { TabItem tbtmProjectInfos = new TabItem(tabFolder, SWT.NONE, TABINDEX_PROJECT_INFOS); tbtmProjectInfos.setText("Project Infos"); Composite projectInfoContainer = new Composite(tabFolder, SWT.NONE); tbtmProjectInfos.setControl(projectInfoContainer); projectNameInput = new Text(projectInfoContainer, SWT.BORDER); projectNameInput.setBounds(113, 30, 307, 26); Label lblProjectName = new Label(projectInfoContainer, SWT.NONE); lblProjectName.setBounds(10, 33, 97, 20); lblProjectName.setText("Project Name"); Label lblInfo = new Label(projectInfoContainer, SWT.NONE); lblInfo.setBounds(10, 62, 70, 20); lblInfo.setText("Info"); infoInput = new Text(projectInfoContainer, SWT.BORDER | SWT.WRAP); infoInput.setBounds(113, 62, 307, 112); Label lblWorkspace = new Label(projectInfoContainer, SWT.NONE); lblWorkspace.setBounds(10, 180, 83, 20); lblWorkspace.setText("Workspace"); workspaceInput = new Text(projectInfoContainer, SWT.BORDER); workspaceInput.setBounds(113, 180, 307, 26); } private void createProcessControlTab() { TabItem tbtmProcessControl = new TabItem(tabFolder, SWT.NONE, TABINDEX_PROCESS_CONTROL); tbtmProcessControl.setText("Process Control"); Composite processControlContainer = new Composite(tabFolder, SWT.NONE); tbtmProcessControl.setControl(processControlContainer); Label lblSplevoDashboard = new Label(processControlContainer, SWT.NONE); lblSplevoDashboard.setAlignment(SWT.CENTER); lblSplevoDashboard.setFont(SWTResourceManager.getFont("Arial", 14, SWT.BOLD)); lblSplevoDashboard.setBounds(10, 10, 746, 30); lblSplevoDashboard.setText("SPLevo Dashboard"); Label activityStart = new Label(processControlContainer, SWT.NONE); activityStart.setAlignment(SWT.CENTER); activityStart.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/bullet_green.png")); activityStart.setBounds(20, 66, 30, 30); Label activityFlow0 = new Label(processControlContainer, SWT.NONE); activityFlow0.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow0.setAlignment(SWT.CENTER); activityFlow0.setBounds(44, 66, 30, 30); Button btnSelectSourceProjects = new Button(processControlContainer, SWT.WRAP); btnSelectSourceProjects.addMouseListener(new GotoTabMouseListener(tabFolder, TABINDEX_PROJECT_SELECTION)); btnSelectSourceProjects.setBounds(75, 59, 78, 45); btnSelectSourceProjects.setText("Project Selection"); Label activityFlow1 = new Label(processControlContainer, SWT.NONE); activityFlow1.setAlignment(SWT.CENTER); activityFlow1.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow1.setBounds(159, 66, 30, 30); Button btnExtractSourceModels = new Button(processControlContainer, SWT.WRAP); btnExtractSourceModels.addMouseListener(new ExtractProjectListener(this)); btnExtractSourceModels.setBounds(195, 59, 78, 45); btnExtractSourceModels.setText("Model Extraction"); Label activityFlow3 = new Label(processControlContainer, SWT.NONE); activityFlow3.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow3.setAlignment(SWT.CENTER); activityFlow3.setBounds(279, 66, 30, 30); Button btnDiffing = new Button(processControlContainer, SWT.WRAP); btnDiffing.addMouseListener(new DiffSourceModelListener(this)); btnDiffing.setBounds(315, 59, 72, 45); btnDiffing.setText("Diffing"); Label activityFlow4 = new Label(processControlContainer, SWT.NONE); activityFlow4.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow4.setAlignment(SWT.CENTER); activityFlow4.setBounds(393, 66, 30, 30); Button btnInitVpm = new Button(processControlContainer, SWT.WRAP); btnInitVpm.addMouseListener(new InitVPMListener(this)); btnInitVpm.setBounds(429, 59, 72, 45); btnInitVpm.setText("Init VPM"); Label activityFlow5 = new Label(processControlContainer, SWT.NONE); activityFlow5.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); activityFlow5.setAlignment(SWT.CENTER); activityFlow5.setBounds(507, 66, 30, 30); Button btnRefineVPM = new Button(processControlContainer, SWT.WRAP); btnRefineVPM.addMouseListener(new VPMAnalysisListener(this)); btnRefineVPM.setText("Analyze VPM"); btnRefineVPM.setBounds(539, 59, 72, 45); Label label = new Label(processControlContainer, SWT.NONE); label.setImage(ResourceManager.getPluginImage("org.splevo.ui", "icons/arrow_right.png")); label.setAlignment(SWT.CENTER); label.setBounds(617, 66, 30, 30); Button btnGenerateFeatureModel = new Button(processControlContainer, SWT.WRAP); btnGenerateFeatureModel.addMouseListener(new GenerateFeatureModelListener(this)); btnGenerateFeatureModel.setText("Generate Feature Model"); btnGenerateFeatureModel.setBounds(648, 59, 118, 45); } @Override public void setFocus() { // Set the focus } /** * Get the editor input resource. This methods overrides the super types method to return a more * specific IFileEditorInput. * * @return The editor input converted to an IFileEditorInput or null if not possible. */ @Override public IFileEditorInput getEditorInput() { if (super.getEditorInput() instanceof IFileEditorInput) { return (IFileEditorInput) super.getEditorInput(); } return null; } /** * Save the project configuration to the currently edited file. * * @param monitor * The progress monitor to report to. */ @Override public void doSave(IProgressMonitor monitor) { // check workspace setting if (getSplevoProject().getWorkspace() == null || getSplevoProject().getWorkspace().equals("")) { Shell shell = getEditorSite().getShell(); MessageDialog.openError(shell, "Workspace Missing", "You need to specify a workspace directory for the project."); return; } String filePath = null; try { filePath = getCurrentFilePath(); ModelUtils.save(splevoProject, filePath); } catch (Exception e) { Shell shell = getEditorSite().getShell(); MessageDialog.openError(shell, "Save error", "Unable to save the project file to " + filePath); e.printStackTrace(); } dirtyFlag = false; firePropertyChange(IEditorPart.PROP_DIRTY); } /** * Get the absolute path of the current editor input file. * * @return The file path derived from the editor input. */ private String getCurrentFilePath() { FileEditorInput fileInput = (FileEditorInput) getEditorInput(); String filePath = fileInput.getFile().getFullPath().toOSString(); return filePath; } @Override public void doSaveAs() { // do save as is not supported } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); if (input instanceof IFileEditorInput) { IFileEditorInput fileInput = (IFileEditorInput) input; if (fileInput.getName().endsWith(SPLevoProjectUtil.SPLEVO_FILE_EXTENSION)) { ResourceSet rs = new ResourceSetImpl(); File projectFile = new File(fileInput.getFile().getFullPath().toOSString()); EObject model; try { model = ModelUtils.load(projectFile, rs); } catch (IOException e) { throw new PartInitException("Unable to load SPLevo project file in editor", e); } if (model instanceof SPLevoProject) { this.splevoProject = (SPLevoProject) model; } } } } /** * @return the splevoProject */ public SPLevoProject getSplevoProject() { return splevoProject; } @Override public boolean isDirty() { return dirtyFlag; } @Override public boolean isSaveAsAllowed() { return false; } /** * Mark the editor as dirty. */ public void markAsDirty() { dirtyFlag = true; firePropertyChange(IEditorPart.PROP_DIRTY); } /** * Update the ui and present the submitted message in an information dialog. If the provided * message is null, no dialog will be opened. * * @param message * The optional message to be presented. */ public void updateUi(String message) { updateUI(); if (message != null) { Shell shell = getEditorSite().getShell(); MessageDialog.openInformation(shell, "SPLevo Info", message); } } /** * Update the user interface. */ public void updateUI() { sourceModelLeadingInput.setText(splevoProject.getSourceModelPathLeading()); sourceModelIntegrationInput.setText(splevoProject.getSourceModelPathIntegration()); if (splevoProject.getDiffingModelPath() != null) { diffingModelInput.setText(splevoProject.getDiffingModelPath()); } markAsDirty(); } protected DataBindingContext initDataBindings() { DataBindingContext bindingContext = new DataBindingContext(); MarkDirtyListener markDirtyListener = new MarkDirtyListener(this); IObservableValue observeTextProjectNameInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( projectNameInput); IObservableValue nameGetSplevoProjectObserveValue = PojoProperties.value("name").observe(getSplevoProject()); nameGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext .bindValue(observeTextProjectNameInputObserveWidget, nameGetSplevoProjectObserveValue, null, null); IObservableValue observeTextInfoInputObserveWidget = WidgetProperties.text(SWT.Modify).observe(infoInput); IObservableValue descriptionGetSplevoProjectObserveValue = PojoProperties.value("description").observe( getSplevoProject()); descriptionGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext .bindValue(observeTextInfoInputObserveWidget, descriptionGetSplevoProjectObserveValue, null, null); IObservableValue observeTextWorkspaceInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( workspaceInput); IObservableValue workspaceGetSplevoProjectObserveValue = PojoProperties.value("workspace").observe( getSplevoProject()); workspaceGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextWorkspaceInputObserveWidget, workspaceGetSplevoProjectObserveValue, null, null); IObservableValue observeTextInputVariantNameLeadingObserveWidget = WidgetProperties.text(SWT.Modify).observe( inputVariantNameLeading); IObservableValue variantNameLeadingGetSplevoProjectObserveValue = PojoProperties.value("variantNameLeading") .observe(getSplevoProject()); variantNameLeadingGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextInputVariantNameLeadingObserveWidget, variantNameLeadingGetSplevoProjectObserveValue, null, null); IObservableValue observeTextInputVariantNameIntegrationObserveWidget = WidgetProperties.text(SWT.Modify) .observe(inputVariantNameIntegration); IObservableValue variantNameIntegrationGetSplevoProjectObserveValue = PojoProperties.value( "variantNameIntegration").observe(getSplevoProject()); variantNameIntegrationGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextInputVariantNameIntegrationObserveWidget, variantNameIntegrationGetSplevoProjectObserveValue, null, null); IObservableValue observeTextSourceModelLeadingObserveWidget = WidgetProperties.text(SWT.Modify).observe( sourceModelLeadingInput); IObservableValue sourceModelPathLeadingGetSplevoProjectObserveValue = PojoProperties.value( "sourceModelPathLeading").observe(splevoProject); sourceModelPathLeadingGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextSourceModelLeadingObserveWidget, sourceModelPathLeadingGetSplevoProjectObserveValue, null, null); IObservableValue observeTextSourceModelIntegrationObserveWidget = WidgetProperties.text(SWT.Modify).observe( sourceModelIntegrationInput); IObservableValue sourceModelPathIntegrationGetSplevoProjectObserveValue = PojoProperties.value( "sourceModelPathIntegration").observe(splevoProject); sourceModelPathIntegrationGetSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextSourceModelIntegrationObserveWidget, sourceModelPathIntegrationGetSplevoProjectObserveValue, null, null); IObservableValue observeTextDiffingModelInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( diffingModelInput); IObservableValue diffingModelPathSplevoProjectObserveValue = PojoProperties.value("diffingModelPath").observe( splevoProject); diffingModelPathSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextDiffingModelInputObserveWidget, diffingModelPathSplevoProjectObserveValue, null, null); IObservableValue observeTextDiffingPackageFilterInputObserveWidget = WidgetProperties.text(SWT.Modify).observe( diffingPackageFilterInput); IObservableValue diffingFilterRulesSplevoProjectObserveValue = PojoProperties.value("diffingFilterRules") .observe(splevoProject); diffingFilterRulesSplevoProjectObserveValue.addChangeListener(markDirtyListener); bindingContext.bindValue(observeTextDiffingPackageFilterInputObserveWidget, diffingFilterRulesSplevoProjectObserveValue, null, null); return bindingContext; } }
package java.lang; import java.util.Map; import java.util.WeakHashMap; public class Thread implements Runnable { private long peer; private boolean interrupted; private boolean daemon; private byte state; private byte priority; private final Runnable task; private Map<ThreadLocal, Object> locals; private Object sleepLock; private ClassLoader classLoader; private UncaughtExceptionHandler exceptionHandler; // package private for GNU Classpath, which inexplicably bypasses // the accessor methods: String name; ThreadGroup group; private static UncaughtExceptionHandler defaultExceptionHandler; public static final int MIN_PRIORITY = 1; public static final int NORM_PRIORITY = 5; public static final int MAX_PRIORITY = 10; public Thread(ThreadGroup group, Runnable task, String name, long stackSize) { this.group = (group == null ? Thread.currentThread().group : group); this.task = task; this.name = name; Thread current = currentThread(); Map<ThreadLocal, Object> map = current.locals; if (map != null) { for (Map.Entry<ThreadLocal, Object> e: map.entrySet()) { if (e.getKey() instanceof InheritableThreadLocal) { InheritableThreadLocal itl = (InheritableThreadLocal) e.getKey(); locals().put(itl, itl.childValue(e.getValue())); } } } classLoader = current.classLoader; } public Thread(ThreadGroup group, Runnable task, String name) { this(group, task, name, 0); } public Thread(ThreadGroup group, String name) { this(null, null, name); } public Thread(Runnable task, String name) { this(null, task, name); } public Thread(Runnable task) { this(null, task, "Thread["+task+"]"); } public Thread(String name) { this(null, null, name); } public Thread() { this((Runnable) null); } public synchronized void start() { if (peer != 0) { throw new IllegalStateException("thread already started"); } peer = doStart(); if (peer == 0) { throw new RuntimeException("unable to start native thread"); } } private native long doStart(); private static void run(Thread t) throws Throwable { t.state = (byte) State.RUNNABLE.ordinal(); try { t.run(); } catch (Throwable e) { UncaughtExceptionHandler eh = t.exceptionHandler; UncaughtExceptionHandler deh = defaultExceptionHandler; if (eh != null) { eh.uncaughtException(t, e); } else if (deh != null) { deh.uncaughtException(t, e); } else { throw e; } } finally { synchronized (t) { t.state = (byte) State.TERMINATED.ordinal(); t.notifyAll(); } } } public void run() { if (task != null) { task.run(); } } public ClassLoader getContextClassLoader() { return classLoader; } public void setContextClassLoader(ClassLoader v) { classLoader = v; } public Map<ThreadLocal, Object> locals() { if (locals == null) { locals = new WeakHashMap(); } return locals; } public static native Thread currentThread(); private static native void interrupt(long peer); public synchronized void interrupt() { if (peer != 0) { interrupt(peer); } else { interrupted = true; } } public static boolean interrupted() { Thread t = currentThread(); synchronized (t) { boolean v = t.interrupted; t.interrupted = false; return v; } } public static boolean isInterrupted() { return currentThread().interrupted; } public static void sleep(long milliseconds) throws InterruptedException { Thread t = currentThread(); if (t.sleepLock == null) { t.sleepLock = new Object(); } synchronized (t.sleepLock) { t.sleepLock.wait(milliseconds); } } public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException { if (nanoseconds > 0) { ++ milliseconds; } sleep(milliseconds); } public StackTraceElement[] getStackTrace() { return Throwable.resolveTrace(getStackTrace(peer)); } private static native Object getStackTrace(long peer); public static native int activeCount(); public static native int enumerate(Thread[] array); public String getName() { return name; } public void setName(String name) { this.name = name; } public UncaughtExceptionHandler getUncaughtExceptionHandler() { UncaughtExceptionHandler eh = exceptionHandler; return (eh == null ? group : eh); } public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() { return defaultExceptionHandler; } public void setUncaughtExceptionHandler(UncaughtExceptionHandler h) { exceptionHandler = h; } public static void setDefaultUncaughtExceptionHandler (UncaughtExceptionHandler h) { defaultExceptionHandler = h; } public State getState() { return State.values()[state]; } public boolean isAlive() { switch (getState()) { case NEW: case TERMINATED: return false; default: return true; } } public int getPriority() { return priority; } public void setPriority(int priority) { if (priority < MIN_PRIORITY || priority > MAX_PRIORITY) { throw new IllegalArgumentException(); } this.priority = (byte) priority; } public boolean isDaemon() { return daemon; } public void setDaemon(boolean v) { daemon = v; } public static native void yield(); public synchronized void join() throws InterruptedException { while (getState() != State.TERMINATED) { wait(); } } public synchronized void join(long milliseconds) throws InterruptedException { long then = System.currentTimeMillis(); long remaining = milliseconds; while (remaining > 0 && getState() != State.TERMINATED) { wait(remaining); remaining = milliseconds - (System.currentTimeMillis() - then); } } public void join(long milliseconds, int nanoseconds) throws InterruptedException { if (nanoseconds > 0) { ++ milliseconds; } join(milliseconds); } public ThreadGroup getThreadGroup() { return group; } public static native boolean holdsLock(Object o); public long getId() { return peer; } public void stop() { throw new UnsupportedOperationException(); } public void stop(Throwable t) { throw new UnsupportedOperationException(); } public void suspend() { throw new UnsupportedOperationException(); } public void resume() { throw new UnsupportedOperationException(); } public interface UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e); } public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED } }
package org.peerbox.presenter; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import javafx.stage.Window; import org.hive2hive.core.exceptions.NoPeerConnectionException; import org.peerbox.ResultStatus; import org.peerbox.UserConfig; import org.peerbox.app.ClientContext; import org.peerbox.app.manager.user.IUserManager; import org.peerbox.guice.provider.ClientContextProvider; import org.peerbox.presenter.validation.EmptyTextFieldValidator; import org.peerbox.presenter.validation.RootPathValidator; import org.peerbox.presenter.validation.SelectRootPathUtils; import org.peerbox.presenter.validation.ValidationUtils.ValidationResult; import org.peerbox.view.ViewNames; import org.peerbox.view.controls.ErrorLabel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; public class LoginController implements Initializable { private static final Logger logger = LoggerFactory.getLogger(LoginController.class); private NavigationService fNavigationService; private IUserManager userManager; private UserConfig userConfig; @Inject private ClientContextProvider clientContext; @FXML private TextField txtUsername; @FXML private Label lblUsernameError; @FXML private PasswordField txtPassword; @FXML private Label lblPasswordError; @FXML private PasswordField txtPin; @FXML private Label lblPinError; @FXML private TextField txtRootPath; @FXML private Label lblPathError; @FXML private CheckBox chbAutoLogin; @FXML private Button btnLogin; @FXML private Button btnRegister; @FXML private GridPane grdForm; @FXML private ErrorLabel lblError; @FXML private ProgressIndicator piProgress; private EmptyTextFieldValidator usernameValidator; private EmptyTextFieldValidator passwordValidator; private EmptyTextFieldValidator pinValidator; private RootPathValidator pathValidator; @Inject public LoginController(NavigationService navigationService, IUserManager userManager) { this.fNavigationService = navigationService; this.userManager = userManager; } public void initialize(URL location, ResourceBundle resources) { initializeValidations(); loadUserConfig(); } private void loadUserConfig() { if (userConfig.hasUsername()) { txtUsername.setText(userConfig.getUsername()); } if (userConfig.hasRootPath()) { txtRootPath.setText(userConfig.getRootPath().toString()); } chbAutoLogin.setSelected(userConfig.isAutoLoginEnabled()); } private void resetForm() { loadUserConfig(); txtPassword.clear(); txtPin.clear(); grdForm.disableProperty().unbind(); grdForm.setDisable(false); uninstallProgressIndicator(); uninstallValidationDecorations(); } private void initializeValidations() { usernameValidator = new EmptyTextFieldValidator(txtUsername, true, ValidationResult.USERNAME_EMPTY); usernameValidator.setErrorProperty(lblUsernameError.textProperty()); passwordValidator = new EmptyTextFieldValidator(txtPassword, false, ValidationResult.PASSWORD_EMPTY); passwordValidator.setErrorProperty(lblPasswordError.textProperty()); pinValidator = new EmptyTextFieldValidator(txtPin, false, ValidationResult.PIN_EMPTY); pinValidator.setErrorProperty(lblPinError.textProperty()); pathValidator = new RootPathValidator(txtRootPath, lblPathError.textProperty()); } private void uninstallValidationDecorations() { usernameValidator.reset(); passwordValidator.reset(); pinValidator.reset(); pathValidator.reset(); } public void loginAction(ActionEvent event) { boolean inputValid = false; try { clearError(); ValidationResult validationRes = validateAll(); inputValid = !validationRes.isError() && checkUserExists(); } catch (NoPeerConnectionException e) { inputValid = false; setError("Connection to the network failed."); } if (inputValid) { Task<ResultStatus> task = createLoginTask(); new Thread(task).start(); } } private ValidationResult validateAll() { return (usernameValidator.validate() == ValidationResult.OK & passwordValidator.validate() == ValidationResult.OK & pinValidator.validate() == ValidationResult.OK & pathValidator.validate() == ValidationResult.OK ) ? ValidationResult.OK : ValidationResult.ERROR; } private boolean checkUserExists() throws NoPeerConnectionException { String username = txtUsername.getText().trim(); if (!userManager.isRegistered(username)) { setError("This user profile does not exist."); return false; } return true; } public ResultStatus loginUser(final String username, final String password, final String pin, final Path path) { try { return userManager.loginUser(username, password, pin, path); } catch (NoPeerConnectionException e) { return ResultStatus.error("Could not login user because connection to network failed."); } } private Task<ResultStatus> createLoginTask() { Task<ResultStatus> task = new Task<ResultStatus>() { // credentials final String username = getUsername(); final String password = txtPassword.getText(); final String pin = txtPin.getText(); final Path path = Paths.get(txtRootPath.getText().trim()); @Override public ResultStatus call() { return loginUser(username, password, pin, path); } }; task.setOnScheduled(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { grdForm.disableProperty().bind(task.runningProperty()); installProgressIndicator(); } }); task.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { onLoginFailed(ResultStatus.error("Could not login user.")); } }); task.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { ResultStatus result = task.getValue(); if (result.isOk()) { onLoginSucceeded(); } else { onLoginFailed(result); } } }); return task; } private void onLoginFailed(ResultStatus result) { logger.error("Login task failed: {}", result.getErrorMessage()); Platform.runLater(() -> { uninstallProgressIndicator(); grdForm.disableProperty().unbind(); grdForm.requestLayout(); setError(result.getErrorMessage()); }); } private void onLoginSucceeded() { logger.debug("Login task succeeded: user {} logged in.", getUsername()); saveLoginConfig(); initializeServices(); resetForm(); hideWindow(); } private void initializeServices() { try { ClientContext ctx = clientContext.get(); ctx.getActionExecutor().start(); // register for local/remote events ctx.getFolderWatchService().addFileEventListener(ctx.getFileEventManager()); ctx.getNodeManager().getNode().getFileManager().subscribeFileEvents(ctx.getFileEventManager()); ctx.getFolderWatchService().start(userConfig.getRootPath()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void saveLoginConfig() { try { userConfig.setUsername(getUsername()); userConfig.setRootPath(Paths.get(txtRootPath.getText())); if (chbAutoLogin.isSelected()) { userConfig.setPassword(txtPassword.getText()); userConfig.setPin(txtPin.getText()); userConfig.setAutoLogin(true); } else { userConfig.setPassword(""); userConfig.setPin(""); userConfig.setAutoLogin(false); } } catch (IOException ioex) { logger.warn("Could not save login settings: {}", ioex.getMessage()); setError("Could not save login settings."); } } private void installProgressIndicator() { Platform.runLater(() -> { // center indicator with respect to the grid double xOffset = piProgress.getWidth() / 2.0; double yOffset = piProgress.getHeight() / 2.0; double x = grdForm.getWidth() / 2.0 - xOffset; double y = grdForm.getHeight() / 2.0 - yOffset; piProgress.relocate(x, y); // show piProgress.setVisible(true); }); } private void uninstallProgressIndicator() { Platform.runLater(() -> { piProgress.setVisible(false); }); } public void registerAction(ActionEvent event) { logger.debug("Navigate to register view."); fNavigationService.navigate(ViewNames.REGISTER_VIEW); } public void changeRootPathAction(ActionEvent event) { String path = txtRootPath.getText(); Window toOpenDialog = grdForm.getScene().getWindow(); path = SelectRootPathUtils.showDirectoryChooser(path, toOpenDialog); txtRootPath.setText(path); } public void navigateBackAction(ActionEvent event) { logger.debug("Navigate back."); fNavigationService.navigateBack(); } private void hideWindow() { Runnable close = new Runnable() { @Override public void run() { // not not quit application when stage closes Platform.setImplicitExit(false); // hide stage Stage stage = (Stage) grdForm.getScene().getWindow(); stage.close(); } }; if (Platform.isFxApplicationThread()) { close.run(); } else { Platform.runLater(close); } } private String getUsername() { return txtUsername.getText().trim(); } private void setError(String error) { lblError.setText(error); } private void clearError() { lblError.setText(""); } @Inject public void setUserConfig(UserConfig userConfig) { this.userConfig = userConfig; } }
package org.pentaho.ui.xul.gwt.tags; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.pentaho.gwt.widgets.client.listbox.CustomListBox; import org.pentaho.gwt.widgets.client.listbox.ListItem; import org.pentaho.gwt.widgets.client.utils.StringUtils; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulDomException; import org.pentaho.ui.xul.XulEventSource; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.components.XulMenuList; import org.pentaho.ui.xul.containers.XulMenupopup; import org.pentaho.ui.xul.containers.XulRoot; import org.pentaho.ui.xul.dom.Document; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer; import org.pentaho.ui.xul.gwt.GwtXulHandler; import org.pentaho.ui.xul.gwt.GwtXulParser; import org.pentaho.ui.xul.gwt.binding.GwtBindingContext; import org.pentaho.ui.xul.gwt.binding.GwtBindingMethod; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.ChangeListener; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; public class GwtMenuList<T> extends AbstractGwtXulContainer implements XulMenuList<T> { static final String ELEMENT_NAME = "menulist"; //$NON-NLS-1$ private boolean editable; public static void register() { GwtXulParser.registerHandler(ELEMENT_NAME, new GwtXulHandler() { public Element newInstance() { return new GwtMenuList(); } }); } private Label label; private CustomListBox listbox; private String bindingProperty; private boolean loaded = false; private boolean suppressLayout = false; private boolean inLayoutProcess = false; private String previousSelectedItem = null; private String onCommand; private SimplePanel wrapper = null; public GwtMenuList() { super(ELEMENT_NAME); wrapper = new SimplePanel() { @Override public void setHeight(String height) { } @Override public void setWidth(String width) { super.setWidth(width); listbox.setWidth(width); } }; listbox = new CustomListBox(); wrapper.add(listbox); managedObject = wrapper; listbox.addChangeListener(new ChangeListener(){ public void onChange(Widget arg0) { /* * This actionlistener is fired at parse time when elements are added. * We'll ignore that call by checking a variable set to true post parse time */ if (!loaded) { return; } fireSelectedEvents(); } }); } public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) { super.init(srcEle, container); setBinding(srcEle.getAttribute("pen:binding")); setOnCommand(srcEle.getAttribute("oncommand")); } public String getBinding() { return bindingProperty; } public Collection getElements() { List<Object> vals = new ArrayList<Object>(); for(int i=0; i<listbox.getItems().size(); i++){ vals.add(listbox.getItems().get(i).getValue()); } return vals; } public int getSelectedIndex() { return listbox.getSelectedIndex(); } public String getSelectedItem() { ListItem selectedItem = listbox.getSelectedItem(); return (selectedItem == null) ? null : listbox.getSelectedItem().getValue().toString(); } public void replaceAllItems(Collection tees) throws XulDomException { throw new RuntimeException("Not implemented"); } public void setBinding(String binding) { this.bindingProperty = binding; } public void setElements(Collection<T> elements) { try{ suppressLayout = true; listbox.setSuppressLayout(true); XulMenupopup popup = getPopupElement(); for (XulComponent menuItem : popup.getChildNodes()) { popup.removeChild(menuItem); } if(elements == null || elements.size() == 0){ this.suppressLayout = false; layout(); return; } for (T t : elements) { GwtMenuitem item = new GwtMenuitem(popup); String attribute = getBinding(); if (!StringUtils.isEmpty(attribute)) { item.setLabel(extractLabel(t)); } popup.addChild(item); } this.suppressLayout = false; listbox.setSuppressLayout(false); layout(); } catch(Exception e){ System.out.println(e.getMessage()); e.printStackTrace(); } } public GwtMenupopup getPopupElement() { for (Element comp : getChildNodes()) { if (comp instanceof GwtMenupopup) { return (GwtMenupopup) comp; } } throw new IllegalStateException("menulist is missing a menupopup child element"); } public void setOncommand(final String command) { this.listbox.addChangeListener(new ChangeListener(){ public void onChange(Widget arg0) { /* * This actionlistener is fired at parse time when elements are added. * We'll ignore that call by checking a variable set to true post parse time */ if (!loaded) { return; } Document doc = getDocument(); XulRoot window = (XulRoot) doc.getRootElement(); final XulDomContainer con = window.getXulDomContainer(); try{ con.invoke(command, new Object[] {}); } catch(XulException e){ Window.alert("MenuList onChange error: "+e.getMessage()); } fireSelectedEvents(); } }); } public void setSelectedIndex(int idx) { listbox.setSelectedIndex(idx); } public void setSelectedItem(T t) { //this is coming in as a string for us. // int i=0; // for(Object o : getElements()){ // if(((String) o).equals(extractLabel(t))){ // setSelectedIndex(i); int i=0; for(Object o : getElements()){ if(((String) o).equals((String)t)){ setSelectedIndex(i); } i++; } } private String extractLabel(T t) { String attribute = getBinding(); if (StringUtils.isEmpty(attribute) || !(t instanceof XulEventSource)) { return t.toString(); } else { try { GwtBindingMethod m = GwtBindingContext.typeController.findGetMethod(t, attribute); if(m == null){ System.out.println("could not find getter method for "+t+"."+attribute); } return m.invoke(t, new Object[]{}).toString(); } catch (Exception e) { throw new RuntimeException(e); } } } public void adoptAttributes(XulComponent component) { } private int selectedIndex = -1; private void fireSelectedEvents(){ GwtMenuList.this.changeSupport.firePropertyChange("selectedItem", previousSelectedItem, (String) getSelectedItem()); int prevSelectedIndex = selectedIndex; selectedIndex = getSelectedIndex(); GwtMenuList.this.changeSupport.firePropertyChange("selectedIndex", prevSelectedIndex, selectedIndex); previousSelectedItem = (String) getSelectedItem(); if(StringUtils.isEmpty(GwtMenuList.this.getOnCommand()) == false && prevSelectedIndex != selectedIndex){ try { GwtMenuList.this.getXulDomContainer().invoke(GwtMenuList.this.getOnCommand(), new Object[] {}); } catch (XulException e) { e.printStackTrace(); } } } @Override public void layout() { inLayoutProcess = true; if(suppressLayout){ inLayoutProcess = false; return; } int currentSelectedIndex = getSelectedIndex(); Object currentSelectedItem = listbox.getSelectedItem(); GwtMenupopup popup = getPopupElement(); listbox.setSuppressLayout(true); this.listbox.removeAll(); GwtMenuitem selectedItem = null; //capture first child as default selection boolean firstChild = true; for (XulComponent item : popup.getChildNodes()) { GwtMenuitem tempItem = ((GwtMenuitem) item); listbox.addItem(tempItem.getLabel()); if (tempItem.isSelected() || firstChild) { selectedItem = tempItem; firstChild = false; } } listbox.setSuppressLayout(false); inLayoutProcess = false; if (selectedItem != null) { //if first setting it to the currently selected one will not fire event. //manually firing here if(this.getSelectedItem().equals(selectedItem.getLabel())){ fireSelectedEvents(); } setSelectedItem((T) selectedItem.getLabel()); } if(getSelectedIndex() > -1){ if(currentSelectedIndex < listbox.getItems().size()) { int index = getIndexForItem(currentSelectedItem); if(index > 0) { listbox.setSelectedIndex(currentSelectedIndex); } else { listbox.setSelectedIndex(listbox.getSelectedIndex()); } } else { listbox.setSelectedIndex(listbox.getSelectedIndex()); } } loaded = true; } @Override public void resetContainer(){ this.layout(); } public String getOnCommand() { return onCommand; } public void setOnCommand(String command) { this.onCommand = command; } public void setEditable(boolean editable) { this.listbox.setEditable(editable); this.editable = editable; } public boolean getEditable() { return editable; } public String getValue() { return getSelectedItem(); } public void setValue(String value) { for(ListItem item : listbox.getItems()){ if(item.getValue().equals(value)){ listbox.setSelectedItem(item); return; } } } private int getIndexForItem(Object obj) { int index = -1; if(obj != null){ for(ListItem item:listbox.getItems()) { index++; if(item.getValue() != null && item.getValue().equals(obj.toString())) { return index; } } } return index; } }
package com.technicolor.eloyente; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Descriptor; import hudson.model.Item; import hudson.model.Items; import hudson.model.Project; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.jivesoftware.smack.Connection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.packet.DiscoverItems; import org.jivesoftware.smackx.pubsub.LeafNode; import org.jivesoftware.smackx.pubsub.Node; import org.jivesoftware.smackx.pubsub.PubSubManager; import org.jivesoftware.smackx.pubsub.Subscription; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; /** * @author Juan Luis Pardo Gonzalez * @author Isabel Fernandez Diaz */ public class ElOyente extends Trigger<Project> { private String server; private String user; private String password; private static Project project; private final static Map<String, Connection> connections = new HashMap<String, Connection>(); /** * Constructor for elOyente. * * It uses the Descriptor to set the fields required later on. The * Descriptor will bring the information set in the main configuration to * the particular job. */ @DataBoundConstructor public ElOyente() { super(); server = this.getDescriptor().server; user = this.getDescriptor().user; password = this.getDescriptor().password; } /** * Method used for starting a job. * * This method is called when the Save or Apply button are pressed in a job * configuration in case this plugin is activated. * * It checks if there is all the information required for an XMPP connection * in the main configuration and creates the connection. * * @param project * @param newInstance */ @Override public void start(Project project, boolean newInstance) { server = this.getDescriptor().server; user = this.getDescriptor().user; password = this.getDescriptor().password; ElOyente.project = project; ArrayList nodes = new ArrayList(); System.out.println("Con datos: " + !connections.isEmpty()); System.out.println("Conexion existente: " + connections.containsKey(project.getName())); System.out.println("Reloading: " + getDescriptor().reloading); try { /* If there are old connections, and there is a connection for this job, and it's reloading then we stop the connection, delete the old subscription and store the node name in order to recreate the connection later with the new parameters. */ if (!connections.isEmpty() && connections.containsKey(project.getName()) && getDescriptor().reloading) { nodes = deleteSubscriptions(connections.get(project.getName()), this.getDescriptor().olduser, project.getName()); connections.get(project.getName()).disconnect(); } /* If parameters are not empty it will create a connection and add it to the Map that stores the connections for later uses. * It will also recreate the subscription based on the saved nodes and the new parameters. */ if (server != null && !server.isEmpty() && user != null && !user.isEmpty() && password != null && !password.isEmpty()) { if (connections.containsKey(project.getName()) && connections.get(project.getName()).getUser().split("@")[0].equals(user)) { System.err.println("\n\n\nproject.getName() = " + project.getName()); System.err.println("\n\n\nuser = " + user); System.err.println(connections.get(project.getName()).getUser().split("@")[0]); connections.get(project.getName()).disconnect(); } ConnectionConfiguration config = new ConnectionConfiguration(server); Connection con = new XMPPConnection(config); con.connect(); if (con.isConnected()) { try { con.login(user, password, project.getName()); connections.put(project.getName(), con); if (getDescriptor().reloading) { recreateSubscription(connections.get(project.getName()), user, nodes, project.getName()); } } catch (XMPPException ex) { System.err.println("Login error"); ex.printStackTrace(System.err); } } } } catch (XMPPException ex) { System.err.println("Couldn't establish the connection, or already connected"); ex.printStackTrace(System.err); } } /** * * Deletes the subscriptions that a job has when the parameters are changed * in the main configuration. * * This method deletes the subscriptions of a user from the nodes it is * subscribed, and saves the name of those nodes in order to create new * subscriptions for the new user. * * @param con * @param olduser * @param resource * @return * @throws XMPPException */ public ArrayList deleteSubscriptions(Connection con, String olduser, String resource) throws XMPPException { ArrayList nodes = new ArrayList(); PubSubManager mgr = new PubSubManager(con); Iterator it = mgr.getSubscriptions().iterator(); while (it.hasNext()) { Subscription sub = (Subscription) it.next(); String JID = sub.getJid(); String JIDuser = JID.split("@")[0]; String JIDresource = JID.split("@")[1].split("/")[1]; if (JIDuser.equals(olduser) && JIDresource.equals(resource)) { Node node = mgr.getNode(sub.getNode()); node.unsubscribe(JID); nodes.add(node.getId()); } } return nodes; } /** * Recreates the subscriptions with the new parameters introduced in the * main config. * * * @param con * @param newuser * @param nodes * @param resource * @throws XMPPException */ public void recreateSubscription(Connection con, String newuser, ArrayList nodes, String resource) throws XMPPException { PubSubManager mgr = new PubSubManager(con); Iterator it = nodes.iterator(); while (it.hasNext()) { Node node = mgr.getNode((String) it.next()); String JID1 = con.getUser(); node.subscribe(JID1); //listen(node,this); } } // public void listen(Node node, Trigger trigger) { // ItemEventCoordinator itemEventCoordinator = new ItemEventCoordinator(node.getId(), trigger); // node.addItemEventListener(itemEventCoordinator); @Override public void run() { // super.run(); if (!project.getAllJobs().isEmpty()) { Iterator iterator = project.getAllJobs().iterator(); while (iterator.hasNext()) { ((Project) iterator.next()).scheduleBuild(null); } } //super.run(); } /** * Retrieves the descriptor for the plugin elOyente. * * Used by the plugin to set and work with the main configuration. * * @return DescriptorImpl */ @Override public final DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } * <tt>src/main/resources/hudson/plugins/eloyente/elOyente/*.jelly</tt> for * the actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends TriggerDescriptor { /** * To persist global configuration information, simply store it in a * field and call save(). * * <p> If you don't want fields to be persisted, use <tt>transient</tt>. */ private String server, oldserver; private String user, olduser; private String password, oldpassword; private boolean reloading = false; /** * Brings the persisted configuration in the main configuration. * * Brings the persisted configuration in the main configuration. */ public DescriptorImpl() { load(); oldserver = this.getServer(); olduser = this.getUser(); oldpassword = this.getPassword(); } /** * Used to persist the global configuration. * * * This method is used to set the field for the checkbox that activates * the plugin in the job configuration. * * @return boolean * @param item */ @Override public boolean isApplicable(Item item) { return true; } /** * Used to persist the global configuration. * * * This method is used to set the field for the checkbox that activates * the plugin in the job configuration. * * @return String */ @Override public String getDisplayName() { return "XMPP triggered plugin"; } /** * Used to persist the global configuration. * * * global.jelly calls this method to obtain the value of field * server.admin * * @param req * @param formData * @return boolean * @throws Descriptor.FormException */ @Override public boolean configure(StaplerRequest req, JSONObject formData) throws Descriptor.FormException { // To persist global configuration information, // set that to properties and call save(). server = formData.getString("server"); user = formData.getString("user"); password = formData.getString("password"); // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this) //report(); save(); reloadJobs(); oldserver = server; olduser = user; oldpassword = password; return super.configure(req, formData); } /** * This method reloads the jobs that are using ElOyente applying the new * main configuration. * * Checks if the parameters username, password and server of the main * configuration have changed, if so it calls the method start() of all * those jobs that are using ElOyente in order to connect to the server * with the new credentials. */ public void reloadJobs() { if (!server.equals(oldserver) || !user.equals(olduser) || !password.equals(oldpassword)) { Iterator it2 = (Jenkins.getInstance().getItems()).iterator(); while (it2.hasNext()) { AbstractProject job = (AbstractProject) it2.next(); Object instance = (ElOyente) job.getTriggers().get(this); if (instance != null) { System.out.println(job.getName() + ": Yo tengo el plugin"); reloading = true; File directoryConfigXml = job.getConfigFile().getFile().getParentFile(); try { Items.load(job.getParent(), directoryConfigXml); } catch (IOException ex) { Logger.getLogger(ElOyente.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println(job.getName() + ": Yo no tengo el plugin"); } reloading = false; } } } /** * Used for logging to the log file. * * This method reports information related to XMPPadmin events like * "Available Nodes", connection information, etc. It creates a * connection to take the required data for reporting and it closes it * after. It is used in the main configuration every time the Save or * Apply buttons are pressed. * */ public void report() { Logger logger = Logger.getLogger("com.technicolor.eloyente"); //Logger loger = Logger.getLogger(ElOyente.class.getName()); if (server != null && !server.isEmpty() && user != null && !user.isEmpty() && password != null && !password.isEmpty()) { try { //Connection ConnectionConfiguration config = new ConnectionConfiguration(server); PubSubManager mgr; Connection con = new XMPPConnection(config); con.connect(); logger.log(Level.INFO, "Connection established"); if (con.isConnected()) { //Login con.login(user, password, "Global"); logger.log(Level.INFO, "JID: {0}", con.getUser()); logger.log(Level.INFO, "{0} has been logged to openfire!", user); //Log the availables nodes mgr = new PubSubManager(con); DiscoverItems items = mgr.discoverNodes(null); Iterator<DiscoverItems.Item> iter = items.getItems(); logger.log(Level.INFO, "NODES: while (iter.hasNext()) { DiscoverItems.Item i = iter.next(); logger.log(Level.INFO, "Node: {0}", i.getNode()); System.out.println("Node: " + i.toXML()); System.out.println("NodeName: " + i.getNode()); } logger.log(Level.INFO, "END NODES: //Disconnection con.disconnect(); } } catch (XMPPException ex) { System.err.println(ex.getXMPPError().getMessage()); } } } /** * This method returns the URL of the XMPP server. * * * global.jelly calls this method to obtain the value of field server. * * @return server */ public String getServer() { return server; } /** * This method returns the username for the XMPP connection. * * * global.jelly calls this method to obtain the value of field user. * * @return user */ public String getUser() { return user; } /** * This method returns the password for the XMPP connection. * * * global.jelly calls this method to obtain the value of field password. * * @return password */ public String getPassword() { return password; } public boolean getReloading() { return reloading; } public String getOldServer() { return oldserver; } public String getOldUser() { return olduser; } public String getOldPassword() { return oldpassword; } /** * Performs on-the-fly validation of the form field 'server'. * * This method checks if the connection to the XMPP server specified is * available. It shows a notification describing the status of the * server connection. * * @param server */ public FormValidation doCheckServer(@QueryParameter String server) { try { ConnectionConfiguration config = new ConnectionConfiguration(server); Connection con = new XMPPConnection(config); if (server.isEmpty()) { return FormValidation.warningWithMarkup("No server specified"); } con.connect(); if (con.isConnected()) { con.disconnect(); return FormValidation.okWithMarkup("Connection available"); } return FormValidation.errorWithMarkup("Couldn't connect"); } catch (XMPPException ex) { return FormValidation.errorWithMarkup("Couldn't connect"); } } /** * Performs on-the-fly validation of the form fields 'user' and * 'password'. * * This method checks if the user and password of the XMPP server * specified are correct and valid. It shows a notification describing * the status of the login. * * @param user * @param password */ public FormValidation doCheckPassword(@QueryParameter String user, @QueryParameter String password, @QueryParameter String server) { ConnectionConfiguration config = new ConnectionConfiguration(server); Connection con = new XMPPConnection(config); if ((user.isEmpty() || password.isEmpty()) || server.isEmpty()) { return FormValidation.warningWithMarkup("Not authenticated"); } try { con.connect(); con.login(user, password); if (con.isAuthenticated()) { con.disconnect(); return FormValidation.okWithMarkup("Authentication succed"); } return FormValidation.warningWithMarkup("Not authenticated"); } catch (XMPPException ex) { return FormValidation.errorWithMarkup("Authentication failed"); } } public ListBoxModel doFillNodesAvailableItems() throws XMPPException { ListBoxModel items = new ListBoxModel(); Connection con = connections.get(project.getName()); PubSubManager mgr = new PubSubManager(con); DiscoverItems it = mgr.discoverNodes(null); Iterator<DiscoverItems.Item> iter = it.getItems(); if (con.isAuthenticated()) { while (iter.hasNext()) { DiscoverItems.Item i = iter.next(); items.add(i.getNode()); System.out.println("Node shown: " + i.getNode()); } } else { System.out.println("No Logeado"); } return items; } public FormValidation doSubscribe(@QueryParameter("nodesAvailable") final String nodesAvailable) { Connection con = connections.get(project.getName()); PubSubManager mgr = new PubSubManager(con); try { LeafNode node = (LeafNode) mgr.getNode(nodesAvailable); ItemEventCoordinator itemEventCoordinator = new ItemEventCoordinator(nodesAvailable); node.addItemEventListener(itemEventCoordinator); String JID = con.getUser(); node.subscribe(JID); return FormValidation.ok(con.getUser() + " Subscribed to " + nodesAvailable + " with resource " + project.getName()); } catch (Exception e) { return FormValidation.error("Couldn't subscribe to " + nodesAvailable); } } } }
package se.simbio.encryption; import android.R.string; import android.util.Base64; import android.util.Log; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; /** * A class to make more easy simple encrypt routines */ public class Encryption { private static final String TAG = "Encryption"; private String mCharsetName = "UTF8"; private int mBase64Mode = Base64.DEFAULT; //type of aes key that will be created private String SECRET_KEY_TYPE = "PBKDF2WithHmacSHA1"; //value used for salting....can be anything private String salt = "some_salt"; //length of key private int KEY_LENGTH = 128; //number of times the password is hashed private int ITERATION_COUNT = 65536; //main family of aes private String mAlgorithm = "AES"; /** * @return the charset name */ public String getCharsetName() { return mCharsetName; } /** * @param charsetName the new charset name */ public void setCharsetName(String charsetName) { mCharsetName = charsetName; } /** * @return the mAlgorithm used */ public String getAlgorithm() { return mAlgorithm; } /** * @param algorithm the mAlgorithm to be used */ public void setAlgorithm(String algorithm) { mAlgorithm = algorithm; } /** * @return the Base 64 mode */ public int getBase64Mode() { return mBase64Mode; } /** * @param base64Mode set the base 64 mode */ public void setBase64Mode(int base64Mode) { mBase64Mode = base64Mode; } /** * Encrypt a {@link string} * * @param key the {@link String} key * @param data the {@link String} to be encrypted * * @return the encrypted {@link String} or <code>null</code> if occur some error */ public String encrypt(String key, String data) { if (key == null || data == null) return null; try { SecretKey secretKey = getSecretKey(hashTheKey(key)); byte[] dataBytes = data.getBytes(mCharsetName); Cipher cipher = Cipher.getInstance(mAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.encodeToString(cipher.doFinal(dataBytes), mBase64Mode); } catch (Exception e) { Log.e(TAG, e.toString()); return null; } } /** * Decrypt a {@link string} * * @param key the {@link String} key * @param data the {@link String} to be decrypted * * @return the decrypted {@link String} or <code>null</code> if occur some error */ public String decrypt(String key, String data) { if (key == null || data == null) return null; try { byte[] dataBytes = Base64.decode(data, mBase64Mode); SecretKey secretKey = getSecretKey(hashTheKey(key)); Cipher cipher = Cipher.getInstance(mAlgorithm); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes)); return new String(dataBytesDecrypted); } catch (Exception e) { Log.e(TAG, e.toString()); return null; } } /** * creates a 128bit salted aes key * * @param key encoded input key * @return aes 128 bit salted key * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException * @throws InvalidKeySpecException */ private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { SecretKeyFactory factory = null; factory = SecretKeyFactory.getInstance(SECRET_KEY_TYPE); KeySpec spec = new PBEKeySpec(key, salt.getBytes(mCharsetName), ITERATION_COUNT, KEY_LENGTH); SecretKey tmp = factory.generateSecret(spec); return new SecretKeySpec(tmp.getEncoded(), mAlgorithm); } /** * takes in a simple string and performs an sha1 hash * that is 128 bits long...we then base64 encode it * and return the char array * * @param key simple inputted string * @return sha1 base64 encoded representation * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException */ private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(key.getBytes(mCharsetName)); return Base64.encodeToString(md.digest(),Base64.NO_PADDING).toCharArray(); } }
package org.ethereum.net; import org.ethereum.core.Block; import org.ethereum.core.ImportResult; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.facade.Blockchain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigInteger; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import static java.lang.Thread.sleep; import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.core.ImportResult.NO_PARENT; import static org.ethereum.core.ImportResult.SUCCESS; /** * The processing queue for blocks to be validated and added to the blockchain. * This class also maintains the list of hashes from the peer with the heaviest sub-tree. * Based on these hashes, blocks are added to the queue. * * @author Roman Mandeleil * @since 27.07.2014 */ @Component public class BlockQueue { private static final Logger logger = LoggerFactory.getLogger("blockqueue"); /** * The list of hashes of the heaviest chain on the network, * for which this client doesn't have the blocks yet */ private Deque<byte[]> blockHashQueue = new ArrayDeque<>(); /** * Queue with blocks to be validated and added to the blockchain */ private PriorityBlockingQueue<Block> blockReceivedQueue = new PriorityBlockingQueue<>(1000, new BlockByNumberComparator()); /** * Highest known total difficulty, representing the heaviest chain on the network */ private BigInteger highestTotalDifficulty; /** * Last block in the queue to be processed */ private Block lastBlock; private Timer timer = new Timer("BlockQueueTimer"); @Autowired Blockchain blockchain; public BlockQueue() { Runnable queueProducer = new Runnable(){ @Override public void run() { produceQueue(); } }; Thread t=new Thread (queueProducer); t.start(); } /** * Processing the queue adding blocks to the chain. */ private void produceQueue() { while (1==1){ try { Block block = blockReceivedQueue.take(); logger.info("BlockQueue size: {}", blockReceivedQueue.size()); ImportResult importResult = blockchain.tryToConnect(block); // In case we don't have a parent on the chain // return the try and wait for more blocks to come. if (importResult == NO_PARENT){ logger.info("No parent on the chain for block.number: [{}]", block.getNumber()); blockReceivedQueue.add(block); sleep(2000); } if (importResult == SUCCESS) logger.info("Success importing: block number: {}", block.getNumber()); } catch (Throwable e) { logger.error("Error: {} ", e.getMessage()); } } } /** * Add a list of blocks to the processing queue. * The list is validated by making sure the first block in the received list of blocks * is the next expected block number of the queue. * * The queue is configured to contain a maximum number of blocks to avoid memory issues * If the list exceeds that, the rest of the received blocks in the list are discarded. * * @param blockList - the blocks received from a peer to be added to the queue */ public void addBlocks(List<Block> blockList) { for (Block block : blockList) blockReceivedQueue.put(block); lastBlock = blockList.get(blockList.size() - 1); logger.info("Blocks waiting to be proceed: queue.size: [{}] lastBlock.number: [{}]", blockReceivedQueue.size(), lastBlock.getNumber()); } /** * adding single block to the queue usually * a result of a NEW_BLOCK message announce. * * @param block - new block */ public void addBlock(Block block) { blockReceivedQueue.add(block); lastBlock = block; logger.debug("Blocks waiting to be proceed: queue.size: [{}] lastBlock.number: [{}]", blockReceivedQueue.size(), lastBlock.getNumber()); } /** * Returns the last block in the queue. If the queue is empty, * this will return the last block added to the blockchain. * * @return The last known block this client on the network * and will never return <code>null</code> as there is * always the Genesis block at the start of the chain. */ public Block getLastBlock() { if (blockReceivedQueue.isEmpty()) return blockchain.getBestBlock(); return lastBlock; } /** * Reset the queue of hashes of blocks to be retrieved * and add the best hash to the top of the queue * * @param hash - the best hash */ public void setBestHash(byte[] hash) { blockHashQueue.clear(); blockHashQueue.addLast(hash); } /** * Returns the last added hash to the queue representing * the latest known block on the network * * @return The best hash on the network known to the client */ public byte[] getBestHash() { return blockHashQueue.peekLast(); } public void addHash(byte[] hash) { blockHashQueue.addLast(hash); if (logger.isTraceEnabled()) { logger.trace("Adding hash to a hashQueue: [{}], hash queue size: {} ", Hex.toHexString(hash).substring(0, 6), blockHashQueue.size()); } } public void returnHashes(List<ByteArrayWrapper> hashes) { if (hashes.isEmpty()) return; logger.info("Hashes remained uncovered: hashes.size: [{}]", hashes.size()); ListIterator iterator = hashes.listIterator(hashes.size()); while (iterator.hasPrevious()) { byte[] hash = ((ByteArrayWrapper) iterator.previous()).getData(); if (logger.isDebugEnabled()) logger.debug("Return hash: [{}]", Hex.toHexString(hash)); blockHashQueue.addLast(hash); } } public void addNewBlockHash(byte[] hash) { blockHashQueue.addFirst(hash); } /** * Return a list of hashes from blocks that still need to be downloaded. * * @return A list of hashes for which blocks need to be retrieved. */ public List<byte[]> getHashes() { List<byte[]> hashes = new ArrayList<>(); while (!blockHashQueue.isEmpty() && hashes.size() < CONFIG.maxBlocksAsk()) { hashes.add(blockHashQueue.removeLast()); } return hashes; } // a bit ugly but really gives // good result public void logHashQueueSize() { logger.info("Block hashes list size: [{}]", blockHashQueue.size()); } private class BlockByNumberComparator implements Comparator<Block> { @Override public int compare(Block o1, Block o2) { if (o1 == null || o2 == null) throw new NullPointerException(); if (o1.getNumber() > o2.getNumber()) return 1; if (o1.getNumber() < o2.getNumber()) return -1; return 0; } } public BigInteger getHighestTotalDifficulty() { return highestTotalDifficulty; } public void setHighestTotalDifficulty(BigInteger highestTotalDifficulty) { this.highestTotalDifficulty = highestTotalDifficulty; } /** * Returns the current number of blocks in the queue * * @return the current number of blocks in the queue */ public int size() { return blockReceivedQueue.size(); } public boolean isHashesEmpty() { return blockHashQueue.size() == 0; } public void clear() { this.blockHashQueue.clear(); this.blockReceivedQueue.clear(); } /** * Cancel and purge the timer-thread that * processes the blocks in the queue */ public void close() { timer.cancel(); timer.purge(); } }
import java.lang.Exception; import java.sql.*; public class AddressList { private ArrayList<Address>; private getAll(){ // Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/addressbook?user=addressbook&password=addressbook"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM address;"); while (rs.next()) { Address temp = new Address(); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("name"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); temp.setName = rs.getString("christianname"); out.println(rs.getString("name")); } rs.close(); stmt.close(); conn.close(); } }
package com.lotsofun.farkle; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class FarkleUI extends JFrame implements MouseListener { private static final long serialVersionUID = 1L; public Die[] dice = new Die[6]; public JButton rollBtn = new JButton("Roll Dice"); public JButton bankBtn = new JButton("Bank Score"); public JButton selectAllBtn = new JButton("Select All"); public FarkleController controller; public JLabel playerNameLabel = new JLabel(""); public JLabel[] scoreLabels = new JLabel[10]; public JLabel[] playerScores = new JLabel[10]; public JLabel gameScoreTitle = new JLabel("Total Score: "); public JLabel gameScore = new JLabel("0"); public JLabel highScoreTitle = new JLabel("High Score: "); public JLabel highScore = new JLabel("5000"); public JLabel runningScore = new JLabel(); public ArrayList<URL> rollSounds = new ArrayList<URL>(); public ArrayList<URL> bankSounds = new ArrayList<URL>(); public URL bonusSound; public URL gSound; public AudioInputStream audioStream = null; public Color greenBackground = new Color(35, 119, 34); //My Frame Globals JFrame frame = new JFrame("Farkle"); public JLabel playerModeSelectLabel = new JLabel(" Select Player Mode:"); public JLabel singlePlayerLabel = new JLabel("One Player Mode", SwingConstants.CENTER); public JLabel multiplayerLabel = new JLabel("Two Player Mode", SwingConstants.CENTER); public JLabel playerTypeSelectLabel = new JLabel(" Select Opponent Type:"); public JLabel humanPlayerLabel = new JLabel("Human Opponent", SwingConstants.CENTER); public JLabel computerPlayerLabel = new JLabel("Computer Opponent", SwingConstants.CENTER); public JLabel gameModeOptionTitle = new JLabel("Game Mode Options", SwingConstants.CENTER); public JPanel playerOneNamePanel = new JPanel(); public JPanel playerTwoNamePanel = new JPanel(); public JPanel playerModeSelectionPanel = new JPanel(); public JPanel playerTypeSelectionPanel = new JPanel(); JLabel playerNamesLabel = new JLabel ("Enter Player Names:"); JLabel playerOneNameLabel = new JLabel("Player One:"); JTextField playerOneName = new JTextField(5); JLabel playerTwoNameLabel = new JLabel("Player Two:"); JTextField playerTwoName = new JTextField(5); JButton startButton = new JButton("Start"); JButton closeButton = new JButton("Close"); Color defaultColor = singlePlayerLabel.getBackground(); /** * Constructor Get a reference to the controller object and fire up the UI * * @param f */ public FarkleUI(FarkleController f) { controller = f; initUI(); } /** * Build the UI */ public void initUI() { // Initialize the sounds rollSounds.add(getClass().getResource("/sounds/roll1.wav")); rollSounds.add(getClass().getResource("/sounds/roll2.wav")); rollSounds.add(getClass().getResource("/sounds/roll3.wav")); rollSounds.add(getClass().getResource("/sounds/roll4.wav")); gSound = getClass().getResource("/sounds/roll5.wav"); bankSounds.add(getClass().getResource("/sounds/bank1.wav")); bankSounds.add(getClass().getResource("/sounds/bank2.wav")); bankSounds.add(getClass().getResource("/sounds/bank3.wav")); bankSounds.add(getClass().getResource("/sounds/bank4.wav")); bonusSound = getClass().getResource("/sounds/bonus.wav"); // Pass a reference to the controller controller.setUI(this); // TODO: CuBr - Write a test case for the window title // based on player mode // Create and set up the main Window frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(1024, 768)); frame.setResizable(false); GridLayout layout = new GridLayout(1, 3, 10, 10); // Hide the gridlines layout.setHgap(0); layout.setVgap(0); frame.setLayout(layout); //Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem newAction = new JMenuItem("New"); JMenuItem resetAction = new JMenuItem("Reset"); JMenuItem exitAction = new JMenuItem("Exit"); fileMenu.add(newAction); fileMenu.add(resetAction); fileMenu.add(exitAction); newAction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { controller.endGame(false, true); } }); resetAction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { controller.endGame(true, false); } }); exitAction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { pullThePlug(); } }); frame.setJMenuBar(menuBar); // Build the UI frame.add(createPlayerPanel()); // Call to create dice frame.add(createDicePanel()); frame.add(createScorePanel()); // Center and display the window frame.setLocationRelativeTo(null); frame.pack(); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2); int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2); frame.setLocation(x, y); frame.setVisible(true); controller.setupGame(); } /* Reduce Reuse Recycle */ public void getGameInformation() { frame.setEnabled(false); final JDialog window = new JDialog(frame); window.setPreferredSize(new Dimension(750, 250)); window.setResizable(false); window.setUndecorated(true); window.setTitle("Game Mode Options"); BorderLayout layout = new BorderLayout(); window.setLayout(layout); controller.tempGameInformation[0] = "S"; controller.tempGameInformation[1] = ""; controller.tempGameInformation[2] = ""; controller.tempGameInformation[3] = ""; //Create panels here JPanel gameModePanel = new JPanel(); gameModePanel.setLayout(new GridLayout(1,2,10,0)); singlePlayerLabel.setName("1"); singlePlayerLabel.setOpaque(true); singlePlayerLabel.setBackground(Color.YELLOW); singlePlayerLabel.addMouseListener(this); multiplayerLabel.setName("2"); multiplayerLabel.setOpaque(true); multiplayerLabel.addMouseListener(this); multiplayerLabel.setBackground(greenBackground); JPanel playerTypePanel = new JPanel(); playerTypePanel.setLayout(new GridLayout(2,1,0,0)); playerModeSelectionPanel.setLayout(new GridLayout(3,1,0,0)); playerModeSelectionPanel.setBackground(greenBackground); playerTypeSelectionPanel.setLayout(new GridLayout(3,1,0,0)); playerTypeSelectionPanel.setBackground(greenBackground); humanPlayerLabel.setName("3"); humanPlayerLabel.setOpaque(true); humanPlayerLabel.addMouseListener(this); humanPlayerLabel.setBackground(greenBackground); computerPlayerLabel.setName("4"); computerPlayerLabel.setOpaque(true); computerPlayerLabel.addMouseListener(this); computerPlayerLabel.setBackground(greenBackground); playerModeSelectLabel.setFont(new Font("Arial Black", Font.PLAIN, 14)); playerModeSelectLabel.setForeground(Color.WHITE); playerModeSelectionPanel.add(playerModeSelectLabel); singlePlayerLabel.setFont(new Font("Arial Black", Font.PLAIN, 12)); playerModeSelectionPanel.add(singlePlayerLabel); multiplayerLabel.setFont(new Font("Arial Black", Font.PLAIN, 12)); multiplayerLabel.setForeground(Color.WHITE); playerModeSelectionPanel.add(multiplayerLabel); playerTypeSelectLabel.setFont(new Font("Arial Black", Font.PLAIN, 14)); playerTypeSelectLabel.setForeground(Color.WHITE); playerTypeSelectionPanel.add(playerTypeSelectLabel); humanPlayerLabel.setFont(new Font("Arial Black", Font.PLAIN, 12)); playerTypeSelectionPanel.add(humanPlayerLabel); computerPlayerLabel.setFont(new Font("Arial Black", Font.PLAIN, 12)); computerPlayerLabel.setForeground(Color.WHITE); playerTypeSelectionPanel.add(computerPlayerLabel); playerTypePanel.add(playerModeSelectionPanel); playerTypePanel.add(playerTypeSelectionPanel); playerTypeSelectionPanel.setVisible(false); JPanel playerNamesPanel = new JPanel(); playerNamesPanel.setLayout(new GridLayout(6,1,0,0)); playerNamesLabel.setFont(new Font("Arial Black", Font.PLAIN, 14)); playerNamesLabel.setForeground(Color.WHITE); playerNamesPanel.add(playerNamesLabel); //set up the playerOneNamePanel playerOneNamePanel.setLayout(new BorderLayout()); playerOneNamePanel.setBackground(greenBackground); playerOneNameLabel.setFont(new Font("Arial Black", Font.PLAIN, 12)); playerOneNameLabel.setForeground(Color.WHITE); playerOneNamePanel.add(playerOneNameLabel, BorderLayout.WEST); playerOneNamePanel.add(playerOneName, BorderLayout.CENTER); playerNamesPanel.add(playerOneNamePanel); //set up the playerTwoNamePanel playerTwoNamePanel.setLayout(new BorderLayout()); playerTwoNamePanel.setBackground(greenBackground); playerTwoNameLabel.setFont(new Font("Arial Black", Font.PLAIN, 12)); playerTwoNameLabel.setForeground(Color.WHITE); playerTwoNamePanel.add(playerTwoNameLabel, BorderLayout.WEST); playerTwoNamePanel.add(playerTwoName, BorderLayout.CENTER); playerNamesPanel.add(playerTwoNamePanel); // Hide the playerTwoNamePanel playerTwoNamePanel.setVisible(false); // Add the player name panels to the gameModePanel.add(playerTypePanel); gameModePanel.add(playerNamesPanel); JPanel buttonPanel = new JPanel(); startButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e){ controller.tempGameInformation[2] = playerOneName.getText(); controller.tempGameInformation[3] = playerTwoName.getText(); if (("Ginuwine").equalsIgnoreCase(controller.tempGameInformation[2])) { try { AudioInputStream audioStream; audioStream = AudioSystem.getAudioInputStream(gSound); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException x) { x.printStackTrace(); } catch (LineUnavailableException y) { y.printStackTrace(); } catch (IOException z) { z.printStackTrace(); } } controller.newGame(); frame.setEnabled(true); frame.setVisible(true); window.dispose(); } }); buttonPanel.add(startButton); closeButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e){pullThePlug();}}); buttonPanel.add(closeButton); // Add a title panel JPanel gameModeTitlePanel = new JPanel(); gameModeTitlePanel.setBackground(Color.WHITE); gameModeOptionTitle.setFont(new Font("Arial Black", Font.PLAIN, 14)); gameModeTitlePanel.add(gameModeOptionTitle); gameModePanel.setBackground(greenBackground); playerTypePanel.setBackground(greenBackground); playerNamesPanel.setBackground(greenBackground); window.add(gameModeTitlePanel, BorderLayout.NORTH); window.add(gameModePanel, BorderLayout.CENTER); window.add(buttonPanel, BorderLayout.SOUTH); //Show the window window.setLocationRelativeTo(null); window.pack(); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - window.getWidth()) / 2); int y = (int) ((dimension.getHeight() - window.getHeight()) / 2); window.setLocation(x, y); window.setVisible(true); } /** * Create a JPanel which contains two buttons and attach a Listener to each * * @return */ public JPanel[] createButtonPanel() { JPanel buttonPanels[] = { new JPanel(), new JPanel(), new JPanel() }; rollBtn.addActionListener(controller); buttonPanels[0].add(rollBtn); buttonPanels[0].setBackground(greenBackground); selectAllBtn.addActionListener(controller); buttonPanels[1].add(selectAllBtn); selectAllBtn.setEnabled(false); buttonPanels[1].setBackground(greenBackground); bankBtn.addActionListener(controller); buttonPanels[2].add(bankBtn); buttonPanels[2].setBackground(greenBackground); getBankBtn().setEnabled(false); return buttonPanels; } /** * Create a JPanel with six Dice, the running score JLabels and the Roll and * Bank buttons * * @return */ public JPanel createDicePanel() { // Create the panel JPanel dicePanel = new JPanel(new GridLayout(0, 3, 0, 0)); JLabel turnScore = new JLabel("<html>Turn Score: </html>"); turnScore.setForeground(Color.WHITE); turnScore.setFont(new Font("Arial Black", Font.BOLD, 14)); dicePanel.add(turnScore); runningScore.setForeground(Color.WHITE); runningScore.setFont(new Font("Arial Black", Font.BOLD, 14)); runningScore.setHorizontalAlignment(JLabel.CENTER); dicePanel.add(runningScore); dicePanel.add(new JLabel()); // Initialize the dice and add to panel for (int i = 0; i < dice.length; i++) { dice[i] = new Die(controller); dicePanel.add(new JLabel(" ")); dicePanel.add(dice[i]); dice[i].setHorizontalAlignment(JLabel.CENTER); dicePanel.add(new JLabel(" ")); } dicePanel.add(new JLabel(" ")); dicePanel.add(new JLabel(" ")); dicePanel.add(new JLabel(" ")); // Call to add buttons and satisfy // requirements 1.3.4 and 1.3.5 JPanel btns[] = createButtonPanel(); dicePanel.add(btns[0]); dicePanel.add(btns[1]); dicePanel.add(btns[2]); dicePanel.setBackground(greenBackground); dicePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.WHITE, 3), BorderFactory.createEmptyBorder(3, 17, 3, 17))); return dicePanel; } /** * Create a new JPanel that contains all the JLabels necessary to represent * a player with 10 turns * * @param playerName * @param playerNumber * @return */ private JPanel createPlayerPanel() { JPanel playerPanel = new JPanel(new GridLayout(0, 2, 0, 2)); JLabel nameLbl = new JLabel("Player: "); nameLbl.setForeground(Color.WHITE); nameLbl.setFont(new Font("Arial Black", Font.BOLD, 16)); playerPanel.add(nameLbl); playerNameLabel.setForeground(Color.WHITE); playerNameLabel.setFont(new Font("Arial Black", Font.BOLD, 16)); playerPanel.add(playerNameLabel); JLabel filler0 = new JLabel(); playerPanel.add(filler0); JLabel filler1 = new JLabel(); playerPanel.add(filler1); for (int i = 0; i < scoreLabels.length; i++) { scoreLabels[i] = new JLabel(); scoreLabels[i].setText("Roll " + (i + 1) + ": "); scoreLabels[i].setForeground(Color.WHITE); scoreLabels[i].setFont(new Font("Arial Black", Font.BOLD, 14)); playerPanel.add(scoreLabels[i]); playerScores[i] = new JLabel(); playerScores[i].setForeground(Color.WHITE); playerScores[i].setFont(new Font("Arial Black", Font.BOLD, 14)); playerPanel.add(playerScores[i]); } gameScoreTitle.setForeground(Color.WHITE); gameScoreTitle.setFont(new Font("Arial Black", Font.BOLD, 14)); playerPanel.add(gameScoreTitle); gameScore.setForeground(Color.WHITE); gameScore.setFont(new Font("Arial Black", Font.BOLD, 14)); playerPanel.add(gameScore); highScoreTitle.setForeground(Color.WHITE); highScoreTitle.setFont(new Font("Arial Black", Font.BOLD, 14)); playerPanel.add(highScoreTitle); highScore.setForeground(Color.WHITE); highScore.setFont(new Font("Arial Black", Font.BOLD, 14)); playerPanel.add(highScore); playerPanel.setBackground(greenBackground); playerPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.WHITE, 3), BorderFactory.createEmptyBorder(3, 17, 3, 17))); return playerPanel; } /** * Create a new JPanel that displays the score guide image * * @return JLabel */ private JPanel createScorePanel() { JPanel scorePanel = new JPanel(); try { Image scoreGuide = ImageIO.read(getClass().getResource( "/images/FarkleScores.png")); scoreGuide = scoreGuide.getScaledInstance(200, 680, Image.SCALE_SMOOTH); JLabel scoreLabel = new JLabel(new ImageIcon(scoreGuide)); scorePanel.add(scoreLabel); scorePanel.setBackground(greenBackground); } catch (IOException e) { e.printStackTrace(); System.exit(0); } scorePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.WHITE, 3), BorderFactory.createEmptyBorder(3, 17, 3, 17))); return scorePanel; } public JButton getRollBtn() { return rollBtn; } public JButton getBankBtn() { return bankBtn; } public JButton getSelectAllBtn() { return selectAllBtn; } public JLabel getGameScore() { return gameScore; } public void setGameScore(JLabel gameScore) { this.gameScore = gameScore; } public JLabel getHighScore() { return highScore; } public void setHighScore(JLabel highScore) { this.highScore = highScore; } public JLabel getRunningScore() { return runningScore; } public void rollDice() { // Test farkle roll // dice[0].setValue(1); // dice[1].setValue(1); // dice[2].setValue(1); // dice[3].setValue(1); // dice[4].setValue(1); // dice[5].setValue(1); // Roll all the dice for (Die d : dice) { d.roll(); } } /** * Get the dice with the specified DieStates * * @param dieState * One or more DieState types * @return the dice with the specified DieStates */ public ArrayList<Die> getDice(DieState... dieState) { ArrayList<DieState> dieStates = new ArrayList<DieState>(); for (DieState state : dieState) { dieStates.add(state); } ArrayList<Die> retDice = new ArrayList<Die>(); for (Die d : dice) { if (dieStates.contains(d.getState())) { retDice.add(d); } } return retDice; } /** * Get the values from the dice with the specified DieStates * * @param dieState * One or more DieState types * @return List<Integer> values from the dice with the specified DieStates */ public List<Integer> getDieValues(DieState... dieState) { List<Integer> retVals = new ArrayList<Integer>(); ArrayList<Die> diceToCheck = getDice(dieState); for (Die d : diceToCheck) { retVals.add(d.getValue()); } return retVals; } /** * Set all six dice back to 0 and their states back to UNHELD */ public void resetDice() { for (Die d : dice) { d.setValue(0); d.setState(DieState.UNHELD); } } public void resetScores() { for (JLabel score : playerScores) { score.setText(""); } } /** * Update all dice with a HELD state to a SCORED state */ public void lockScoredDice() { for (Die d : dice) { if (d.getState() == DieState.HELD) { d.setState(DieState.SCORED); } } } /** * Update the turn label for the specified player with the specified score * * @param int player * @param int turn * @param int score */ public void setTurnScore(int player, int turn, int score) { playerScores[turn - 1].setText("" + score); } /** * Sets the background colors of the score labels based on the turn number. * If 0 is passed as the turn number all colors will be reset to default. * * @param turn * - Current turn number. (0 for reset) * @param isBonusTurn * - Bonus turns have the color set to yellow. */ public void setTurnHighlighting(int turn, boolean isBonusTurn) { for (int i = 0; i <= playerScores.length - 1; i++) { playerScores[i].setOpaque(false); playerScores[i].setForeground(Color.WHITE); scoreLabels[i].setOpaque(false); scoreLabels[i].setForeground(Color.WHITE); } if (turn != 0 && !isBonusTurn) { playerScores[turn - 1].setOpaque(true); playerScores[turn - 1].setBackground(Color.WHITE); playerScores[turn - 1].setText(""); playerScores[turn - 1].setForeground(Color.BLACK); scoreLabels[turn - 1].setOpaque(true); scoreLabels[turn - 1].setBackground(Color.WHITE); scoreLabels[turn - 1].setForeground(Color.BLACK); } else if (turn != 0) { playerScores[turn - 1].setOpaque(true); playerScores[turn - 1].setText("BONUS ROLL!"); playerScores[turn - 1].setBackground(Color.YELLOW); playerScores[turn - 1].setForeground(Color.BLACK); scoreLabels[turn - 1].setOpaque(true); scoreLabels[turn - 1].setBackground(Color.YELLOW); scoreLabels[turn - 1].setForeground(Color.BLACK); } } /** * Update the running score label with the specified score * * @param int score */ public void setRunningScore(int score) { runningScore.setText("" + score); } /** * Randomly return one of the four dice roll sounds * * @return */ public void playRollSound() { try { audioStream = AudioSystem.getAudioInputStream(rollSounds .get(new Random().nextInt(3))); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void playBonusSound() { try { audioStream = AudioSystem.getAudioInputStream(bonusSound); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void playBankSound() { try { audioStream = AudioSystem.getAudioInputStream(bankSounds .get(new Random().nextInt(3))); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Display a message to the user via JOptionPane * * @param message * - Message to be displayed in the main box. * @param title * - Title of the JOptionPane window. * */ public void displayMessage(String message, String title) { JOptionPane.showMessageDialog(this, message, title, JOptionPane.DEFAULT_OPTION); } public boolean displayYesNoMessage (String message, String title) { boolean retVal; int dialogResult = JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION); if (dialogResult == JOptionPane.YES_OPTION) { retVal = true; } else { retVal = false; } return retVal; } public boolean gameEnded(boolean resetOnly, boolean mainMenu) { boolean retVal = true; if ((!resetOnly) && (!mainMenu)){ Object[] options = { "Play Again", "Main Menu", "Exit"}; int n = JOptionPane.showOptionDialog(this, "Total Score: " + controller.farkleGame.players[0].gameScore + "\nWhat would you like to do?", "Game Over", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (n == 0) { retVal = true; } else if (n == 1) { retVal = false; } else { pullThePlug(); } } if (mainMenu) { retVal = false; } runningScore.setText(""); gameScore.setText("0"); getBankBtn().setEnabled(false); setTurnHighlighting(0, false); resetScores(); return retVal; } public void pullThePlug() { dispose(); System.exit(0); } /** * If no dice are held, selects all unheld dice * If no dice are unheld, selects all held dice */ public void selectAllDice() { if(getDice(DieState.HELD).size() == 0) { ArrayList<Die> dice = getDice(DieState.UNHELD); for(Die d : dice) { d.dispatchEvent(new MouseEvent(d, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), MouseEvent.BUTTON1, d.getX(), d.getY(), 1, false)); } } else { ArrayList<Die> dice = getDice(DieState.HELD); for(Die d : dice) { d.dispatchEvent(new MouseEvent(d, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), MouseEvent.BUTTON1, d.getX(), d.getY(), 1, false)); } } } public void updateGUI(int[] scores, String playerName) { playerNameLabel.setText(playerName); runningScore.setText(""); resetScores(); for (int i = 0; i <= 9; i++) { playerScores[i].setText(String.valueOf(scores[i])); } } @Override public void mouseClicked(MouseEvent e) { //SinglePlayer if (e.getComponent().getName().equals("1")) { singlePlayerLabel.setBackground(Color.YELLOW); singlePlayerLabel.setForeground(Color.BLACK); multiplayerLabel.setBackground(greenBackground); multiplayerLabel.setForeground(Color.WHITE); playerTypeSelectionPanel.setVisible(false); humanPlayerLabel.setBackground(greenBackground); computerPlayerLabel.setBackground(greenBackground); playerTwoNamePanel.setVisible(false); playerTwoName.setText(""); controller.tempGameInformation[0] = "S"; controller.tempGameInformation[1] = ""; } //Multiplayer else if (e.getComponent().getName().equals("2")) { singlePlayerLabel.setBackground(greenBackground); singlePlayerLabel.setForeground(Color.WHITE); multiplayerLabel.setBackground(Color.YELLOW); multiplayerLabel.setForeground(Color.BLACK); humanPlayerLabel.setForeground(Color.BLACK); humanPlayerLabel.setBackground(Color.YELLOW); computerPlayerLabel.setForeground(Color.WHITE); computerPlayerLabel.setBackground(greenBackground); playerTypeSelectionPanel.setVisible(true); playerTwoNamePanel.setVisible(true); playerTwoNamePanel.setVisible(true); playerTwoName.setText(""); playerTwoName.setEnabled(true); controller.tempGameInformation[0] = "M"; controller.tempGameInformation[1] = "H"; } //Human else if (e.getComponent().getName().equals("3")) { singlePlayerLabel.setBackground(greenBackground); singlePlayerLabel.setForeground(Color.WHITE); multiplayerLabel.setBackground(Color.YELLOW); multiplayerLabel.setForeground(Color.BLACK); humanPlayerLabel.setForeground(Color.BLACK); humanPlayerLabel.setBackground(Color.YELLOW); computerPlayerLabel.setForeground(Color.WHITE); computerPlayerLabel.setBackground(greenBackground); playerTypeSelectionPanel.setVisible(true); playerTwoNameLabel.setEnabled(true); playerTwoNamePanel.setVisible(true); playerTwoName.setText(""); playerTwoName.setEnabled(true); //startButton.setEnabled(false); controller.tempGameInformation[0] = "M"; controller.tempGameInformation[1] = "H"; } //Computer else if (e.getComponent().getName().equals("4")) { singlePlayerLabel.setBackground(greenBackground); singlePlayerLabel.setForeground(Color.WHITE); multiplayerLabel.setBackground(Color.YELLOW); multiplayerLabel.setForeground(Color.BLACK); humanPlayerLabel.setForeground(Color.WHITE); humanPlayerLabel.setBackground(greenBackground); computerPlayerLabel.setForeground(Color.BLACK); computerPlayerLabel.setBackground(Color.YELLOW); playerTypeSelectionPanel.setVisible(true); playerTwoNameLabel.setEnabled(false); playerTwoNamePanel.setEnabled(false); playerTwoName.setText("Computer"); playerTwoName.setEnabled(false); //startButton.setEnabled(false); controller.tempGameInformation[0] = "M"; controller.tempGameInformation[1] = "C"; } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }
package com.axelor.db; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import com.axelor.db.mapper.Mapper; import com.axelor.db.mapper.Property; import com.axelor.db.mapper.PropertyType; import com.axelor.inject.Beans; public class JpaRepository<T extends Model> implements Repository<T> { protected Class<T> modelClass; protected JpaRepository(Class<T> modelClass) { this.modelClass = modelClass; } @Override public List<Property> fields() { final Property[] fields = JPA.fields(modelClass); if (fields == null) { return null; } return Arrays.asList(fields); } @Override public Query<T> all() { return JPA.all(modelClass); } /** * Get the {@link Query} instance of the given type. * * @param type * the subtype of the managed model class. * @return instance of {@link Query} */ public <U extends T> Query<U> all(Class<U> type) { return JPA.all(type); } @Override public T create(Map<String, Object> values) { return Mapper.toBean(modelClass, values); } @Override public T copy(T entity, boolean deep) { return JPA.copy(entity, deep); } @Override public T find(Long id) { return JPA.find(modelClass, id); } @Override public T save(T entity) { return JPA.save(entity); } /** * Make an entity managed and persistent. * * @see EntityManager#persist(Object) */ public void persist(T entity) { JPA.persist(entity); } /** * Merge the state of the given entity into the current persistence context. * * @see EntityManager#merge(Object) */ public T merge(T entity) { return JPA.merge(entity); } @Override public void remove(T entity) { // detach orphan o2m records detachChildren(entity); JPA.remove(entity); } @SuppressWarnings("all") private void detachChildren(T entity) { if (!JPA.em().contains(entity)) { return; } final Mapper mapper = Mapper.of(EntityHelper.getEntityClass(entity)); for (Property property : mapper.getProperties()) { if (property.getType() != PropertyType.ONE_TO_MANY || !property.isOrphan()) { continue; } final Property mappedBy = mapper.of(property.getTarget()).getProperty(property.getMappedBy()); if (mappedBy != null && mappedBy.isRequired()) { continue; } final Collection<? extends Model> items = (Collection) property.get(entity); if (items == null || items.size() == 0) { continue; } for (Model item : items) { property.setAssociation(item, null); } items.clear(); } } /** * Refresh the state of the instance from the database, overwriting changes * made to the entity, if any. * * @see EntityManager#refresh(Object) */ @Override public void refresh(T entity) { JPA.refresh(entity); } /** * Synchronize the persistence context to the underlying database. * * @see EntityManager#flush() */ @Override public void flush() { JPA.flush(); } @Override public Map<String, Object> validate(Map<String, Object> json, Map<String, Object> context) { return json; } @Override public Map<String, Object> populate(Map<String, Object> json, Map<String, Object> context) { return json; } @SuppressWarnings("unchecked") public static <U extends Model> JpaRepository<U> of(Class<U> type) { final Class<?> klass = JpaScanner.findRepository(type.getSimpleName() + "Repository"); if (klass != null) { final JpaRepository<U> repo = (JpaRepository<U>) Beans.get(klass); if (repo.modelClass.isAssignableFrom(type)) { return repo; } } return Beans.inject(new JpaRepository<>(type)); } }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.*; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.bcel.PreorderDetector; import org.apache.bcel.Repository; import org.apache.bcel.classfile.*; public class DontUseEnum extends PreorderDetector { BugReporter bugReporter; public DontUseEnum(BugReporter bugReporter) { this.bugReporter = bugReporter; } //@Override public void visit(Method obj) { if (obj.getName().equals("enum") || obj.getName().equals("assert")) { BugInstance bug = new BugInstance(this, "Nm_DONT_USE_ENUM", NORMAL_PRIORITY) .addClass(this).addMethod(this); bugReporter.reportBug(bug); } } @Override public void visit(Field obj) { if (obj.getName().equals("enum") || obj.getName().equals("assert")) { BugInstance bug = new BugInstance(this, "Nm_DONT_USE_ENUM", NORMAL_PRIORITY) .addClass(this).addField(this); bugReporter.reportBug(bug); } } }
package com.axelor.meta; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import com.axelor.common.reflections.ClassFinder; import com.axelor.common.reflections.Reflections; import com.axelor.meta.loader.ModuleManager; import com.google.common.collect.ImmutableList; /** * This class provides some utility methods to scan classpath for * resources/classes. * */ public class MetaScanner { private MetaScanner() { } /** * Find all resources matched by the given pattern. * * @param pattern * the resource name pattern to match * @return list of resources matched */ public static ImmutableList<URL> findAll(String pattern) { return Reflections.findResources(loader()).byName(pattern).find(); } /** * Find all resources within a directory of the given module matching the * pattern. * * @param module * the module name * @param directory * the directory name * @param pattern * the resource name pattern to match * @return list of resources matched */ public static ImmutableList<URL> findAll(String module, String directory, String pattern) { URL pathUrl = ModuleManager.getModulePath(module); if (pathUrl == null) { return ImmutableList.of(); } String path = pathUrl.getPath(); String pathPattern = String.format("^%s", path.replaceFirst("module\\.properties$", "")); String namePattern = "(^|/|\\\\)" + directory + "(/|\\\\)" + pattern; try { Path parent = Paths.get(path).getParent(); Path resources = parent.resolve("../../resources/main").normalize(); if (Files.exists(resources)) { pathPattern = String.format("(%s)|(^%s)", pathPattern, resources); } } catch (Exception e) { } return Reflections.findResources().byName(namePattern).byURL(pathPattern).find(); } /** * Find module path URLs as in current classpath. * */ public static URL[] findURLs() { final List<URL> path = new ArrayList<>(); final URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); for (URL item : loader.getURLs()) { final URL[] urls = { item }; try (final URLClassLoader cl = new URLClassLoader(urls)) { URL res = cl.findResource("module.properties"); if (res == null) { res = cl.findResource("application.properties"); } if (res != null || Paths.get(item.getPath()).endsWith("build/classes/test/")) { path.add(item); } } catch (IOException e) { } } return path.toArray(new URL[]{}); } private static ClassLoader loader() { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); return new URLClassLoader(findURLs(), null) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loader.loadClass(name); } }; } /** * Delegates to {@link Reflections#findSubTypesOf(Class, ClassLoader)} * method and uses custom {@link ClassLoader} to speedup searching. * * This method search within module jar/directories only. * * @see Reflections#findSubTypesOf(Class) */ public static <T> ClassFinder<T> findSubTypesOf(Class<T> type) { return Reflections.findSubTypesOf(type, loader()); } /** * Delegates to {@link Reflections#findTypes(ClassLoader)} * method and uses custom {@link ClassLoader} to speedup searching. * * This method search within module jar/directories only. * * @see Reflections#findTypes() */ public static ClassFinder<?> findTypes() { return Reflections.findTypes(loader()); } }
package thredds.bufrtables; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileItem; import org.jdom.transform.XSLTransformer; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; import org.jdom.Document; import org.jdom.Element; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServlet; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Formatter; import java.util.regex.Matcher; import java.util.regex.Pattern; import ucar.unidata.util.StringUtil; import ucar.unidata.io.RandomAccessFile; import ucar.nc2.util.DiskCache2; import ucar.nc2.NetcdfFile; import ucar.nc2.dataset.NetcdfDataset; import ucar.bufr.MessageScanner; import ucar.bufr.Message; import ucar.bufr.Dump; /** * @author caron * @since Aug 9, 2008 */ public class BtServlet extends HttpServlet { protected org.slf4j.Logger log; private DiskCache2 cdmValidateCache = null; private DiskFileItemFactory factory; private File cacheDir; private long maxFileUploadSize = 20 * 1000 * 1000; boolean allow = true; boolean deleteImmediately = true; protected String contentPath; public void init() throws javax.servlet.ServletException { log = org.slf4j.LoggerFactory.getLogger(getClass()); String cacheDirName = getInitParameter("CacheDir"); int scourSecs = Integer.parseInt(getInitParameter("CacheScourSecs")); int maxAgeSecs = Integer.parseInt(getInitParameter("CacheMaxAgeSecs")); if (maxAgeSecs > 0) { deleteImmediately = false; cdmValidateCache = new DiskCache2(cacheDirName, false, maxAgeSecs / 60, scourSecs / 60); } cacheDir = new File(cacheDirName); cacheDir.mkdirs(); factory = new DiskFileItemFactory(0, cacheDir); // LOOK can also do in-memory } public void destroy() { if (cdmValidateCache != null) cdmValidateCache.exit(); super.destroy(); } /** * GET handles the case where its a remote URL (dods or http) * * @param req request * @param res response * @throws ServletException * @throws java.io.IOException */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (!allow) { res.sendError(HttpServletResponse.SC_FORBIDDEN, "Service not supported"); return; } String urlString = req.getParameter("URL"); if (urlString != null) { // validate the uri String try { URI uri = new URI(urlString); urlString = uri.toASCIIString(); // LOOK do we want just toString() ? Is this useful "input validation" ? } catch (URISyntaxException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "URISyntaxException on URU parameter"); return; } String xml = req.getParameter("xml"); boolean wantXml = (xml != null) && xml.equals("true"); } // info about existing files String path = req.getPathInfo(); if (path.startsWith("/mess/")) { path = path.substring(6); // cmd int pos = path.lastIndexOf("/"); if (pos < 0) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "no message number"); return; } String cmd = path.substring(pos + 1); path = path.substring(0, pos); // messno pos = path.lastIndexOf("/"); if (pos < 0) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "no message number"); return; } String mess = path.substring(pos + 1); int messno; try { messno = Integer.parseInt(mess); } catch (Exception e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "illegal message number=" + mess); return; } // cacheFile String cacheName = path.substring(0, pos); File uploadedFile = new File(cacheDir + "/" + cacheName); if (!uploadedFile.exists()) { res.sendError(HttpServletResponse.SC_NOT_FOUND, "file not found=" + cacheName); return; } if (cmd.equals("dds.txt")) showMessDDS(res, uploadedFile, cacheName, messno); else if (cmd.equals("data.txt")) showMessData(res, uploadedFile, cacheName, messno); else if (cmd.equals("bitCount.txt")) showMessSize(res, uploadedFile, cacheName, messno); } res.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET request not understood"); } private void showMessDDS(HttpServletResponse res, File file, String cacheName, int messno) throws IOException { Message m = getBufrMessage(file, messno); if (m == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, "message " + messno + " not found in " + cacheName); return; } res.setContentType("text/plain"); OutputStream out = res.getOutputStream(); Formatter f = new Formatter(out); f.format("File %s message %d %n%n", cacheName, messno); new Dump().dump(f, m); f.flush(); } private void showMessSize(HttpServletResponse res, File file, String cacheName, int messno) throws IOException { Message m = getBufrMessage(file, messno); if (m == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, "message " + messno + " not found in " + cacheName); return; } res.setContentType("text/plain"); OutputStream out = res.getOutputStream(); Formatter f = new Formatter(out); f.format("File %s message %d %n%n", cacheName, messno); new Dump().dump(f, m); f.flush(); } private void showMessData(HttpServletResponse res, File file, String cacheName, int messno) throws IOException { Message message = null; NetcdfDataset ncd = null; RandomAccessFile raf = null; try { raf = new RandomAccessFile(file.getPath(), "r"); MessageScanner scan = new MessageScanner(raf); int count = 0; while (scan.hasNext()) { message = scan.next(); if (message == null) continue; if (count == messno) { byte[] mbytes = scan.getMessageBytesFromLast( message); NetcdfFile ncfile = NetcdfFile.openInMemory("test", mbytes); ncd = new NetcdfDataset(ncfile); } count++; } } finally { if (raf != null) raf.close(); } if (ncd == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, "message " + messno + " not found in " + cacheName); return; } try { res.setContentType("text/plain"); OutputStream out = res.getOutputStream(); new Bufr2Xml(message, ncd, out); out.flush(); } finally { ncd.close(); } } private Message getBufrMessage(File file, int messno) throws IOException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file.getPath(), "r"); MessageScanner scan = new MessageScanner(raf); int count = 0; while (scan.hasNext()) { Message m = scan.next(); if (m == null) continue; if (count == messno) return m; count++; } } finally { if (raf != null) raf.close(); } return null; } private NetcdfDataset getBufrMessageAsDataset(File file, int messno) throws IOException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file.getPath(), "r"); MessageScanner scan = new MessageScanner(raf); int count = 0; while (scan.hasNext()) { Message m = scan.next(); if (m == null) continue; if (count == messno) { byte[] mbytes = scan.getMessageBytesFromLast(m); NetcdfFile ncfile = NetcdfFile.openInMemory("test", mbytes); NetcdfDataset ncd = new NetcdfDataset(ncfile); return ncd; } count++; } } finally { if (raf != null) raf.close(); } return null; } /** * POST handles uploaded files * * @param req request * @param res response * @throws ServletException * @throws IOException */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (!allow) { res.sendError(HttpServletResponse.SC_FORBIDDEN, "Service not supported"); return; } // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "POST must be multipart"); return; } //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileUploadSize); // maximum bytes before a FileUploadException will be thrown List<FileItem> fileItems; try { fileItems = (List<FileItem>) upload.parseRequest(req); } catch (FileUploadException e) { log.info("Validator FileUploadException", e); res.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } //Process the uploaded items String username = null; boolean wantXml = false; for (FileItem item : fileItems) { if (item.isFormField()) { if ("username".equals(item.getFieldName())) username = item.getString(); if ("xml".equals(item.getFieldName())) wantXml = item.getString().equals("true"); } } for (FileItem item : fileItems) { if (!item.isFormField()) { try { processUploadedFile(req, res, (DiskFileItem) item, username, wantXml); return; } catch (Exception e) { log.info("Validator processUploadedFile", e); res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } } } } private void processUploadedFile(HttpServletRequest req, HttpServletResponse res, DiskFileItem item, String username, boolean wantXml) throws Exception { if ((username == null) || (username.length() == 0)) username = "anon"; username = StringUtil.filter(username, "_"); String filename = item.getName(); filename = StringUtil.replace(filename, "/", "-"); filename = StringUtil.filter(filename, ".-_"); String cacheName = username + "/" + filename; File uploadedFile = new File(cacheDir + "/" + cacheName); uploadedFile.getParentFile().mkdirs(); item.write(uploadedFile); try { Document doc = readBufr(uploadedFile, cacheName); // debug XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream fout = new FileOutputStream("C:/temp/bufr.xml"); System.out.print(fmt.outputString(doc)); fmt.output(doc, fout); int len = showValidatorResults(res, doc, wantXml); } finally { if (deleteImmediately) { try { uploadedFile.delete(); } catch (Exception e) { log.error("Uploaded File = " + uploadedFile.getPath() + " delete failed = " + e.getMessage()); } } } if (req.getRemoteUser() == null) { } log.info("Uploaded File = " + item.getName() + " sent to " + uploadedFile.getPath() + " size= " + uploadedFile.length()); } private Document readBufr(File file, String cacheName) throws Exception { long start = System.nanoTime(); RandomAccessFile raf = new RandomAccessFile(file.getPath(), "r"); Element rootElem = new Element("bufrValidation"); Document doc = new Document(rootElem); rootElem.setAttribute("fileName", cacheName); rootElem.setAttribute("fileSize", Long.toString(raf.length())); MessageScanner scan = new MessageScanner(raf); int count = 0; while (scan.hasNext()) { Message m = scan.next(); if (m == null) continue; Element bufrMessage = new Element("bufrMessage").setAttribute("status", "ok"); rootElem.addContent(bufrMessage); bufrMessage.setAttribute("pos", Integer.toString(count)); if (!m.isTablesComplete()) bufrMessage.setAttribute("dds", "incomplete"); else bufrMessage.setAttribute("dds", "ok"); int nbitsCounted = m.getTotalBits(); int nbitsGiven = 8 * (m.dataSection.dataLength - 4); boolean ok = Math.abs(m.getCountedDataBytes() - m.dataSection.dataLength) <= 1; // radiosondes dataLen not even number of bytes if (ok) bufrMessage.setAttribute("size", "ok"); else { bufrMessage.setAttribute("size", "fail"); bufrMessage.addContent( new Element("ByteCount").setText("countBytes " + m.getCountedDataBytes() + " != " + m.dataSection.dataLength + " dataSize")); } bufrMessage.addContent(new Element("BitCount").setText("countBits " + nbitsCounted + " != " + nbitsGiven + " dataSizeBits")); bufrMessage.setAttribute("nobs", Integer.toString(m.getNumberDatasets())); bufrMessage.addContent(new Element("WMOheader").setText(extractWMO(m.getHeader()))); bufrMessage.addContent(new Element("center").setText(m.getCenterName())); bufrMessage.addContent(new Element("category").setText(m.getCategoryFullName())); bufrMessage.addContent(new Element("date").setText(m.ids.getReferenceTime())); count++; } raf.close(); rootElem.setAttribute("totalObs", Integer.toString(scan.getTotalObs())); return doc; } private static final Pattern wmoPattern = Pattern.compile(".*([IJ]..... ....) .*"); private String extractWMO(String header) { Matcher matcher = wmoPattern.matcher(header); if (!matcher.matches()) { log.warn("extractWMO failed= %s\n", header); return header; } return matcher.group(1); } private int showValidatorResults(HttpServletResponse res, Document doc, boolean wantXml) throws Exception { String infoString; if (wantXml) { XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); infoString = fmt.outputString(doc); res.setContentLength(infoString.length()); res.setContentType("text/xml; charset=iso-8859-1"); } else { InputStream is = getXSLT(); XSLTransformer transformer = new XSLTransformer(is); Document html = transformer.transform(doc); XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); infoString = fmt.outputString(html); res.setContentType("text/html; charset=iso-8859-1"); } res.setContentLength(infoString.length()); OutputStream out = res.getOutputStream(); out.write(infoString.getBytes()); out.flush(); return infoString.length(); } private InputStream getXSLT() { Class c = this.getClass(); String resource = "/resources/xsl/validation.xsl"; InputStream is = c.getResourceAsStream(resource); if (null == is) log.error("Cant load XSLT resource = " + resource); return is; } }
package arez.gwt.qa; import javax.annotation.Nonnull; import org.intellij.lang.annotations.RegExp; import org.realityforge.gwt.symbolmap.SymbolEntryIndex; /** * A collection of assertions about the expected symbols present in GWT javascript output. */ public final class ArezBuildAsserts { private ArezBuildAsserts() { } /** * This assertion verifies that the standard inlines have occurred. * * @param index the index that contains all symbols for output target. */ public static void assertStandardOutputs( @Nonnull final SymbolEntryIndex index ) { // These are JsFunction instances and thus should be omitted index.assertNoClassNameMatches( "arez\\.Reaction" ); assertNoTestOnlyElements( index ); // This should be optimized out completely index.assertNoClassNameMatches( "arez\\.ArezConfig" ); index.assertNoClassNameMatches( "arez\\.component\\.ComponentState" ); // This should be eliminated as it will improve the ability for GWT compiler to dead-code-eliminate index.assertNoMemberMatches( "arez\\.Arez", "$clinit" ); // This should be eliminated as only used during invariant checking index.assertNoMemberMatches( "arez\\.ObservableValue", "preReportChanged" ); // No repository should have equals defined assertEquals( index, ".*(\\.|_)Arez_[^\\.]Repository", false ); } /** * This assertion verifies that there is no elements that we have annotated as TestOnly. * * @param index the index that contains all symbols for output target. */ private static void assertNoTestOnlyElements( @Nonnull final SymbolEntryIndex index ) { // TestOnly annotated methods index.assertNoMemberMatches( "arez\\.ArezContext", "getObserverErrorHandlerSupport" ); index.assertNoMemberMatches( "arez\\.ArezContext", "currentNextTransactionId" ); index.assertNoMemberMatches( "arez\\.ArezContext", "getScheduler" ); index.assertNoMemberMatches( "arez\\.ArezContext", "setNextNodeId" ); index.assertNoMemberMatches( "arez\\.ArezContext", "getNextNodeId" ); index.assertNoMemberMatches( "arez\\.ArezContext", "getSchedulerLockCount" ); index.assertNoMemberMatches( "arez\\.ArezContext", "setSchedulerLockCount" ); index.assertNoMemberMatches( "arez\\.ArezContextHolder", "reset" ); index.assertNoMemberMatches( "arez\\.ArezLogger", "getLogger" ); index.assertNoClassNameMatches( "arez\\.ArezTestUtil" ); index.assertNoMemberMatches( "arez\\.ArezZoneHolder", "getDefaultZone" ); index.assertNoMemberMatches( "arez\\.ArezZoneHolder", "getZoneStack" ); index.assertNoMemberMatches( "arez\\.ArezZoneHolder", "reset" ); index.assertNoMemberMatches( "arez\\.Component", "getPreDispose" ); index.assertNoMemberMatches( "arez\\.Component", "getPostDispose" ); index.assertNoMemberMatches( "arez\\.ComputedValue", "setValue" ); index.assertNoMemberMatches( "arez\\.ComputedValue", "getError" ); index.assertNoMemberMatches( "arez\\.ComputedValue", "setError" ); index.assertNoMemberMatches( "arez\\.ComputedValue", "setComputing" ); index.assertNoMemberMatches( "arez\\.ObservableValue", "getWorkState" ); index.assertNoMemberMatches( "arez\\.Observer", "markAsScheduled" ); index.assertNoMemberMatches( "arez\\.ObserverErrorHandlerSupport", "getObserverErrorHandlers" ); index.assertNoMemberMatches( "arez\\.ReactionScheduler", "getPendingObservers" ); index.assertNoMemberMatches( "arez\\.ReactionScheduler", "getCurrentReactionRound" ); index.assertNoMemberMatches( "arez\\.ReactionScheduler", "getRemainingReactionsInCurrentRound" ); index.assertNoMemberMatches( "arez\\.ReactionScheduler", "setCurrentReactionRound" ); index.assertNoMemberMatches( "arez\\.SpyImpl", "getSpyEventHandlers" ); index.assertNoMemberMatches( "arez\\.Transaction", "getPendingDeactivations" ); index.assertNoMemberMatches( "arez\\.Transaction", "setTransaction" ); index.assertNoMemberMatches( "arez\\.Transaction", "isSuspended" ); index.assertNoMemberMatches( "arez\\.Transaction", "markAsSuspended" ); index.assertNoMemberMatches( "arez\\.Transaction", "resetSuspendedFlag" ); index.assertNoMemberMatches( "arez\\.component\\.MemoizeCache", "getCache" ); index.assertNoMemberMatches( "arez\\.component\\.MemoizeCache", "getNextIndex" ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enforce_transaction_type` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertShouldEnforceTransactionTypeOutputs( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { // Assert no Transaction validation cruft is enabled as !Arez.shouldEnforceTransactionType() in the build index.assertSymbol( "arez\\.TransactionMode", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.collections_properties_unmodifiable` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertCollectionPropertiesUnmodifiableOutputs( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { // Assert RepositoryUtil is eliminated once !Arez.areCollectionsPropertiesUnmodifiable() in the build index.assertSymbol( "arez\\.component\\.RepositoryUtil", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enable_observer_error_handlers` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertAreObserverErrorHandlersEnabledOutputs( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { index.assertSymbol( "arez\\.ObserverErrorHandler", enabled ); index.assertSymbol( "arez\\.ObserverErrorHandlerSupport", enabled ); // This is actually only elided when both Spy and ObserverErrorHandler are both disabled but mostly // if observer error handlers are disabled then spies are disabled so adding this assertion here index.assertSymbol( "arez\\.ObserverError", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enable_names` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertAreNamesEnabled( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { index.assertSymbol( "arez\\.ThrowableUtil", enabled ); index.assertSymbol( ".*\\.Arez_.*Repository", "getRepositoryName", enabled ); index.assertSymbol( ".*\\.Arez_.*", "toString", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enable_registries` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertAreRegistriesEnabled( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { index.assertSymbol( "arez\\.ArezContext", "_observables", enabled ); index.assertSymbol( "arez\\.ArezContext", "_computedValues", enabled ); index.assertSymbol( "arez\\.ArezContext", "_observers", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enable_spies` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertSpyOutputs( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { index.assertSymbol( "arez\\.spy\\..*", enabled ); index.assertSymbol( "arez\\..*InfoImpl", enabled ); index.assertSymbol( "arez\\.ObservableValue", "_info", enabled ); index.assertSymbol( "arez\\.ComputedValue", "_info", enabled ); index.assertSymbol( "arez\\.Observer", "_info", enabled ); index.assertSymbol( "arez\\.Transaction", "_info", enabled ); index.assertSymbol( "arez\\.Component", "_info", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enable_zones` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertZoneOutputs( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { index.assertSymbol( "arez\\.Zone", enabled ); index.assertSymbol( "arez\\.ArezZoneHolder", enabled ); index.assertSymbol( "arez\\.Arez", "createZone", enabled ); index.assertSymbol( "arez\\.Arez", "activateZone", enabled ); index.assertSymbol( "arez\\.Arez", "deactivateZone", enabled ); index.assertSymbol( "arez\\.Arez", "currentZone", enabled ); index.assertSymbol( ".*\\.Arez_.*", "$$arezi$$_context", enabled ); index.assertSymbol( "arez\\.Node", "_context", enabled ); index.assertSymbol( "arez\\.ReactionScheduler", "_context", enabled ); } /** * This assertion verifies that the symbols that are conditional on the `arez.enable_native_components` * setting are present if enabled and not present if not enabled. * * @param index the index that contains all symbols for output target. * @param enabled true if setting is enabled, false otherwise. */ public static void assertNativeComponentOutputs( @Nonnull final SymbolEntryIndex index, final boolean enabled ) { // Assert no Component cruft is enabled as !Arez.areNativeComponentsEnabled() in the build index.assertSymbol( "arez\\.Component.*", enabled ); index.assertSymbol( ".*\\.Arez_.*", "$$arezi$$_component", enabled ); index.assertSymbol( ".*\\.Arez_.*Repository", "component", enabled ); // No repositories need their own identity if native components disabled assertSyntheticId( index, ".*\\.Arez_[^\\.]+Repository", false ); } /** * Assert that a synthetic id is present or not present in classes specified by pattern. * * @param index the index that contains all symbols for output target. * @param classNamePattern the pattern that determine which classes should be matched. * @param enabled true if syntheticId should be present, false otherwise. */ public static void assertSyntheticId( @Nonnull final SymbolEntryIndex index, @RegExp( prefix = "^", suffix = "$" ) @Nonnull final String classNamePattern, final boolean enabled ) { index.assertSymbol( classNamePattern, "$$arezi$$_id", enabled ); index.assertSymbol( classNamePattern, "$$arezi$$_nextId", enabled ); } /** * Assert that the equals method is not present, usually applied to select generated classes. * * @param index the index that contains all symbols for output target. * @param classNamePattern the pattern that determine which classes should be matched. * @param enabled true if equals should be present, false otherwise. */ public static void assertEquals( @Nonnull final SymbolEntryIndex index, @RegExp( prefix = "^", suffix = "$" ) @Nonnull final String classNamePattern, final boolean enabled ) { index.assertSymbol( classNamePattern, "\\$equals", enabled ); } /** * Assert normal arez outputs based on specified Arez compile time settings. * * @param index the index that contains all symbols for output target. * @param areNamesEnabled the value of the `arez.enable_names` setting. * @param areSpiesEnabled the value of the `arez.enable_spies` setting. * @param areNativeComponentsEnabled the value of the `arez.enable_native_components` setting. * @param areRegistriesEnabled the value of the `arez.enable_registries` setting. * @param areObserverErrorHandlersEnabled the value of the `arez.enable_observer_error_handlers` setting. * @param areZonesEnabled the value of the `arez.enable_zones` setting. * @param shouldEnforceTransactionType the value of the `arez.enforce_transaction_type` setting. * @param areCollectionsPropertiesUnmodifiable the value of the `arez.collections_properties_unmodifiable` setting. */ public static void assertArezOutputs( @Nonnull final SymbolEntryIndex index, final boolean areNamesEnabled, final boolean areSpiesEnabled, final boolean areNativeComponentsEnabled, final boolean areRegistriesEnabled, final boolean areObserverErrorHandlersEnabled, final boolean areZonesEnabled, final boolean shouldEnforceTransactionType, final boolean areCollectionsPropertiesUnmodifiable ) { assertStandardOutputs( index ); assertAreNamesEnabled( index, areNamesEnabled ); assertSpyOutputs( index, areSpiesEnabled ); assertNativeComponentOutputs( index, areNativeComponentsEnabled ); assertAreRegistriesEnabled( index, areRegistriesEnabled ); assertAreObserverErrorHandlersEnabledOutputs( index, areObserverErrorHandlersEnabled ); assertZoneOutputs( index, areZonesEnabled ); assertShouldEnforceTransactionTypeOutputs( index, shouldEnforceTransactionType ); assertCollectionPropertiesUnmodifiableOutputs( index, areCollectionsPropertiesUnmodifiable ); } }
package water.persist; import java.io.*; import java.net.SocketTimeoutException; import java.net.URI; import java.util.concurrent.Callable; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.io.ByteStreams; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import water.*; import water.api.HDFSIOException; import water.fvec.HDFSFileVec; import water.fvec.Vec; import water.util.FileUtils; import water.util.Log; /** * HDFS persistence layer. */ public final class PersistHdfs extends Persist { /** Globally shared HDFS configuration. */ public static final Configuration CONF; /** Root path of HDFS */ private final Path _iceRoot; // Returns String with path for given key. private static String getPathForKey(Key k) { final int off = k._kb[0]==Key.CHK ? Vec.KEY_PREFIX_LEN : 0; return new String(k._kb,off,k._kb.length-off); } // Global HDFS initialization // FIXME: do not share it via classes, but initialize it by object static { Configuration conf = null; if( H2O.ARGS.hdfs_config != null ) { conf = new Configuration(); File p = new File(H2O.ARGS.hdfs_config); if( !p.exists() ) H2O.die("Unable to open hdfs configuration file " + p.getAbsolutePath()); conf.addResource(new Path(p.getAbsolutePath())); Log.debug("resource ", p.getAbsolutePath(), " added to the hadoop configuration"); } else { conf = new Configuration(); Path confDir = null; // Try to guess location of default Hadoop configuration // WARNING: loading of default properties should be disabled if the job // is executed via yarn command which prepends core-site.xml properties on classpath if (System.getenv().containsKey("HADOOP_CONF_DIR")) { confDir = new Path(System.getenv("HADOOP_CONF_DIR")); } else if (System.getenv().containsKey("YARN_CONF_DIR")) { confDir = new Path(System.getenv("YARN_CONF_DIR")); } else if (System.getenv().containsKey("HADOOP_HOME")) { confDir = new Path(System.getenv("HADOOP_HOME"), "conf"); } // Load default HDFS configuration if (confDir != null) { Log.info("Using HDFS configuration from " + confDir); conf.addResource(new Path(confDir, "core-site.xml")); } else { Log.debug("Cannot find HADOOP_CONF_DIR or YARN_CONF_DIR - default HDFS properties are NOT loaded!"); } } CONF = conf; } // Loading HDFS files public PersistHdfs() { _iceRoot = null; } public void cleanUp() { throw H2O.unimpl(); /** user-mode swapping not implemented */} // Loading/Writing ice to HDFS public PersistHdfs(URI uri) { try { _iceRoot = new Path(uri + "/ice" + H2O.SELF_ADDRESS.getHostAddress() + "-" + H2O.API_PORT); // Make the directory as-needed FileSystem fs = FileSystem.get(_iceRoot.toUri(), CONF); fs.mkdirs(_iceRoot); } catch( Exception e ) { throw Log.throwErr(e); } } /** InputStream from a HDFS-based Key */ /*public static InputStream openStream(Key k, Job pmon) throws IOException { H2OHdfsInputStream res = null; Path p = new Path(k.toString()); try { res = new H2OHdfsInputStream(p, 0, pmon); } catch( IOException e ) { try { Thread.sleep(1000); } catch( Exception ex ) {} Log.warn("Error while opening HDFS key " + k.toString() + ", will wait and retry."); res = new H2OHdfsInputStream(p, 0, pmon); } return res; }*/ @Override public byte[] load(final Value v) { // !!! WARNING !!! // tomk: Sun Apr 19 13:11:51 PDT 2015 // This load implementation behaved *HORRIBLY* with S3 when the libraries were updated. // Behaves well (and is the same set of libraries as H2O-1): // org.apache.hadoop:hadoop-client:2.0.0-cdh4.3.0 // net.java.dev.jets3t:jets3t:0.6.1 // Behaves abysmally: // org.apache.hadoop:hadoop-client:2.5.0-cdh5.2.0 // net.java.dev.jets3t:jets3t:0.9.2 // I did some debugging. // What happens in the new libraries is the connection type is a streaming connection, and // the entire file gets read on close() even if you only wanted to read a chunk. The result // is the same data gets read over and over again by the underlying transport layer even // though H2O only thinks it's asking for (and receiving) each piece of data once. // I suspect this has something to do with the 'Range' HTTP header on the GET, but I'm not // entirely sure. Many layers of library need to be fought through to really figure it out. // Anyway, this will need to be rewritten from the perspective of how to properly use the // new library version. Might make sense to go to straight to 's3a' which is a replacement // for 's3n'. long end, start = System.currentTimeMillis(); final byte[] b = MemoryManager.malloc1(v._max); Key k = v._key; long skip = k.isChunkKey() ? water.fvec.NFSFileVec.chunkOffset(k) : 0; final Path p = _iceRoot == null?new Path(getPathForKey(k)):new Path(_iceRoot, getIceName(v)); final long skip_ = skip; run(new Callable() { @Override public Object call() throws Exception { FileSystem fs = FileSystem.get(p.toUri(), CONF); FSDataInputStream s = null; try { s = fs.open(p); if (p.toString().toLowerCase().startsWith("maprfs:")) { // MapR behaves really horribly with the google ByteStreams code below. // Instead of skipping by seeking, it skips by reading and dropping. Very bad. // Use the HDFS API here directly instead. s.seek(skip_); s.readFully(b); } else { // NOTE: // The following line degrades performance of HDFS load from S3 API: s.readFully(skip,b,0,b.length); // Google API's simple seek has better performance // Load of 300MB file via Google API ~ 14sec, via s.readFully ~ 5min (under the same condition) ByteStreams.skipFully(s, skip_); ByteStreams.readFully(s, b); } assert v.isPersisted(); } finally { FileUtils.close(s); } return null; } }, true, v._max); end = System.currentTimeMillis(); if (end-start > 1000) // Only log read that took over 1 second to complete Log.debug("Slow Read: "+(end-start)+" millis to get bytes "+skip_ +"-"+(skip_+b.length)+" in HDFS read."); return b; } @Override public void store(Value v) { // Should be used only if ice goes to HDFS assert this == H2O.getPM().getIce(); assert !v.isPersisted(); byte[] m = v.memOrLoad(); assert (m == null || m.length == v._max); // Assert not saving partial files store(new Path(_iceRoot, getIceName(v)), m); v.setdsk(); // Set as write-complete to disk } public static void store(final Path path, final byte[] data) { run(new Callable() { @Override public Object call() throws Exception { FileSystem fs = FileSystem.get(path.toUri(), CONF); fs.mkdirs(path.getParent()); FSDataOutputStream s = fs.create(path); try { s.write(data); } finally { s.close(); } return null; } }, false, data.length); } @Override public void delete(final Value v) { assert this == H2O.getPM().getIce(); assert !v.isPersisted(); // Upper layers already cleared out run(new Callable() { @Override public Object call() throws Exception { Path p = new Path(_iceRoot, getIceName(v)); FileSystem fs = FileSystem.get(p.toUri(), CONF); fs.delete(p, true); return null; } }, false, 0); } private static class Size { int _value; } private static void run(Callable c, boolean read, int size) { // Count all i/o time from here, including all retry overheads long start_io_ms = System.currentTimeMillis(); while( true ) { try { long start_ns = System.nanoTime(); // Blocking i/o call timing - without counting repeats c.call(); // TimeLine.record_IOclose(start_ns, start_io_ms, read ? 1 : 0, size, Value.HDFS); break; // Explicitly ignore the following exceptions but // fail on the rest IOExceptions } catch( EOFException e ) { ignoreAndWait(e, false); } catch( SocketTimeoutException e ) { ignoreAndWait(e, false); } catch( IOException e ) { // Newer versions of Hadoop derive S3Exception from IOException if (e.getClass().getName().contains("S3Exception")) { ignoreAndWait(e, false); } else { ignoreAndWait(e, true); } } catch( RuntimeException e ) { // Older versions of Hadoop derive S3Exception from RuntimeException if (e.getClass().getName().contains("S3Exception")) { ignoreAndWait(e, false); } else { throw Log.throwErr(e); } } catch( Exception e ) { throw Log.throwErr(e); } } } private static void ignoreAndWait(final Exception e, boolean printException) { Log.ignore(e, "Hit HDFS reset problem, retrying...", printException); try { Thread.sleep(500); } catch( InterruptedException ie ) {} } public static void addFolder(Path p, ArrayList<String> keys,ArrayList<String> failed) throws IOException { FileSystem fs = FileSystem.get(p.toUri(), PersistHdfs.CONF); if(!fs.exists(p)){ failed.add("Path does not exist: '" + p.toString() + "'"); return; } addFolder(fs, p, keys, failed); } private static void addFolder(FileSystem fs, Path p, ArrayList<String> keys, ArrayList<String> failed) { try { if( fs == null ) return; Futures futures = new Futures(); for( FileStatus file : fs.listStatus(p) ) { Path pfs = file.getPath(); if( file.isDir() ) { addFolder(fs, pfs, keys, failed); } else { long size = file.getLen(); Key k = null; keys.add((k = HDFSFileVec.make(file.getPath().toString(), file.getLen(), futures)).toString()); Log.debug("PersistHdfs: DKV.put(" + k + ")"); } } } catch( Exception e ) { Log.err(e); failed.add(p.toString()); } } @Override public Key uriToKey(URI uri) throws IOException { assert "hdfs".equals(uri.getScheme()) || "s3".equals(uri.getScheme()) || "s3n".equals(uri.getScheme()) || "s3a".equals(uri.getScheme()) : "Expected hdfs, s3 s3n, or s3a scheme, but uri is " + uri; FileSystem fs = FileSystem.get(uri, PersistHdfs.CONF); FileStatus[] fstatus = fs.listStatus(new Path(uri)); assert fstatus.length == 1 : "Expected uri to single file, but uri is " + uri; return HDFSFileVec.make(fstatus[0].getPath().toString(), fstatus[0].getLen()); } // Is there a bucket name without a trailing "/" ? private boolean isBareS3NBucketWithoutTrailingSlash(String s) { String s2 = s.toLowerCase(); Matcher m = Pattern.compile("s3n://[^/]*").matcher(s2); return m.matches(); } // We don't handle HDFS style S3 storage, just native storage. But all users // don't know about HDFS style S3 so treat S3 as a request for a native file private static final String convertS3toS3N(String s) { if (Pattern.compile("^s3[a]?://.*").matcher(s).matches()) return s.replaceFirst("^s3[a]?://", "s3n://"); else return s; } @Override public ArrayList<String> calcTypeaheadMatches(String filter, int limit) { // Get HDFS configuration Configuration conf = PersistHdfs.CONF; // Hack around s3:// filter = convertS3toS3N(filter); // Handle S3N bare buckets - s3n://bucketname should be suffixed by '/' // or underlying Jets3n will throw NPE. filter name should be s3n://bucketname/ if (isBareS3NBucketWithoutTrailingSlash(filter)) { filter += "/"; } // Output matches ArrayList<String> array = new ArrayList<String>(); { // Filter out partials which are known to print out useless stack traces. String s = filter.toLowerCase(); if ("hdfs:".equals(s)) return array; if ("maprfs:".equals(s)) return array; } try { Path p = new Path(filter); Path expand = p; if( !filter.endsWith("/") ) expand = p.getParent(); FileSystem fs = FileSystem.get(p.toUri(), conf); for( FileStatus file : fs.listStatus(expand) ) { Path fp = file.getPath(); if( fp.toString().startsWith(p.toString()) ) { array.add(fp.toString()); } if( array.size() == limit) break; } } catch (Exception e) { Log.trace(e); } catch (Throwable t) { t.printStackTrace(); Log.warn(t); } return array; } @Override public void importFiles(String path, ArrayList<String> files, ArrayList<String> keys, ArrayList<String> fails, ArrayList<String> dels) { path = convertS3toS3N(path); // Fix for S3 kind of URL if (isBareS3NBucketWithoutTrailingSlash(path)) { path += "/"; } Log.info("ImportHDFS processing (" + path + ")"); // List of processed files try { // Recursively import given file/folder addFolder(new Path(path), keys, fails); files.addAll(keys); // write barrier was here : DKV.write_barrier(); } catch (IOException e) { throw new HDFSIOException(path, PersistHdfs.CONF.toString(), e); } } // Node Persistent Storage helpers @Override public String getHomeDirectory() { try { FileSystem fs = FileSystem.get(CONF); return fs.getHomeDirectory().toString(); } catch (Exception e) { return null; } } @Override public PersistEntry[] list(String path) { try { Path p = new Path(path); URI uri = p.toUri(); FileSystem fs = FileSystem.get(uri, CONF); FileStatus[] arr1 = fs.listStatus(p); PersistEntry[] arr2 = new PersistEntry[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr2[i] = new PersistEntry(arr1[i].getPath().getName(), arr1[i].getLen(), arr1[i].getModificationTime()); } return arr2; } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } @Override public boolean exists(String path) { Path p = new Path(path); URI uri = p.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.exists(p); } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } @Override public long length(String path) { Path p = new Path(path); URI uri = p.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.getFileStatus(p).getLen(); } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } @Override public InputStream open(String path) { Path p = new Path(path); URI uri = p.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.open(p); } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } @Override public boolean mkdirs(String path) { Path p = new Path(path); URI uri = p.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.mkdirs(p); } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } @Override public boolean rename(String fromPath, String toPath) { Path f = new Path(fromPath); Path t = new Path(toPath); URI uri = f.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.rename(f, t); } catch (IOException e) { throw new HDFSIOException(toPath, CONF.toString(), e); } } @Override public OutputStream create(String path, boolean overwrite) { Path p = new Path(path); URI uri = p.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.create(p, overwrite); } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } @Override public boolean delete(String path) { Path p = new Path(path); URI uri = p.toUri(); try { FileSystem fs = FileSystem.get(uri, CONF); return fs.delete(p, true); } catch (IOException e) { throw new HDFSIOException(path, CONF.toString(), e); } } }
package hudson.model; import hudson.tasks.Mailer; import hudson.tasks.Maven; import hudson.tasks.Publisher; import hudson.tasks.junit.JUnitResultArchiver; import hudson.triggers.SCMTrigger; import hudson.triggers.TimerTrigger; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import java.io.File; import java.net.URISyntaxException; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.mockStatic; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; @RunWith(PowerMockRunner.class) @PrepareForTest({Hudson.class, SCMTrigger.DescriptorImpl.class, TimerTrigger.DescriptorImpl.class, Mailer.DescriptorImpl.class, JUnitResultArchiver.DescriptorImpl.class}) public class LegacyProjectTest { private File config; @Before public void setUp() throws URISyntaxException { config = new File(FreeStyleProject.class.getResource("/hudson/model/freestyle").toURI()); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether CustomWorkspace is configured based * on legacy value. * * @throws Exception if any. */ @Test public void testConvertLegacyCustomWorkspaceProperty() throws Exception { FreeStyleProject project = (FreeStyleProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(FreeStyleProject.CUSTOM_WORKSPACE_PROPERTY_NAME)); project.convertCustomWorkspaceProperty(); assertNotNull(project.getProperty(FreeStyleProject.CUSTOM_WORKSPACE_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether Builders * from Project are configured * * @throws Exception if any. */ @Test public void testConvertLegacyBuildersProperty() throws Exception { Project project = (Project) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); //Property should be null, because of legacy implementation. Version < 2.2.0 assertNull(project.getProperty(Project.BUILDERS_PROPERTY_NAME)); project.convertBuildersProjectProperty(); //Verify builders assertNotNull(project.getProperty(Project.BUILDERS_PROPERTY_NAME)); assertFalse(project.getBuildersList().isEmpty()); assertEquals(1, project.getBuildersList().size()); assertTrue(project.getBuildersList().get(0) instanceof Maven); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether BuildWrappers * from Project are configured * * @throws Exception if any. */ @Test @Ignore //TODO re-implement this method according to new implementation. Logic is similar to testConvertPublishersProperty public void testConvertLegacyBuildWrappersProperty() throws Exception { Project project = (Project) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); //Property should be null, because of legacy implementation. Version < 2.2.0 project.convertBuildWrappersProjectProperties(); //Verify buildWrappers assertTrue(project.getBuildWrappersList().isEmpty()); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether publishers * from Project are configured * * @throws Exception if any. */ @Test public void testConvertPublishersProperty() throws Exception { Project project = (Project) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); Hudson hudson = createMock(Hudson.class); String mailerKey = "hudson-tasks-Mailer"; Descriptor<Publisher> mailerDescriptor = createMock(Mailer.DescriptorImpl.class); expect(mailerDescriptor.getJsonSafeClassName()).andReturn(mailerKey); expect(hudson.getDescriptorOrDie(Mailer.class)).andReturn(mailerDescriptor); String jUnitKey = "hudson-task-JUnitResultArchiver"; Descriptor<Publisher> junitDescriptor = createMock(JUnitResultArchiver.DescriptorImpl.class); expect(junitDescriptor.getJsonSafeClassName()).andReturn(jUnitKey); expect(hudson.getDescriptorOrDie(JUnitResultArchiver.class)).andReturn(junitDescriptor); mockStatic(Hudson.class); expect(Hudson.getInstance()).andReturn(hudson).anyTimes(); replayAll(); //Publishers should be null, because of legacy implementation. Version < 2.2.0 assertNull(project.getProperty(mailerKey)); assertNull(project.getProperty(jUnitKey)); project.convertPublishersProperties(); //Verify publishers assertNotNull(project.getProperty(mailerKey).getValue()); assertNotNull(project.getProperty(jUnitKey).getValue()); verifyAll(); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyBlockBuildWhenDownstreamBuildingProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME)); project.convertBlockBuildWhenDownstreamBuildingProperty(); assertNotNull(project.getProperty(AbstractProject.BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyBlockBuildWhenUpstreamBuildingProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME)); project.convertBlockBuildWhenUpstreamBuildingProperty(); assertNotNull(project.getProperty(AbstractProject.BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyConcurrentBuildProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.CONCURRENT_BUILD_PROPERTY_NAME)); project.convertConcurrentBuildProperty(); assertNotNull(project.getProperty(AbstractProject.CONCURRENT_BUILD_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyCleanWorkspaceRequiredProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME)); project.convertCleanWorkspaceRequiredProperty(); assertNotNull(project.getProperty(AbstractProject.CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyQuietPeriodProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.QUIET_PERIOD_PROPERTY_NAME)); project.convertQuietPeriodProperty(); assertNotNull(project.getProperty(AbstractProject.QUIET_PERIOD_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyScmCheckoutRetryCountProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME)); project.convertScmCheckoutRetryCountProperty(); assertNotNull(project.getProperty(AbstractProject.SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether expected property * from AbstractProject is configured * * @throws Exception if any. */ @Test public void testConvertLegacyJDKProperty() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(AbstractProject.JDK_PROPERTY_NAME)); project.convertJDKProperty(); assertNotNull(project.getProperty(AbstractProject.JDK_PROPERTY_NAME)); } /** * Tests unmarshalls FreeStyleProject configuration and checks whether LogRotator * from Job are configured * * @throws Exception if any. */ @Test public void testConvertLegacyLogRotatorProperty() throws Exception { Job project = (Job) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(Job.LOG_ROTATOR_PROPERTY_NAME)); project.convertLogRotatorProperty(); assertNotNull(project.getProperty(Job.LOG_ROTATOR_PROPERTY_NAME)); } /** * Tests unmarshalling FreeStyleProject configuration and checks whether Triggers properties * from Job are configured. * * @throws Exception if any. */ @Test public void testConvertLegacyTriggers() throws Exception { AbstractProject project = (AbstractProject) Items.getConfigFile(config).read(); project.setAllowSave(false); project.initProjectProperties(); Hudson hudson = createMock(Hudson.class); String scmTriggerPropertyKey = "hudson-trigger-SCMTrigger"; TriggerDescriptor scmTriggerDescriptor = createMock(SCMTrigger.DescriptorImpl.class); expect(scmTriggerDescriptor.getJsonSafeClassName()).andReturn(scmTriggerPropertyKey); expect(hudson.getDescriptorOrDie(SCMTrigger.class)).andReturn(scmTriggerDescriptor); String timerTriggerPropertyKey = "hudson-trigger-TimerTrigger"; TriggerDescriptor timerTriggerDescriptor = createMock(TimerTrigger.DescriptorImpl.class); expect(timerTriggerDescriptor.getJsonSafeClassName()).andReturn(timerTriggerPropertyKey); expect(hudson.getDescriptorOrDie(TimerTrigger.class)).andReturn(timerTriggerDescriptor); mockStatic(Hudson.class); expect(Hudson.getInstance()).andReturn(hudson).anyTimes(); replayAll(); project.setAllowSave(false); project.initProjectProperties(); assertNull(project.getProperty(scmTriggerPropertyKey)); assertNull(project.getProperty(timerTriggerPropertyKey)); project.convertTriggerProperties(); assertNotNull(project.getProperty(scmTriggerPropertyKey)); Trigger trigger = (Trigger) project.getProperty(scmTriggerPropertyKey).getValue(); assertEquals("5 * * * *", trigger.getSpec()); assertNotNull(project.getProperty(timerTriggerPropertyKey)); trigger = (Trigger) project.getProperty(timerTriggerPropertyKey).getValue(); assertEquals("*/10 * * * *", trigger.getSpec()); verifyAll(); } }
package net.bytebuddy.asm; import lombok.EqualsAndHashCode; import net.bytebuddy.ClassFileVersion; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.MethodList; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.method.ParameterList; import net.bytebuddy.description.type.TypeDefinition; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeList; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.TargetType; import net.bytebuddy.dynamic.scaffold.FieldLocator; import net.bytebuddy.dynamic.scaffold.InstrumentedType; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.SuperMethodCall; import net.bytebuddy.implementation.bytecode.*; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.implementation.bytecode.collection.ArrayAccess; import net.bytebuddy.implementation.bytecode.collection.ArrayFactory; import net.bytebuddy.implementation.bytecode.constant.*; import net.bytebuddy.implementation.bytecode.member.FieldAccess; import net.bytebuddy.implementation.bytecode.member.MethodInvocation; import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.pool.TypePool; import net.bytebuddy.utility.CompoundList; import net.bytebuddy.utility.JavaType; import net.bytebuddy.utility.visitor.ExceptionTableSensitiveMethodVisitor; import net.bytebuddy.utility.visitor.LineNumberPrependingMethodVisitor; import net.bytebuddy.utility.visitor.StackAwareMethodVisitor; import org.objectweb.asm.*; import org.objectweb.asm.Type; import java.io.IOException; import java.io.Serializable; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; import static net.bytebuddy.matcher.ElementMatchers.named; @EqualsAndHashCode public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper, Implementation { /** * Indicates that no class reader is available to an adice method. */ private static final ClassReader UNDEFINED = null; /** * A reference to the {@link OnMethodEnter#inline()} method. */ private static final MethodDescription.InDefinedShape INLINE_ENTER; /** * A reference to the {@link OnMethodEnter#suppress()} method. */ private static final MethodDescription.InDefinedShape SUPPRESS_ENTER; /** * A reference to the {@link OnMethodEnter#prependLineNumber()} method. */ private static final MethodDescription.InDefinedShape PREPEND_LINE_NUMBER; /** * A reference to the {@link OnMethodEnter#skipOn()} method. */ private static final MethodDescription.InDefinedShape SKIP_ON; /** * A reference to the {@link OnMethodExit#inline()} method. */ private static final MethodDescription.InDefinedShape INLINE_EXIT; /** * A reference to the {@link OnMethodExit#suppress()} method. */ private static final MethodDescription.InDefinedShape SUPPRESS_EXIT; /** * A reference to the {@link OnMethodExit#onThrowable()} method. */ private static final MethodDescription.InDefinedShape ON_THROWABLE; /* * Extracts the annotation values for the enter and exit advice annotations. */ static { MethodList<MethodDescription.InDefinedShape> enter = new TypeDescription.ForLoadedType(OnMethodEnter.class).getDeclaredMethods(); INLINE_ENTER = enter.filter(named("inline")).getOnly(); SUPPRESS_ENTER = enter.filter(named("suppress")).getOnly(); SKIP_ON = enter.filter(named("skipOn")).getOnly(); PREPEND_LINE_NUMBER = enter.filter(named("prependLineNumber")).getOnly(); MethodList<MethodDescription.InDefinedShape> exit = new TypeDescription.ForLoadedType(OnMethodExit.class).getDeclaredMethods(); INLINE_EXIT = exit.filter(named("inline")).getOnly(); SUPPRESS_EXIT = exit.filter(named("suppress")).getOnly(); ON_THROWABLE = exit.filter(named("onThrowable")).getOnly(); } /** * The dispatcher for instrumenting the instrumented method upon entering. */ private final Dispatcher.Resolved.ForMethodEnter methodEnter; /** * The dispatcher for instrumenting the instrumented method upon exiting. */ private final Dispatcher.Resolved.ForMethodExit methodExit; /** * The assigner to use. */ private final Assigner assigner; /** * The stack manipulation to apply within a suppression handler. */ private final StackManipulation exceptionHandler; /** * The delegate implementation to apply if this advice is used as an instrumentation. */ private final Implementation delegate; /** * Creates a new advice. * * @param methodEnter The dispatcher for instrumenting the instrumented method upon entering. * @param methodExit The dispatcher for instrumenting the instrumented method upon exiting. */ protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit) { this(methodEnter, methodExit, Assigner.DEFAULT, Removal.of(TypeDescription.THROWABLE), SuperMethodCall.INSTANCE); } /** * Creates a new advice. * * @param methodEnter The dispatcher for instrumenting the instrumented method upon entering. * @param methodExit The dispatcher for instrumenting the instrumented method upon exiting. * @param assigner The assigner to use. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @param delegate The delegate implementation to apply if this advice is used as an instrumentation. */ private Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, Assigner assigner, StackManipulation exceptionHandler, Implementation delegate) { this.methodEnter = methodEnter; this.methodExit = methodExit; this.assigner = assigner; this.exceptionHandler = exceptionHandler; this.delegate = delegate; } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param advice The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> advice) { return to(advice, ClassFileLocator.ForClassLoader.of(advice.getClassLoader())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param advice The type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> advice, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(advice), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational * class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set * to {@code false} are resolvable by the returned instance. * * @param advice The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription advice) { return to(advice, ClassFileLocator.NoOp.INSTANCE); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param advice A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription advice, ClassFileLocator classFileLocator) { return to(advice, classFileLocator, Collections.<OffsetMapping.Factory<?>>emptyList()); } /** * Creates a new advice. * * @param advice A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @param userFactories A list of custom factories for user generated offset mappings. * @return A method visitor wrapper representing the supplied advice. */ protected static Advice to(TypeDescription advice, ClassFileLocator classFileLocator, List<? extends OffsetMapping.Factory<?>> userFactories) { Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE; for (MethodDescription.InDefinedShape methodDescription : advice.getDeclaredMethods()) { methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription); methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription); } if (!methodEnter.isAlive() && !methodExit.isAlive()) { throw new IllegalArgumentException("No advice defined by " + advice); } try { ClassReader classReader = methodEnter.isBinary() || methodExit.isBinary() ? new ClassReader(classFileLocator.locate(advice.getName()).resolve()) : UNDEFINED; Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, classReader); return new Advice(resolved, methodExit.asMethodExitTo(userFactories, classReader, resolved)); } catch (IOException exception) { throw new IllegalStateException("Error reading class file of " + advice, exception); } } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> enterAdvice, Class<?> exitAdvice) { ClassLoader enterLoader = enterAdvice.getClassLoader(), exitLoader = exitAdvice.getClassLoader(); return to(enterAdvice, exitAdvice, enterLoader == exitLoader ? ClassFileLocator.ForClassLoader.of(enterLoader) : new ClassFileLocator.Compound(ClassFileLocator.ForClassLoader.of(enterLoader), ClassFileLocator.ForClassLoader.of(exitLoader))); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> enterAdvice, Class<?> exitAdvice, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(enterAdvice), new TypeDescription.ForLoadedType(exitAdvice), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational * class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set * to {@code false} are resolvable by the returned instance. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice) { return to(enterAdvice, exitAdvice, ClassFileLocator.NoOp.INSTANCE); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice, ClassFileLocator classFileLocator) { return to(enterAdvice, exitAdvice, classFileLocator, Collections.<OffsetMapping.Factory<?>>emptyList()); } /** * Creates a new advice. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @param userFactories A list of custom factories for user generated offset mappings. * @return A method visitor wrapper representing the supplied advice. */ protected static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice, ClassFileLocator classFileLocator, List<? extends OffsetMapping.Factory<?>> userFactories) { Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE; for (MethodDescription.InDefinedShape methodDescription : enterAdvice.getDeclaredMethods()) { methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription); } if (!methodEnter.isAlive()) { throw new IllegalArgumentException("No enter advice defined by " + enterAdvice); } for (MethodDescription.InDefinedShape methodDescription : exitAdvice.getDeclaredMethods()) { methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription); } if (!methodExit.isAlive()) { throw new IllegalArgumentException("No enter advice defined by " + exitAdvice); } try { Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, methodEnter.isBinary() ? new ClassReader(classFileLocator.locate(enterAdvice.getName()).resolve()) : UNDEFINED); return new Advice(resolved, methodExit.asMethodExitTo(userFactories, methodExit.isBinary() ? new ClassReader(classFileLocator.locate(exitAdvice.getName()).resolve()) : UNDEFINED, resolved)); } catch (IOException exception) { throw new IllegalStateException("Error reading class file of " + enterAdvice + " or " + exitAdvice, exception); } } /** * Locates a dispatcher for the method if available. * * @param type The annotation type that indicates a given form of advice that is currently resolved. * @param property An annotation property that indicates if the advice method should be inlined. * @param dispatcher Any previous dispatcher that was discovered or {@code null} if no such dispatcher was yet found. * @param methodDescription The method description that is considered as an advice method. * @return A resolved dispatcher or {@code null} if no dispatcher was resolved. */ private static Dispatcher.Unresolved locate(Class<? extends Annotation> type, MethodDescription.InDefinedShape property, Dispatcher.Unresolved dispatcher, MethodDescription.InDefinedShape methodDescription) { AnnotationDescription annotation = methodDescription.getDeclaredAnnotations().ofType(type); if (annotation == null) { return dispatcher; } else if (dispatcher.isAlive()) { throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription); } else if (!methodDescription.isStatic()) { throw new IllegalStateException("Advice for " + methodDescription + " is not static"); } else { return annotation.getValue(property).resolve(Boolean.class) ? new Dispatcher.Inlining(methodDescription) : new Dispatcher.Delegating(methodDescription); } } /** * Allows for the configuration of custom annotations that are then bound to a dynamically computed, constant value. * * @return A builder for an {@link Advice} instrumentation with custom values. * @see OffsetMapping.Factory */ public static WithCustomMapping withCustomMapping() { return new WithCustomMapping(); } /** * Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods. * * @param matcher The matcher identifying methods to apply the advice to. * @return A suitable ASM visitor wrapper with the <i>compute frames</i> option enabled. */ public AsmVisitorWrapper.ForDeclaredMethods on(ElementMatcher<? super MethodDescription> matcher) { return new AsmVisitorWrapper.ForDeclaredMethods().method(matcher, this); } @Override public MethodVisitor wrap(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, TypePool typePool, int writerFlags, int readerFlags) { return instrumentedMethod.isAbstract() || instrumentedMethod.isNative() ? methodVisitor : doWrap(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, writerFlags, readerFlags); } /** * Wraps the method visitor to implement this advice. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor to write to. * @param implementationContext The implementation context to use. * @param writerFlags The ASM writer flags to use. * @param readerFlags The ASM reader flags to use. * @return A method visitor that applies this advice. */ protected MethodVisitor doWrap(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, int writerFlags, int readerFlags) { methodVisitor = methodEnter.isPrependLineNumber() ? new LineNumberPrependingMethodVisitor(methodVisitor) : methodVisitor; if (!methodExit.isAlive()) { return new AdviceVisitor.WithoutExitAdvice(methodVisitor, implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, writerFlags, readerFlags); } else if (methodExit.getThrowable().represents(NoExceptionHandler.class)) { return new AdviceVisitor.WithExitAdvice.WithoutExceptionHandling(methodVisitor, implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, methodExit, writerFlags, readerFlags); } else if (instrumentedMethod.isConstructor()) { throw new IllegalStateException("Cannot catch exception during constructor call for " + instrumentedMethod); } else { return new AdviceVisitor.WithExitAdvice.WithExceptionHandling(methodVisitor, implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, methodExit, writerFlags, readerFlags, methodExit.getThrowable()); } } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return delegate.prepare(instrumentedType); } @Override public ByteCodeAppender appender(Target implementationTarget) { return new Appender(this, implementationTarget, delegate.appender(implementationTarget)); } /** * Configures this advice to use the specified assigner. Any previous or default assigner is replaced. * * @param assigner The assigner to use, * @return A version of this advice that uses the specified assigner. */ public Advice withAssigner(Assigner assigner) { return new Advice(methodEnter, methodExit, assigner, exceptionHandler, delegate); } /** * Configures this advice to call {@link Throwable#printStackTrace()} upon a suppressed exception. * * @return A version of this advice that prints any suppressed exception. */ public Advice withExceptionPrinting() { try { return withExceptionHandler(MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Throwable.class.getMethod("printStackTrace")))); } catch (NoSuchMethodException exception) { throw new IllegalStateException("Cannot locate Throwable::printStackTrace"); } } /** * Configures this advice to execute the given stack manipulation upon a suppressed exception. The stack manipulation is executed with a * {@link Throwable} instance on the operand stack. The stack must be empty upon completing the exception handler. * * @param exceptionHandler The exception handler to apply. * @return A version of this advice that applies the supplied exception handler. */ public Advice withExceptionHandler(StackManipulation exceptionHandler) { return new Advice(methodEnter, methodExit, assigner, exceptionHandler, delegate); } /** * Wraps the supplied implementation to have this advice applied around it. * * @param implementation The implementation to wrap. * @return An implementation that applies the supplied implementation and wraps it with this advice. */ public Implementation wrap(Implementation implementation) { return new Advice(methodEnter, methodExit, assigner, exceptionHandler, implementation); } /** * Represents an offset mapping for an advice method to an alternative offset. */ public interface OffsetMapping { /** * Resolves an offset mapping to a given target offset. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method for which the mapping is to be resolved. * @param assigner The assigner to use. * @param context The context in which the offset mapping is applied. * @return A suitable target mapping. */ Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context); /** * A context for applying an {@link OffsetMapping}. */ interface Context { /** * Returns {@code true} if the advice is applied on a fully initialized instance, i.e. describes if the {@code this} * instance is available or still uninitialized during calling the advice. * * @return {@code true} if the advice is applied onto a fully initialized method. */ boolean isInitialized(); /** * Returns the padding before writing additional values that this context applies. * * @return The required padding for this context. */ int getPadding(); /** * A context for an offset mapping describing a method entry. */ enum ForMethodEntry implements Context { /** * Describes a context for a method entry that is not a constructor. */ INITIALIZED(true), /** * Describes a context for a method entry that is a constructor. */ NON_INITIALIZED(false); /** * Resolves an appropriate method entry context for the supplied instrumented method. * * @param instrumentedMethod The instrumented method. * @return An appropriate context. */ protected static Context of(MethodDescription instrumentedMethod) { return instrumentedMethod.isConstructor() ? NON_INITIALIZED : INITIALIZED; } /** * {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry. */ private final boolean initialized; /** * Creates a new context for a method entry. * * @param initialized {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry. */ ForMethodEntry(boolean initialized) { this.initialized = initialized; } @Override public boolean isInitialized() { return initialized; } @Override public int getPadding() { return StackSize.ZERO.getSize(); } } /** * A context for an offset mapping describing a method exit. */ enum ForMethodExit implements Context { /** * A method exit with a zero sized padding. */ ZERO(StackSize.ZERO), /** * A method exit with a single slot padding. */ SINGLE(StackSize.SINGLE), /** * A method exit with a double slot padding. */ DOUBLE(StackSize.DOUBLE); /** * The padding implied by this method exit. */ private final StackSize stackSize; /** * Creates a new context for a method exit. * * @param stackSize The padding implied by this method exit. */ ForMethodExit(StackSize stackSize) { this.stackSize = stackSize; } /** * Resolves an appropriate method exit context for the supplied entry method type. * * @param typeDescription The type that is returned by the enter method. * @return An appropriate context for the supplied entry method type. */ protected static Context of(TypeDefinition typeDescription) { switch (typeDescription.getStackSize()) { case ZERO: return ZERO; case SINGLE: return SINGLE; case DOUBLE: return DOUBLE; default: throw new IllegalStateException("Unknown stack size: " + typeDescription); } } @Override public boolean isInitialized() { return true; } @Override public int getPadding() { return stackSize.getSize(); } } } /** * A target offset of an offset mapping. */ interface Target { /** * Resolves a read instruction. * * @return A stack manipulation that represents a reading of an advice parameter. */ StackManipulation resolveRead(); /** * Resolves a write instruction. * * @return A stack manipulation that represents a writing to an advice parameter. */ StackManipulation resolveWrite(); /** * Resolves an increment instruction. * * @param value The incrementation value. * @return A stack manipulation that represents a writing to an advice parameter. */ StackManipulation resolveIncrement(int value); /** * A target for an offset mapping that represents a non-operational value. All writes are discarded and a value's * default value is returned upon every read. */ @EqualsAndHashCode abstract class ForDefaultValue implements Target { /** * The represented type. */ protected final TypeDefinition typeDefinition; /** * A stack manipulation to apply after a read instruction. */ protected final StackManipulation readAssignment; /** * Creates a new target for a default value. * * @param typeDefinition The represented type. * @param readAssignment A stack manipulation to apply after a read instruction. */ protected ForDefaultValue(TypeDefinition typeDefinition, StackManipulation readAssignment) { this.typeDefinition = typeDefinition; this.readAssignment = readAssignment; } @Override public StackManipulation resolveRead() { return new StackManipulation.Compound(DefaultValue.of(typeDefinition), readAssignment); } /** * A read-only target for a default value. */ protected static class ReadOnly extends ForDefaultValue { /** * Creates a new writable target for a default value. * * @param typeDefinition The represented type. */ protected ReadOnly(TypeDefinition typeDefinition) { this(typeDefinition, StackManipulation.Trivial.INSTANCE); } /** * Creates a new -writable target for a default value. * * @param typeDefinition The represented type. * @param readAssignment A stack manipulation to apply after a read instruction. */ protected ReadOnly(TypeDefinition typeDefinition, StackManipulation readAssignment) { super(typeDefinition, readAssignment); } @Override public StackManipulation resolveWrite() { throw new IllegalStateException("Cannot write to read-only default value"); } @Override public StackManipulation resolveIncrement(int value) { throw new IllegalStateException("Cannot write to read-only default value"); } } /** * A read-write target for a default value. */ protected static class ReadWrite extends ForDefaultValue { /** * Creates a new read-only target for a default value. * * @param typeDefinition The represented type. */ protected ReadWrite(TypeDefinition typeDefinition) { this(typeDefinition, StackManipulation.Trivial.INSTANCE); } /** * Creates a new read-only target for a default value. * * @param typeDefinition The represented type. * @param readAssignment A stack manipulation to apply after a read instruction. */ protected ReadWrite(TypeDefinition typeDefinition, StackManipulation readAssignment) { super(typeDefinition, readAssignment); } @Override public StackManipulation resolveWrite() { return Removal.of(typeDefinition); } @Override public StackManipulation resolveIncrement(int value) { return StackManipulation.Trivial.INSTANCE; } } } /** * A target for an offset mapping that represents a local variable. */ @EqualsAndHashCode abstract class ForVariable implements Target { /** * The represented type. */ protected final TypeDefinition typeDefinition; /** * The value's offset. */ protected final int offset; /** * An assignment to execute upon reading a value. */ protected final StackManipulation readAssignment; /** * Creates a new target for a local variable mapping. * * @param typeDefinition The represented type. * @param offset The value's offset. * @param readAssignment An assignment to execute upon reading a value. */ protected ForVariable(TypeDefinition typeDefinition, int offset, StackManipulation readAssignment) { this.typeDefinition = typeDefinition; this.offset = offset; this.readAssignment = readAssignment; } @Override public StackManipulation resolveRead() { return new StackManipulation.Compound(MethodVariableAccess.of(typeDefinition).loadFrom(offset), readAssignment); } /** * A target for a read-only mapping of a local variable. */ protected static class ReadOnly extends ForVariable { /** * Creates a read-only mapping for a local variable. * * @param parameterDescription The mapped parameter. * @param readAssignment An assignment to execute upon reading a value. */ protected ReadOnly(ParameterDescription parameterDescription, StackManipulation readAssignment) { this(parameterDescription.getType(), parameterDescription.getOffset(), readAssignment); } /** * Creates a read-only mapping for a local variable. * * @param typeDefinition The represented type. * @param offset The value's offset. * @param readAssignment An assignment to execute upon reading a value. */ protected ReadOnly(TypeDefinition typeDefinition, int offset, StackManipulation readAssignment) { super(typeDefinition, offset, readAssignment); } @Override public StackManipulation resolveWrite() { throw new IllegalStateException("Cannot write to read-only parameter " + typeDefinition + " at " + offset); } @Override public StackManipulation resolveIncrement(int value) { throw new IllegalStateException("Cannot write to read-only variable " + typeDefinition + " at " + offset); } } /** * A target for a writable mapping of a local variable. */ @EqualsAndHashCode(callSuper = true) protected static class ReadWrite extends ForVariable { /** * A stack manipulation to apply upon a write to the variable. */ private final StackManipulation writeAssignment; /** * Creates a new target mapping for a writable local variable. * * @param parameterDescription The mapped parameter. * @param readAssignment An assignment to execute upon reading a value. * @param writeAssignment A stack manipulation to apply upon a write to the variable. */ protected ReadWrite(ParameterDescription parameterDescription, StackManipulation readAssignment, StackManipulation writeAssignment) { this(parameterDescription.getType(), parameterDescription.getOffset(), readAssignment, writeAssignment); } /** * Creates a new target mapping for a writable local variable. * * @param typeDefinition The represented type. * @param offset The value's offset. * @param readAssignment An assignment to execute upon reading a value. * @param writeAssignment A stack manipulation to apply upon a write to the variable. */ protected ReadWrite(TypeDefinition typeDefinition, int offset, StackManipulation readAssignment, StackManipulation writeAssignment) { super(typeDefinition, offset, readAssignment); this.writeAssignment = writeAssignment; } @Override public StackManipulation resolveWrite() { return new StackManipulation.Compound(writeAssignment, MethodVariableAccess.of(typeDefinition).storeAt(offset)); } @Override public StackManipulation resolveIncrement(int value) { return typeDefinition.represents(int.class) ? MethodVariableAccess.of(typeDefinition).increment(offset, value) : new StackManipulation.Compound(resolveRead(), IntegerConstant.forValue(1), Addition.INTEGER, resolveWrite()); } } } /** * A target mapping for an array of all local variables. */ @EqualsAndHashCode abstract class ForArray implements Target { /** * The compound target type. */ protected final TypeDescription.Generic target; /** * The stack manipulations to apply upon reading a variable array. */ protected final List<? extends StackManipulation> valueReads; /** * Creates a new target mapping for an array of all local variables. * * @param target The compound target type. * @param valueReads The stack manipulations to apply upon reading a variable array. */ protected ForArray(TypeDescription.Generic target, List<? extends StackManipulation> valueReads) { this.target = target; this.valueReads = valueReads; } @Override public StackManipulation resolveRead() { return ArrayFactory.forType(target).withValues(valueReads); } @Override public StackManipulation resolveIncrement(int value) { throw new IllegalStateException("Cannot increment read-only array value"); } /** * A target mapping for a read-only target mapping for an array of local variables. */ protected static class ReadOnly extends ForArray { /** * Creates a read-only target mapping for an array of all local variables. * * @param target The compound target type. * @param valueReads The stack manipulations to apply upon reading a variable array. */ protected ReadOnly(TypeDescription.Generic target, List<? extends StackManipulation> valueReads) { super(target, valueReads); } @Override public StackManipulation resolveWrite() { throw new IllegalStateException("Cannot write to read-only array value"); } } /** * A target mapping for a writable target mapping for an array of local variables. */ @EqualsAndHashCode(callSuper = true) protected static class ReadWrite extends ForArray { /** * The stack manipulations to apply upon writing to a variable array. */ private final List<? extends StackManipulation> valueWrites; /** * Creates a writable target mapping for an array of all local variables. * * @param target The compound target type. * @param valueReads The stack manipulations to apply upon reading a variable array. * @param valueWrites The stack manipulations to apply upon writing to a variable array. */ protected ReadWrite(TypeDescription.Generic target, List<? extends StackManipulation> valueReads, List<? extends StackManipulation> valueWrites) { super(target, valueReads); this.valueWrites = valueWrites; } @Override public StackManipulation resolveWrite() { return ArrayAccess.of(target).forEach(valueWrites); } } } /** * A target for an offset mapping that loads a field value. */ @EqualsAndHashCode abstract class ForField implements Target { /** * The field value to load. */ protected final FieldDescription fieldDescription; /** * The stack manipulation to apply upon a read. */ protected final StackManipulation readAssignment; /** * Creates a new target for a field value mapping. * * @param fieldDescription The field value to load. * @param readAssignment The stack manipulation to apply upon a read. */ protected ForField(FieldDescription fieldDescription, StackManipulation readAssignment) { this.fieldDescription = fieldDescription; this.readAssignment = readAssignment; } @Override public StackManipulation resolveRead() { return new StackManipulation.Compound(fieldDescription.isStatic() ? StackManipulation.Trivial.INSTANCE : MethodVariableAccess.loadThis(), FieldAccess.forField(fieldDescription).read(), readAssignment); } /** * A read-only mapping for a field value. */ static class ReadOnly extends ForField { /** * Creates a new read-only mapping for a field. * * @param fieldDescription The field value to load. * @param readAssignment The stack manipulation to apply upon a read. */ protected ReadOnly(FieldDescription fieldDescription, StackManipulation readAssignment) { super(fieldDescription, readAssignment); } @Override public StackManipulation resolveWrite() { throw new IllegalStateException("Cannot write to read-only field value"); } @Override public StackManipulation resolveIncrement(int value) { throw new IllegalStateException("Cannot write to read-only field value"); } } /** * A mapping for a writable field. */ @EqualsAndHashCode(callSuper = true) static class ReadWrite extends ForField { /** * An assignment to apply prior to a field write. */ private final StackManipulation writeAssignment; /** * Creates a new target for a writable field. * * @param fieldDescription The field value to load. * @param readAssignment The stack manipulation to apply upon a read. * @param writeAssignment An assignment to apply prior to a field write. */ protected ReadWrite(FieldDescription fieldDescription, StackManipulation readAssignment, StackManipulation writeAssignment) { super(fieldDescription, readAssignment); this.writeAssignment = writeAssignment; } @Override public StackManipulation resolveWrite() { StackManipulation preparation; if (fieldDescription.isStatic()) { preparation = StackManipulation.Trivial.INSTANCE; } else { preparation = new StackManipulation.Compound( MethodVariableAccess.loadThis(), Duplication.SINGLE.flipOver(fieldDescription.getType()), Removal.SINGLE ); } return new StackManipulation.Compound(preparation, FieldAccess.forField(fieldDescription).write()); } @Override public StackManipulation resolveIncrement(int value) { return new StackManipulation.Compound( resolveRead(), IntegerConstant.forValue(value), Addition.INTEGER, resolveWrite() ); } } } /** * A target for an offset mapping that represents a read-only stack manipulation. */ @EqualsAndHashCode class ForStackManipulation implements Target { /** * The represented stack manipulation. */ private final StackManipulation stackManipulation; /** * Creates a new target for an offset mapping for a stack manipulation. * * @param stackManipulation The represented stack manipulation. */ protected ForStackManipulation(StackManipulation stackManipulation) { this.stackManipulation = stackManipulation; } /** * Creates a target for a {@link Method} or {@link Constructor} constant. * * @param methodDescription The method or constructor to represent. * @return A mapping for a method or constructor constant. */ protected static Target of(MethodDescription.InDefinedShape methodDescription) { return new ForStackManipulation(MethodConstant.forMethod(methodDescription)); } /** * Creates a target for an offset mapping for a type constant. * * @param typeDescription The type constant to represent. * @return A mapping for a type constant. */ protected static Target of(TypeDescription typeDescription) { return new ForStackManipulation(ClassConstant.of(typeDescription)); } /** * Creates a target for an offset mapping for a constant string. * * @param value The constant string value to represent. * @return A mapping for a constant string. */ protected static Target of(String value) { return new ForStackManipulation(new TextConstant(value)); } /** * Creates a target for an offset mapping for a constant value. * * @param value The constant value to represent. * @return An appropriate target for an offset mapping. */ protected static Target of(Object value) { if (value instanceof Boolean) { return new ForStackManipulation(IntegerConstant.forValue((Boolean) value)); } else if (value instanceof Byte) { return new ForStackManipulation(IntegerConstant.forValue((Byte) value)); } else if (value instanceof Short) { return new ForStackManipulation(IntegerConstant.forValue((Short) value)); } else if (value instanceof Character) { return new ForStackManipulation(IntegerConstant.forValue((Character) value)); } else if (value instanceof Integer) { return new ForStackManipulation(IntegerConstant.forValue((Integer) value)); } else if (value instanceof Long) { return new ForStackManipulation(LongConstant.forValue((Long) value)); } else if (value instanceof Float) { return new ForStackManipulation(FloatConstant.forValue((Float) value)); } else if (value instanceof Double) { return new ForStackManipulation(DoubleConstant.forValue((Double) value)); } else if (value instanceof String) { return new ForStackManipulation(new TextConstant((String) value)); } else { throw new IllegalArgumentException("Not a constant value: " + value); } } @Override public StackManipulation resolveRead() { return stackManipulation; } @Override public StackManipulation resolveWrite() { throw new IllegalStateException("Cannot write to constant value: " + stackManipulation); } @Override public StackManipulation resolveIncrement(int value) { throw new IllegalStateException("Cannot write to constant value: " + stackManipulation); } } } /** * Represents a factory for creating a {@link OffsetMapping} for a given parameter for a given annotation. * * @param <T> the annotation type that triggers this factory. */ interface Factory<T extends Annotation> { boolean DELEGATION = true; boolean INLINING = false; /** * Returns the annotation type of this factory. * * @return The factory's annotation type. */ Class<T> getAnnotationType(); /** * Creates a new offset mapping for the supplied parameter if possible. * * @param target The parameter description for which to resolve an offset mapping. * @param annotation The annotation that triggered this factory. * @param delegation {@code true} if the binding is applied using advice method delegation. * @return A resolved offset mapping or {@code null} if no mapping can be resolved for this parameter. */ OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation); } /** * An offset mapping for a given parameter of the instrumented method. */ @EqualsAndHashCode abstract class ForArgument implements OffsetMapping { /** * The type expected by the advice method. */ private final TypeDescription.Generic target; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The typing to apply when assigning values. */ private final Assigner.Typing typing; /** * Creates a new offset mapping for a parameter of the instrumented method. * * @param target The type expected by the advice method. * @param readOnly Determines if the parameter is to be treated as read-only. * @param typing The typing to apply. */ protected ForArgument(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) { this.target = target; this.readOnly = readOnly; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { ParameterDescription parameterDescription = resolve(instrumentedMethod); StackManipulation readAssignment = assigner.assign(parameterDescription.getType(), target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + target); } else if (readOnly) { return new Target.ForVariable.ReadOnly(parameterDescription, readAssignment); } else { StackManipulation writeAssignment = assigner.assign(target, parameterDescription.getType(), typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + target); } return new Target.ForVariable.ReadWrite(parameterDescription, readAssignment, writeAssignment); } } /** * Resolves the bound parameter. * * @param instrumentedMethod The instrumented method. * @return The bound parameter. */ protected abstract ParameterDescription resolve(MethodDescription instrumentedMethod); @EqualsAndHashCode(callSuper = true) public static class Unresolved extends ForArgument { /** * The index of the parameter. */ private final int index; public Unresolved(TypeDescription.Generic target, Argument argument) { this(target, argument.readOnly(), argument.typing(), argument.value()); } protected Unresolved(ParameterDescription parameterDescription) { this(parameterDescription.getType(), true, Assigner.Typing.STATIC, parameterDescription.getIndex()); } public Unresolved(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, int index) { super(target, readOnly, typing); this.index = index; } @Override protected ParameterDescription resolve(MethodDescription instrumentedMethod) { ParameterList<?> parameters = instrumentedMethod.getParameters(); if (parameters.size() <= index) { throw new IllegalStateException(instrumentedMethod + " does not define an index " + index); } else { return parameters.get(index); } } /** * A factory for a mapping of a parameter of the instrumented method. */ protected enum Factory implements OffsetMapping.Factory<Argument> { INSTANCE; @Override public Class<Argument> getAnnotationType() { return Argument.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Argument> annotation, boolean delegation) { if (delegation && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot define writable field access for " + target + " when using delegation"); } else { return new ForArgument.Unresolved(target.getType(), annotation.loadSilent()); } } } } @EqualsAndHashCode(callSuper = true) public static class Resolved extends ForArgument { private final ParameterDescription parameterDescription; public Resolved(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, ParameterDescription parameterDescription) { super(target, readOnly, typing); this.parameterDescription = parameterDescription; } @Override protected ParameterDescription resolve(MethodDescription instrumentedMethod) { if (!parameterDescription.getDeclaringMethod().equals(instrumentedMethod)) { throw new IllegalStateException(); } else { return parameterDescription; } } public static class Factory<T extends Annotation> implements OffsetMapping.Factory<T> { private final Class<T> annotationType; private final ParameterDescription parameterDescription; public Factory(Class<T> annotationType, ParameterDescription parameterDescription) { this.annotationType = annotationType; this.parameterDescription = parameterDescription; } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { return new Resolved(target.getType(), true, Assigner.Typing.DYNAMIC, parameterDescription); } } } } /** * An offset mapping that provides access to the {@code this} reference of the instrumented method. */ @EqualsAndHashCode class ForThisReference implements OffsetMapping { /** * The offset of the {@code this} reference. */ private static final int THIS_REFERENCE = 0; /** * The type that the advice method expects for the {@code this} reference. */ private final TypeDescription.Generic target; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The typing to apply. */ private final Assigner.Typing typing; /** * {@code true} if the parameter should be bound to {@code null} if the instrumented method is static. */ private final boolean optional; /** * Creates a new offset mapping for a {@code this} reference. * * @param target The type that the advice method expects for the {@code this} reference. * @param annotation The mapped annotation. */ protected ForThisReference(TypeDescription.Generic target, This annotation) { this(target, annotation.readOnly(), annotation.typing(), annotation.optional()); } /** * Creates a new offset mapping for a {@code this} reference. * * @param target The type that the advice method expects for the {@code this} reference. * @param readOnly Determines if the parameter is to be treated as read-only. * @param typing The typing to apply. * @param optional {@code true} if the parameter should be bound to {@code null} if the instrumented method is static. */ protected ForThisReference(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, boolean optional) { this.target = target; this.readOnly = readOnly; this.typing = typing; this.optional = optional; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { if (instrumentedMethod.isStatic() || !context.isInitialized()) { if (optional) { return readOnly ? new Target.ForDefaultValue.ReadOnly(instrumentedType) : new Target.ForDefaultValue.ReadWrite(instrumentedType); } else { throw new IllegalStateException("Cannot map this reference for static method or constructor start: " + instrumentedMethod); } } StackManipulation readAssignment = assigner.assign(instrumentedType.asGenericType(), target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + instrumentedType + " to " + target); } else if (readOnly) { return new Target.ForVariable.ReadOnly(instrumentedType.asGenericType(), THIS_REFERENCE, readAssignment); } else { StackManipulation writeAssignment = assigner.assign(target, instrumentedType.asGenericType(), typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + target + " to " + instrumentedType); } return new Target.ForVariable.ReadWrite(instrumentedType.asGenericType(), THIS_REFERENCE, readAssignment, writeAssignment); } } /** * A factory for creating a {@link ForThisReference} offset mapping. */ protected enum Factory implements OffsetMapping.Factory<This> { INSTANCE; @Override public Class<This> getAnnotationType() { return This.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<This> annotation, boolean delegation) { if (delegation && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot write to this reference for " + target + " in read-only context"); } else { return new ForThisReference(target.getType(), annotation.loadSilent()); } } } } /** * An offset mapping that maps an array containing all arguments of the instrumented method. */ @EqualsAndHashCode class ForAllArguments implements OffsetMapping { /** * The component target type. */ private final TypeDescription.Generic target; /** * {@code true} if the array is read-only. */ private final boolean readOnly; /** * The typing to apply. */ private final Assigner.Typing typing; /** * Creates a new offset mapping for an array containing all arguments. * * @param target The component target type. * @param annotation The mapped annotation. */ protected ForAllArguments(TypeDescription.Generic target, AllArguments annotation) { this(target, annotation.readOnly(), annotation.typing()); } /** * Creates a new offset mapping for an array containing all arguments. * * @param target The component target type. * @param readOnly {@code true} if the array is read-only. * @param typing The typing to apply. */ protected ForAllArguments(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) { this.target = target; this.readOnly = readOnly; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { List<StackManipulation> valueReads = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size()); for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) { StackManipulation readAssignment = assigner.assign(parameterDescription.getType(), target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + target); } valueReads.add(new StackManipulation.Compound(MethodVariableAccess.load(parameterDescription), readAssignment)); } if (readOnly) { return new Target.ForArray.ReadOnly(target, valueReads); } else { List<StackManipulation> valueWrites = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size()); for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) { StackManipulation writeAssignment = assigner.assign(target, parameterDescription.getType(), typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + target + " to " + parameterDescription); } valueWrites.add(new StackManipulation.Compound(writeAssignment, MethodVariableAccess.store(parameterDescription))); } return new Target.ForArray.ReadWrite(target, valueReads, valueWrites); } } /** * A factory for an offset mapping that maps all arguments values of the instrumented method. */ protected enum Factory implements OffsetMapping.Factory<AllArguments> { INSTANCE; @Override public Class<AllArguments> getAnnotationType() { return AllArguments.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<AllArguments> annotation, boolean delegation) { if (!target.getType().represents(Object.class) && !target.getType().isArray()) { throw new IllegalStateException("Cannot use AllArguments annotation on a non-array type"); } else if (delegation && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot define writable field access for " + target); } else { return new ForAllArguments(target.getType().represents(Object.class) ? TypeDescription.Generic.OBJECT // TODO: Test : target.getType().getComponentType(), annotation.loadSilent()); } } } } /** * Maps the declaring type of the instrumented method. */ enum ForInstrumentedType implements OffsetMapping { /** * The singleton instance. */ INSTANCE; @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { return Target.ForStackManipulation.of(instrumentedType); } } /** * Maps a constant representing the instrumented method. */ enum ForInstrumentedMethod implements OffsetMapping { /** * A constant that must be a {@link Method} instance. */ METHOD { @Override protected boolean isRepresentable(MethodDescription instrumentedMethod) { return instrumentedMethod.isMethod(); } }, /** * A constant that must be a {@link Constructor} instance. */ CONSTRUCTOR { @Override protected boolean isRepresentable(MethodDescription instrumentedMethod) { return instrumentedMethod.isConstructor(); } }, /** * A constant that must be a {@code java.lang.reflect.Executable} instance. */ EXECUTABLE { @Override protected boolean isRepresentable(MethodDescription instrumentedMethod) { return true; } }; @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { if (!isRepresentable(instrumentedMethod)) { throw new IllegalStateException("Cannot represent " + instrumentedMethod + " as given method constant"); } return Target.ForStackManipulation.of(instrumentedMethod.asDefined()); } /** * Checks if the supplied method is representable for the assigned offset mapping. * * @param instrumentedMethod The instrumented method to represent. * @return {@code true} if this method is representable. */ protected abstract boolean isRepresentable(MethodDescription instrumentedMethod); } /** * An offset mapping for a field. */ @EqualsAndHashCode abstract class ForField implements OffsetMapping { /** * The {@link FieldValue#value()} method. */ private static final MethodDescription.InDefinedShape VALUE; /** * The {@link FieldValue#declaringType()}} method. */ private static final MethodDescription.InDefinedShape DECLARING_TYPE; /** * The {@link FieldValue#readOnly()}} method. */ private static final MethodDescription.InDefinedShape READ_ONLY; /** * The {@link FieldValue#typing()}} method. */ private static final MethodDescription.InDefinedShape TYPING; /* * Looks up all annotation properties to avoid loading of the declaring field type. */ static { MethodList<MethodDescription.InDefinedShape> methods = new TypeDescription.ForLoadedType(FieldValue.class).getDeclaredMethods(); VALUE = methods.filter(named("value")).getOnly(); DECLARING_TYPE = methods.filter(named("declaringType")).getOnly(); READ_ONLY = methods.filter(named("readOnly")).getOnly(); TYPING = methods.filter(named("typing")).getOnly(); } /** * The expected type that the field can be assigned to. */ protected final TypeDescription.Generic target; /** * {@code true} if this mapping is read-only. */ protected final boolean readOnly; /** * The typing to apply. */ protected final Assigner.Typing typing; /** * Creates an offset mapping for a field. * * @param target The target type. * @param readOnly {@code true} if this mapping is read-only. * @param typing The typing to apply. */ protected ForField(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) { this.target = target; this.readOnly = readOnly; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { FieldDescription fieldDescription = resolve(instrumentedType); if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) { throw new IllegalStateException("Cannot read non-static field " + fieldDescription + " from static method " + instrumentedMethod); } else if (!context.isInitialized() && !fieldDescription.isStatic()) { throw new IllegalStateException("Cannot access non-static field before calling constructor: " + instrumentedMethod); } StackManipulation readAssignment = assigner.assign(fieldDescription.getType(), target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + target); } else if (readOnly) { return new Target.ForField.ReadOnly(fieldDescription, readAssignment); } else { StackManipulation writeAssignment = assigner.assign(target, fieldDescription.getType(), typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + target + " to " + fieldDescription); } return new Target.ForField.ReadWrite(fieldDescription.asDefined(), readAssignment, writeAssignment); } } protected abstract FieldDescription resolve(TypeDescription instrumentedType); @EqualsAndHashCode(callSuper = true) public abstract static class Unresolved extends ForField { /** * The name of the field. */ protected final String name; public Unresolved(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, String name) { super(target, readOnly, typing); this.name = name; } @Override protected FieldDescription resolve(TypeDescription instrumentedType) { FieldLocator.Resolution resolution = fieldLocator(instrumentedType).locate(name); if (!resolution.isResolved()) { throw new IllegalStateException("Cannot locate field named " + name + " for " + instrumentedType); } else { return resolution.getField(); } } /** * Returns a field locator for this instance. * * @param instrumentedType The instrumented type. * @return An appropriate field locator. */ protected abstract FieldLocator fieldLocator(TypeDescription instrumentedType); /** * An offset mapping for a field with an implicit declaring type. */ protected static class WithImplicitType extends Unresolved { /** * Creates an offset mapping for a field with an implicit declaring type. * * @param target The target type. * @param annotation The annotation to represent. */ protected WithImplicitType(TypeDescription.Generic target, AnnotationDescription.Loadable<FieldValue> annotation) { this(target, annotation.getValue(READ_ONLY).resolve(Boolean.class), annotation.getValue(TYPING).loadSilent(Assigner.Typing.class.getClassLoader()).resolve(Assigner.Typing.class), annotation.getValue(VALUE).resolve(String.class)); } /** * Creates an offset mapping for a field with an implicit declaring type. * * @param target The target type. * @param name The name of the field. * @param readOnly {@code true} if the field is read-only. * @param typing The typing to apply. */ protected WithImplicitType(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, String name) { super(target, readOnly, typing, name); } @Override protected FieldLocator fieldLocator(TypeDescription instrumentedType) { return new FieldLocator.ForClassHierarchy(instrumentedType); } } /** * An offset mapping for a field with an explicit declaring type. */ @EqualsAndHashCode(callSuper = true) protected static class WithExplicitType extends Unresolved { /** * The type declaring the field. */ private final TypeDescription declaringType; /** * Creates an offset mapping for a field with an explicit declaring type. * * @param target The target type. * @param annotation The annotation to represent. * @param declaringType The field's declaring type. */ protected WithExplicitType(TypeDescription.Generic target, AnnotationDescription.Loadable<FieldValue> annotation, TypeDescription declaringType) { this(target, annotation.getValue(READ_ONLY).resolve(Boolean.class), annotation.getValue(TYPING).loadSilent(Assigner.Typing.class.getClassLoader()).resolve(Assigner.Typing.class), annotation.getValue(VALUE).resolve(String.class), declaringType); } /** * Creates an offset mapping for a field with an explicit declaring type. * * @param target The target type. * @param name The name of the field. * @param readOnly {@code true} if the field is read-only. * @param typing The typing to apply. * @param declaringType The field's declaring type. */ protected WithExplicitType(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, String name, TypeDescription declaringType) { super(target, readOnly, typing, name); this.declaringType = declaringType; } @Override protected FieldLocator fieldLocator(TypeDescription instrumentedType) { if (!declaringType.represents(TargetType.class) && !instrumentedType.isAssignableTo(declaringType)) { throw new IllegalStateException(declaringType + " is no super type of " + instrumentedType); } return new FieldLocator.ForExactType(TargetType.resolve(declaringType, instrumentedType)); } } /** * A factory for a {@link ForField} offset mapping. */ protected enum Factory implements OffsetMapping.Factory<FieldValue> { INSTANCE; @Override public Class<FieldValue> getAnnotationType() { return FieldValue.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<FieldValue> annotation, boolean delegation) { if (delegation && !annotation.getValue(ForField.READ_ONLY).resolve(Boolean.class)) { throw new IllegalStateException("Cannot write to field for " + target + " in read-only context"); } else { TypeDescription declaringType = annotation.getValue(DECLARING_TYPE).resolve(TypeDescription.class); return declaringType.represents(void.class) ? new WithImplicitType(target.getType(), annotation) : new WithExplicitType(target.getType(), annotation, declaringType); } } } } @EqualsAndHashCode(callSuper = true) public static class Resolved extends ForField { private final FieldDescription fieldDescription; public Resolved(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, FieldDescription fieldDescription) { super(target, readOnly, typing); this.fieldDescription = fieldDescription; } @Override protected FieldDescription resolve(TypeDescription instrumentedType) { if (!fieldDescription.isAccessibleTo(instrumentedType)) { throw new IllegalStateException(); } else if (!fieldDescription.isStatic() && !fieldDescription.getDeclaringType().asErasure().isAssignableFrom(instrumentedType)) { throw new IllegalStateException(); } return fieldDescription; } public static class Factory<T extends Annotation> implements OffsetMapping.Factory<T> { private final Class<T> annotationType; private final FieldDescription fieldDescription; public Factory(Class<T> annotationType, FieldDescription fieldDescription) { this.annotationType = annotationType; this.fieldDescription = fieldDescription; } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { return new Resolved(target.getType(), false, Assigner.Typing.DYNAMIC, fieldDescription); } } } } /** * An offset mapping for the {@link Advice.Origin} annotation. */ @EqualsAndHashCode class ForOrigin implements OffsetMapping { /** * The delimiter character. */ private static final char DELIMITER = ' /** * The escape character. */ private static final char ESCAPE = '\\'; /** * The renderers to apply. */ private final List<Renderer> renderers; /** * Creates a new offset mapping for an origin value. * * @param renderers The renderers to apply. */ protected ForOrigin(List<Renderer> renderers) { this.renderers = renderers; } /** * Parses a pattern of an origin annotation. * * @param pattern The supplied pattern. * @return An appropriate offset mapping. */ protected static OffsetMapping parse(String pattern) { if (pattern.equals(Origin.DEFAULT)) { return new ForOrigin(Collections.<Renderer>singletonList(Renderer.ForStringRepresentation.INSTANCE)); } else { List<Renderer> renderers = new ArrayList<Renderer>(pattern.length()); int from = 0; for (int to = pattern.indexOf(DELIMITER); to != -1; to = pattern.indexOf(DELIMITER, from)) { if (to != 0 && pattern.charAt(to - 1) == ESCAPE && (to == 1 || pattern.charAt(to - 2) != ESCAPE)) { renderers.add(new Renderer.ForConstantValue(pattern.substring(from, Math.max(0, to - 1)) + DELIMITER)); from = to + 1; continue; } else if (pattern.length() == to + 1) { throw new IllegalStateException("Missing sort descriptor for " + pattern + " at index " + to); } renderers.add(new Renderer.ForConstantValue(pattern.substring(from, to).replace("" + ESCAPE + ESCAPE, "" + ESCAPE))); switch (pattern.charAt(to + 1)) { case Renderer.ForMethodName.SYMBOL: renderers.add(Renderer.ForMethodName.INSTANCE); break; case Renderer.ForTypeName.SYMBOL: renderers.add(Renderer.ForTypeName.INSTANCE); break; case Renderer.ForDescriptor.SYMBOL: renderers.add(Renderer.ForDescriptor.INSTANCE); break; case Renderer.ForReturnTypeName.SYMBOL: renderers.add(Renderer.ForReturnTypeName.INSTANCE); break; case Renderer.ForJavaSignature.SYMBOL: renderers.add(Renderer.ForJavaSignature.INSTANCE); break; default: throw new IllegalStateException("Illegal sort descriptor " + pattern.charAt(to + 1) + " for " + pattern); } from = to + 2; } renderers.add(new Renderer.ForConstantValue(pattern.substring(from))); return new ForOrigin(renderers); } } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { StringBuilder stringBuilder = new StringBuilder(); for (Renderer renderer : renderers) { stringBuilder.append(renderer.apply(instrumentedType, instrumentedMethod)); } return Target.ForStackManipulation.of(stringBuilder.toString()); } /** * A renderer for an origin pattern element. */ protected interface Renderer { /** * Returns a string representation for this renderer. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method. * @return The string representation. */ String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod); /** * A renderer for a method's internal name. */ enum ForMethodName implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The method name symbol. */ public static final char SYMBOL = 'm'; @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { return instrumentedMethod.getInternalName(); } } /** * A renderer for a method declaring type's binary name. */ enum ForTypeName implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The type name symbol. */ public static final char SYMBOL = 't'; @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { return instrumentedType.getName(); } } /** * A renderer for a method descriptor. */ enum ForDescriptor implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The descriptor symbol. */ public static final char SYMBOL = 'd'; @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { return instrumentedMethod.getDescriptor(); } } /** * A renderer for a method's Java signature in binary form. */ enum ForJavaSignature implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The signature symbol. */ public static final char SYMBOL = 's'; @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { StringBuilder stringBuilder = new StringBuilder("("); boolean comma = false; for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { if (comma) { stringBuilder.append(','); } else { comma = true; } stringBuilder.append(typeDescription.getName()); } return stringBuilder.append(')').toString(); } } /** * A renderer for a method's return type in binary form. */ enum ForReturnTypeName implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The return type symbol. */ public static final char SYMBOL = 'r'; @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { return instrumentedMethod.getReturnType().asErasure().getName(); } } /** * A renderer for a method's {@link Object#toString()} representation. */ enum ForStringRepresentation implements Renderer { /** * The singleton instance. */ INSTANCE; @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { return instrumentedMethod.toString(); } } /** * A renderer for a constant value. */ @EqualsAndHashCode class ForConstantValue implements Renderer { /** * The constant value. */ private final String value; /** * Creates a new renderer for a constant value. * * @param value The constant value. */ protected ForConstantValue(String value) { this.value = value; } @Override public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) { return value; } } } /** * A factory for a method origin. */ protected enum Factory implements OffsetMapping.Factory<Origin> { /** * The singleton instance. */ INSTANCE; @Override public Class<Origin> getAnnotationType() { return Origin.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Origin> annotation, boolean delegation) { if (target.getType().asErasure().represents(Class.class)) { return OffsetMapping.ForInstrumentedType.INSTANCE; } else if (target.getType().asErasure().represents(Method.class)) { return OffsetMapping.ForInstrumentedMethod.METHOD; } else if (target.getType().asErasure().represents(Constructor.class)) { return OffsetMapping.ForInstrumentedMethod.CONSTRUCTOR; } else if (JavaType.EXECUTABLE.getTypeStub().equals(target.getType().asErasure())) { return OffsetMapping.ForInstrumentedMethod.EXECUTABLE; } else if (target.getType().asErasure().isAssignableFrom(String.class)) { return ForOrigin.parse(annotation.loadSilent().value()); } else { throw new IllegalStateException("Non-supported type " + target.getType() + " for @Origin annotation"); } } } } /** * An offset mapping for a parameter where assignments are fully ignored and that always return the parameter type's default value. */ @EqualsAndHashCode class ForUnusedValue implements OffsetMapping { /** * The unused type. */ private final TypeDefinition target; /** * Creates a new offset mapping for an unused type. * * @param target The unused type. */ protected ForUnusedValue(TypeDefinition target) { this.target = target; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { return new Target.ForDefaultValue.ReadWrite(target); } /** * A factory for an offset mapping for an unused value. */ enum Factory implements OffsetMapping.Factory<Unused> { /** * A factory for representing an unused value. */ INSTANCE; @Override public Class<Unused> getAnnotationType() { return Unused.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Unused> annotation, boolean delegation) { return new ForUnusedValue(target.getType()); } } } /** * An offset mapping for a parameter where assignments are fully ignored and that is assigned a boxed version of the instrumented * method's return valueor {@code null} if the return type is not primitive or {@code void}. */ enum ForStubValue implements OffsetMapping, Factory<StubValue> { /** * The singleton instance. */ INSTANCE; @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { return new Target.ForDefaultValue.ReadOnly(instrumentedMethod.getReturnType(), assigner.assign(instrumentedMethod.getReturnType(), TypeDescription.Generic.OBJECT, Assigner.Typing.DYNAMIC)); } @Override public Class<StubValue> getAnnotationType() { return StubValue.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<StubValue> annotation, boolean delegation) { if (!target.getType().represents(Object.class)) { throw new IllegalStateException("Cannot use StubValue on non-Object parameter type " + target); } else { return this; } } } /** * An offset mapping that provides access to the value that is returned by the enter advice. */ @EqualsAndHashCode class ForEnterValue implements OffsetMapping { /** * The represented target type. */ private final TypeDescription.Generic target; /** * The enter type. */ private final TypeDescription.Generic enterType; /** * {@code true} if the annotated value is read-only. */ private final boolean readOnly; /** * The typing to apply. */ private final Assigner.Typing typing; /** * Creates a new offset mapping for the enter type. * * @param target The represented target type. * @param enterType The enter type. * @param enter The represented annotation. */ protected ForEnterValue(TypeDescription.Generic target, TypeDescription.Generic enterType, Enter enter) { this(target, enterType, enter.readOnly(), enter.typing()); } /** * Creates a new offset mapping for the enter type. * * @param target The represented target type. * @param enterType The enter type. * @param readOnly {@code true} if the annotated value is read-only. * @param typing The typing to apply. */ protected ForEnterValue(TypeDescription.Generic target, TypeDescription.Generic enterType, boolean readOnly, Assigner.Typing typing) { this.target = target; this.enterType = enterType; this.readOnly = readOnly; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { StackManipulation readAssignment = assigner.assign(enterType, target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + enterType + " to " + target); } else if (readOnly) { return new Target.ForVariable.ReadOnly(target, instrumentedMethod.getStackSize(), readAssignment); } else { StackManipulation writeAssignment = assigner.assign(target, enterType, typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + target + " to " + enterType); } return new Target.ForVariable.ReadWrite(target, instrumentedMethod.getStackSize(), readAssignment, writeAssignment); } } /** * A factory for creating a {@link ForEnterValue} offset mapping. */ @EqualsAndHashCode protected static class Factory implements OffsetMapping.Factory<Enter> { /** * The supplied type of the enter method. */ private final TypeDefinition enterType; /** * Creates a new factory for creating a {@link ForEnterValue} offset mapping. * * @param enterType The supplied type of the enter method. */ protected Factory(TypeDefinition enterType) { this.enterType = enterType; } @Override public Class<Enter> getAnnotationType() { return Enter.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Enter> annotation, boolean delegation) { if (delegation && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot use writable " + target + " on read-only parameter"); } else { return new ForEnterValue(target.getType(), enterType.asGenericType(), annotation.loadSilent()); } } } } /** * An offset mapping that provides access to the value that is returned by the instrumented method. */ @EqualsAndHashCode class ForReturnValue implements OffsetMapping { /** * The type that the advice method expects for the return value. */ private final TypeDescription.Generic target; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The typing to apply. */ private final Assigner.Typing typing; /** * Creates a new offset mapping for a return value. * * @param target The type that the advice method expects for the return value. * @param annotation The annotation being bound. */ protected ForReturnValue(TypeDescription.Generic target, Return annotation) { this(target, annotation.readOnly(), annotation.typing()); } /** * Creates a new offset mapping for a return value. * * @param target The type that the advice method expects for the return value. * @param readOnly Determines if the parameter is to be treated as read-only. * @param typing The typing to apply. */ protected ForReturnValue(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) { this.target = target; this.readOnly = readOnly; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { int offset = instrumentedMethod.getStackSize() + context.getPadding(); StackManipulation readAssignment = assigner.assign(instrumentedMethod.getReturnType(), target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + instrumentedMethod.getReturnType() + " to " + target); } else if (readOnly) { return instrumentedMethod.getReturnType().represents(void.class) ? new Target.ForDefaultValue.ReadOnly(target) : new Target.ForVariable.ReadOnly(instrumentedMethod.getReturnType(), offset, readAssignment); } else { StackManipulation writeAssignment = assigner.assign(target, instrumentedMethod.getReturnType(), typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + target + " to " + instrumentedMethod.getReturnType()); } return instrumentedMethod.getReturnType().represents(void.class) ? new Target.ForDefaultValue.ReadWrite(target) : new Target.ForVariable.ReadWrite(instrumentedMethod.getReturnType(), offset, readAssignment, writeAssignment); } } /** * A factory for creating a {@link ForReturnValue} offset mapping. */ protected enum Factory implements OffsetMapping.Factory<Return> { INSTANCE; @Override public Class<Return> getAnnotationType() { return Return.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Return> annotation, boolean delegation) { if (delegation && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot write return value for " + target + " in read-only context"); } else { return new ForReturnValue(target.getType(), annotation.loadSilent()); } } } } /** * An offset mapping for accessing a {@link Throwable} of the instrumented method. */ @EqualsAndHashCode class ForThrowable implements OffsetMapping { /** * The type of parameter that is being accessed. */ private final TypeDescription.Generic target; /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * The typing to apply. */ private final Assigner.Typing typing; /** * Creates a new offset mapping for access of the exception that is thrown by the instrumented method.. * * @param target The type of parameter that is being accessed. * @param annotation The annotation to bind. */ protected ForThrowable(TypeDescription.Generic target, Thrown annotation) { this(target, annotation.readOnly(), annotation.typing()); } /** * Creates a new offset mapping for access of the exception that is thrown by the instrumented method.. * * @param target The type of parameter that is being accessed. * @param readOnly {@code true} if the parameter is read-only. * @param typing The typing to apply. */ protected ForThrowable(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) { this.target = target; this.readOnly = readOnly; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { int offset = instrumentedMethod.getStackSize() + context.getPadding() + instrumentedMethod.getReturnType().getStackSize().getSize(); StackManipulation readAssignment = assigner.assign(TypeDescription.THROWABLE.asGenericType(), target, typing); if (!readAssignment.isValid()) { throw new IllegalStateException("Cannot assign Throwable to " + target); } else if (readOnly) { return new Target.ForVariable.ReadOnly(TypeDescription.THROWABLE, offset, readAssignment); } else { StackManipulation writeAssignment = assigner.assign(target, TypeDescription.THROWABLE.asGenericType(), typing); if (!writeAssignment.isValid()) { throw new IllegalStateException("Cannot assign " + target + " to Throwable"); } return new Target.ForVariable.ReadWrite(TypeDescription.THROWABLE, offset, readAssignment, writeAssignment); } } /** * A factory for accessing an exception that was thrown by the instrumented method. */ protected enum Factory implements OffsetMapping.Factory<Thrown> { INSTANCE; /** * Resolves an appropriate offset mapping factory for the {@link Thrown} parameter annotation. * * @param adviceMethod The exit advice method, annotated with {@link OnMethodExit}. * @return An appropriate offset mapping factory. */ @SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6 protected static OffsetMapping.Factory<?> of(MethodDescription.InDefinedShape adviceMethod) { return adviceMethod.getDeclaredAnnotations() .ofType(OnMethodExit.class) .getValue(ON_THROWABLE) .resolve(TypeDescription.class) .represents(NoExceptionHandler.class) ? new OffsetMapping.Illegal(Thrown.class) : Factory.INSTANCE; } @Override public Class<Thrown> getAnnotationType() { return Thrown.class; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Thrown> annotation, boolean delegation) { if (delegation && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot use writable " + target + " on read-only parameter"); } else { return new ForThrowable(target.getType(), annotation.loadSilent()); } } } } @EqualsAndHashCode class ForStackManipulation implements OffsetMapping { private final StackManipulation stackManipulation; private final TypeDescription.Generic typeDescription; private final TypeDescription.Generic targetType; private final Assigner.Typing typing; public ForStackManipulation(StackManipulation stackManipulation, TypeDescription.Generic typeDescription, TypeDescription.Generic targetType, Assigner.Typing typing) { this.stackManipulation = stackManipulation; this.typeDescription = typeDescription; this.targetType = targetType; this.typing = typing; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { StackManipulation assigment = assigner.assign(typeDescription, targetType, typing); if (!assigment.isValid()) { throw new IllegalStateException(); } return new Target.ForStackManipulation(new StackManipulation.Compound(stackManipulation, assigment)); } @EqualsAndHashCode public static class Factory<T extends Annotation> implements OffsetMapping.Factory<T> { private final Class<T> annotationType; private final StackManipulation stackManipulation; private final TypeDescription.Generic typeDescription; public Factory(Class<T> annotationType, StackManipulation stackManipulation, TypeDescription.Generic typeDescription) { this.annotationType = annotationType; this.stackManipulation = stackManipulation; this.typeDescription = typeDescription; } public static <S extends Annotation> OffsetMapping.Factory<S> of(Class<S> annotationType, Object value) { StackManipulation stackManipulation; TypeDescription typeDescription; if (value == null) { return new OfDefaultValue<S>(annotationType); } else if (value instanceof Boolean) { stackManipulation = IntegerConstant.forValue((Boolean) value); typeDescription = new TypeDescription.ForLoadedType(boolean.class); } else if (value instanceof Byte) { stackManipulation = IntegerConstant.forValue((Byte) value); typeDescription = new TypeDescription.ForLoadedType(byte.class); } else if (value instanceof Short) { stackManipulation = IntegerConstant.forValue((Short) value); typeDescription = new TypeDescription.ForLoadedType(short.class); } else if (value instanceof Character) { stackManipulation = IntegerConstant.forValue((Character) value); typeDescription = new TypeDescription.ForLoadedType(char.class); } else if (value instanceof Integer) { stackManipulation = IntegerConstant.forValue((Integer) value); typeDescription = new TypeDescription.ForLoadedType(int.class); } else if (value instanceof Long) { stackManipulation = LongConstant.forValue((Long) value); typeDescription = new TypeDescription.ForLoadedType(long.class); } else if (value instanceof Float) { stackManipulation = FloatConstant.forValue((Float) value); typeDescription = new TypeDescription.ForLoadedType(float.class); } else if (value instanceof Double) { stackManipulation = DoubleConstant.forValue((Double) value); typeDescription = new TypeDescription.ForLoadedType(double.class); } else if (value instanceof String) { stackManipulation = new TextConstant((String) value); typeDescription = TypeDescription.STRING; } else if (value instanceof Class<?>) { stackManipulation = ClassConstant.of(new TypeDescription.ForLoadedType((Class<?>) value)); typeDescription = TypeDescription.CLASS; } else { throw new IllegalStateException("Not a constant value: " + value); } return new Factory<S>(annotationType, stackManipulation, typeDescription.asGenericType()); } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { return new ForStackManipulation(stackManipulation, typeDescription, target.getType(), Assigner.Typing.STATIC); } } @EqualsAndHashCode public static class OfDefaultValue<T extends Annotation> implements OffsetMapping.Factory<T> { private final Class<T> annotationType; public OfDefaultValue(Class<T> annotationType) { this.annotationType = annotationType; } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { return new ForStackManipulation(DefaultValue.of(target.getType()), target.getType(), target.getType(), Assigner.Typing.STATIC); } } @EqualsAndHashCode public static class OfAnnotationProperty<T extends Annotation> implements OffsetMapping.Factory<T> { private final Class<T> annotationType; private final MethodDescription.InDefinedShape property; public OfAnnotationProperty(Class<T> annotationType, MethodDescription.InDefinedShape property) { this.annotationType = annotationType; this.property = property; } public static <S extends Annotation> OffsetMapping.Factory<S> of(Class<S> annotationType, String property) { try { return new OfAnnotationProperty<S>(annotationType, new MethodDescription.ForLoadedMethod(annotationType.getMethod(property))); } catch (NoSuchMethodException exception) { throw new IllegalStateException(exception); } } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { return Factory.of(annotationType, annotation.getValue(property).resolve()).make(target, annotation, delegation); } } } @EqualsAndHashCode class ForSerializedValue implements OffsetMapping { private final TypeDescription.Generic target; private final TypeDescription typeDescription; private final StackManipulation deserialization; public ForSerializedValue(TypeDescription.Generic target, TypeDescription typeDescription, StackManipulation deserialization) { this.target = target; this.typeDescription = typeDescription; this.deserialization = deserialization; } @Override public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) { StackManipulation assignment = assigner.assign(typeDescription.asGenericType(), target, Assigner.Typing.DYNAMIC); if (!assignment.isValid()) { throw new IllegalStateException("Cannot assign " + typeDescription + " to " + target); } return new Target.ForStackManipulation(new StackManipulation.Compound(deserialization, assignment)); } @EqualsAndHashCode public static class Factory<T extends Annotation> implements OffsetMapping.Factory<T> { private final Class<T> annotationType; private final TypeDescription typeDescription; private final StackManipulation deserialization; protected Factory(Class<T> annotationType, TypeDescription typeDescription, StackManipulation deserialization) { this.annotationType = annotationType; this.typeDescription = typeDescription; this.deserialization = deserialization; } public static <S extends Annotation> OffsetMapping.Factory<S> of(Class<S> annotationType, Serializable target, Class<?> type) { if (!type.isInstance(target)) { throw new IllegalArgumentException(target + " is no instance of " + type); } return new Factory<S>(annotationType, new TypeDescription.ForLoadedType(type), SerializedConstant.of(target)); } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { return new ForSerializedValue(target.getType(), typeDescription, deserialization); } } } @EqualsAndHashCode class Illegal<T extends Annotation> implements Factory<T> { private final Class<T> annotationType; public Illegal(Class<T> annotationType) { this.annotationType = annotationType; } @Override public Class<T> getAnnotationType() { return annotationType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean delegation) { throw new IllegalStateException(); } } } /** * A handler for computing the instrumented method's size. */ protected interface MethodSizeHandler { /** * Indicates that a size is not computed but handled directly by ASM. */ int UNDEFINED_SIZE = Short.MAX_VALUE; /** * Requires a minimum length of the local variable array. * * @param localVariableLength The minimal required length of the local variable array. */ void requireLocalVariableLength(int localVariableLength); /** * A method size handler for the instrumented method. */ interface ForInstrumentedMethod extends MethodSizeHandler { /** * Binds a method size handler for the entry advice. * * @param adviceMethod The method representing the entry advice. * @return A method size handler for the entry advice. */ ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod); /** * Binds the method size handler for the exit advice. * * @param adviceMethod The method representing the exit advice. * @param skipThrowable {@code true} if the exit advice is not invoked on an exception. * @return A method size handler for the exit advice. */ ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable); /** * Computes a compound stack size for the advice and the translated instrumented method. * * @param stackSize The required stack size of the instrumented method before translation. * @return The stack size required by the instrumented method and its advice methods. */ int compoundStackSize(int stackSize); /** * Computes a compound local variable array length for the advice and the translated instrumented method. * * @param localVariableLength The required local variable array length of the instrumented method before translation. * @return The local variable length required by the instrumented method and its advice methods. */ int compoundLocalVariableLength(int localVariableLength); } /** * A method size handler for an advice method. */ interface ForAdvice extends MethodSizeHandler { /** * Records a minimum stack size required by the represented advice method. * * @param stackSize The minimum size required by the represented advice method. */ void requireStackSize(int stackSize); /** * Records the maximum values for stack size and local variable array which are required by the advice method * for its individual execution without translation. * * @param stackSize The minimum required stack size. * @param localVariableLength The minimum required length of the local variable array. */ void recordMaxima(int stackSize, int localVariableLength); /** * Records a minimum padding additionally to the computed stack size that is required for implementing this advice method. * * @param padding The minimum required padding. */ void recordPadding(int padding); } /** * A non-operational method size handler. */ enum NoOp implements ForInstrumentedMethod, ForAdvice { /** * The singleton instance. */ INSTANCE; @Override public ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { return this; } @Override public ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) { return this; } @Override public int compoundStackSize(int stackSize) { return UNDEFINED_SIZE; } @Override public int compoundLocalVariableLength(int localVariableLength) { return UNDEFINED_SIZE; } @Override public void requireLocalVariableLength(int localVariableLength) { /* do nothing */ } @Override public void requireStackSize(int stackSize) { /* do nothing */ } @Override public void recordMaxima(int stackSize, int localVariableLength) { /* do nothing */ } @Override public void recordPadding(int padding) { /* do nothing */ } } /** * A default implementation for a method size handler. */ class Default implements MethodSizeHandler.ForInstrumentedMethod { /** * The instrumented method. */ private final MethodDescription instrumentedMethod; /** * The list of types that the instrumented method requires in addition to the method parameters. */ private final TypeList requiredTypes; /** * A list of types that are yielded by the instrumented method and available to the exit advice. */ private final TypeList yieldedTypes; /** * The maximum stack size required by a visited advice method. */ private int stackSize; /** * The maximum length of the local variable array required by a visited advice method. */ private int localVariableLength; /** * Creates a new default meta data handler that recomputes the space requirements of an instrumented method. * * @param instrumentedMethod The instrumented method. * @param requiredTypes The types this meta data handler expects to be available additionally to the instrumented method's parameters. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. */ protected Default(MethodDescription instrumentedMethod, TypeList requiredTypes, TypeList yieldedTypes) { this.instrumentedMethod = instrumentedMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; } /** * Creates a method size handler applicable for the given instrumented method. * * @param instrumentedMethod The instrumented method. * @param requiredTypes The list of types that the instrumented method requires in addition to the method parameters. * @param yieldedTypes A list of types that are yielded by the instrumented method and available to the exit advice. * @param writerFlags The flags supplied to the ASM class writer. * @return An appropriate method size handler. */ protected static MethodSizeHandler.ForInstrumentedMethod of(MethodDescription instrumentedMethod, List<? extends TypeDescription> requiredTypes, List<? extends TypeDescription> yieldedTypes, int writerFlags) { return (writerFlags & (ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES)) != 0 ? NoOp.INSTANCE : new Default(instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes)); } @Override public MethodSizeHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize()); return new ForAdvice(adviceMethod, new TypeList.Empty(), new TypeList.Explicit(requiredTypes)); } @Override public MethodSizeHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) { stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().maximum(skipThrowable ? StackSize.ZERO : StackSize.SINGLE).getSize()); return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty()); } @Override public int compoundStackSize(int stackSize) { return Math.max(this.stackSize, stackSize); } @Override public int compoundLocalVariableLength(int localVariableLength) { return Math.max(this.localVariableLength, localVariableLength + requiredTypes.getStackSize() + yieldedTypes.getStackSize()); } @Override public void requireLocalVariableLength(int localVariableLength) { this.localVariableLength = Math.max(this.localVariableLength, localVariableLength); } /** * A method size handler for an advice method. */ protected class ForAdvice implements MethodSizeHandler.ForAdvice { /** * The advice method. */ private final MethodDescription.InDefinedShape adviceMethod; /** * A list of types required by this advice method. */ private final TypeList requiredTypes; /** * A list of types yielded by this advice method. */ private final TypeList yieldedTypes; /** * The padding that this advice method requires additionally to its computed size. */ private int padding; /** * Creates a new method size handler for an advice method. * * @param adviceMethod The advice method. * @param requiredTypes A list of types required by this advice method. * @param yieldedTypes A list of types yielded by this advice method. */ protected ForAdvice(MethodDescription.InDefinedShape adviceMethod, TypeList requiredTypes, TypeList yieldedTypes) { this.adviceMethod = adviceMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize()); } @Override public void requireLocalVariableLength(int localVariableLength) { Default.this.requireLocalVariableLength(localVariableLength); } @Override public void requireStackSize(int stackSize) { Default.this.stackSize = Math.max(Default.this.stackSize, stackSize); } @Override public void recordMaxima(int stackSize, int localVariableLength) { Default.this.stackSize = Math.max(Default.this.stackSize, stackSize) + padding; Default.this.localVariableLength = Math.max(Default.this.localVariableLength, localVariableLength - adviceMethod.getStackSize() + instrumentedMethod.getStackSize() + requiredTypes.getStackSize() + yieldedTypes.getStackSize()); } @Override public void recordPadding(int padding) { this.padding = Math.max(this.padding, padding); } } } } /** * A handler for computing and translating stack map frames. */ protected interface StackMapFrameHandler { /** * Translates a frame. * * @param methodVisitor The method visitor to write the frame to. * @param type The frame's type. * @param localVariableLength The local variable length. * @param localVariable An array containing the types of the current local variables. * @param stackSize The size of the operand stack. * @param stack An array containing the types of the current operand stack. */ void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack); /** * Injects a frame indicating the beginning of a return value handler for the currently handled method. * * @param methodVisitor The method visitor onto which to apply the stack map frame. */ void injectReturnFrame(MethodVisitor methodVisitor); /** * Injects a frame indicating the beginning of an exception handler for the currently handled method. * * @param methodVisitor The method visitor onto which to apply the stack map frame. */ void injectExceptionFrame(MethodVisitor methodVisitor); /** * Injects a frame indicating the completion of the currently handled method, i.e. all yielded types were added. * * @param methodVisitor The method visitor onto which to apply the stack map frame. * @param secondary {@code true} if another completion frame for this method was written previously. */ void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary); /** * A stack map frame handler for an instrumented method. */ interface ForInstrumentedMethod extends StackMapFrameHandler { /** * Binds this meta data handler for the entry advice. * * @param adviceMethod The entry advice method. * @return An appropriate meta data handler for the enter method. */ ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod); /** * Binds this meta data handler for the exit advice. * * @param adviceMethod The exit advice method. * @return An appropriate meta data handler for the enter method. */ ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod); /** * Returns a hint to supply to a {@link ClassReader} when parsing an advice method. * * @return The reader hint to supply to an ASM class reader. */ int getReaderHint(); } /** * A stack map frame handler for an advice method. */ interface ForAdvice extends StackMapFrameHandler { /* marker interface */ } /** * A non-operational stack map frame handler. */ enum NoOp implements ForInstrumentedMethod, ForAdvice { /** * The singleton instance. */ INSTANCE; @Override public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { return this; } @Override public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) { return this; } @Override public int getReaderHint() { return ClassReader.SKIP_FRAMES; } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { /* do nothing */ } @Override public void injectReturnFrame(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void injectExceptionFrame(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) { /* do nothing */ } } /** * A default implementation of a stack map frame handler for an instrumented method. */ class Default implements ForInstrumentedMethod { /** * An empty array indicating an empty frame. */ private static final Object[] EMPTY = new Object[0]; /** * The instrumented type. */ private final TypeDescription instrumentedType; /** * The instrumented method. */ protected final MethodDescription instrumentedMethod; /** * A list of intermediate types to be considered as part of the instrumented method's steady signature. */ protected final TypeList requiredTypes; /** * The types that are expected to be added after the instrumented method returns. */ protected final TypeList yieldedTypes; /** * {@code true} if the meta data handler is expected to expand its frames. */ private final boolean expandFrames; /** * The current frame's size divergence from the original local variable array. */ private int currentFrameDivergence; /** * Creates a new default meta data handler. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method. * @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param expandFrames {@code true} if the meta data handler is expected to expand its frames. */ protected Default(TypeDescription instrumentedType, MethodDescription instrumentedMethod, TypeList requiredTypes, TypeList yieldedTypes, boolean expandFrames) { this.instrumentedType = instrumentedType; this.instrumentedMethod = instrumentedMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; this.expandFrames = expandFrames; } /** * Creates an appropriate stack map frame handler for an instrumented method. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method. * @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The flags supplied to the ASM writier. * @param readerFlags The reader flags supplied to the ASM reader. * @return An approrpiate stack map frame handler for an instrumented method. */ protected static ForInstrumentedMethod of(TypeDescription instrumentedType, MethodDescription instrumentedMethod, List<? extends TypeDescription> requiredTypes, List<? extends TypeDescription> yieldedTypes, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { return (writerFlags & ClassWriter.COMPUTE_FRAMES) != 0 || classFileVersion.isLessThan(ClassFileVersion.JAVA_V6) ? NoOp.INSTANCE : new Default(instrumentedType, instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes), (readerFlags & ClassReader.EXPAND_FRAMES) != 0); } /** * Translates a type into a representation of its form inside a stack map frame. * * @param typeDescription The type to translate. * @return A stack entry representation of the supplied type. */ protected static Object toFrame(TypeDescription typeDescription) { if (typeDescription.represents(boolean.class) || typeDescription.represents(byte.class) || typeDescription.represents(short.class) || typeDescription.represents(char.class) || typeDescription.represents(int.class)) { return Opcodes.INTEGER; } else if (typeDescription.represents(long.class)) { return Opcodes.LONG; } else if (typeDescription.represents(float.class)) { return Opcodes.FLOAT; } else if (typeDescription.represents(double.class)) { return Opcodes.DOUBLE; } else { return typeDescription.getInternalName(); } } @Override public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { return new ForAdvice(adviceMethod, new TypeList.Empty(), requiredTypes, TranslationMode.ENTRY); } @Override public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) { return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty(), TranslationMode.EXIT); } @Override public int getReaderHint() { return expandFrames ? ClassReader.EXPAND_FRAMES : AsmVisitorWrapper.NO_FLAGS; } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { translateFrame(methodVisitor, TranslationMode.COPY, instrumentedMethod, requiredTypes, type, localVariableLength, localVariable, stackSize, stack); } /** * Translates a frame. * * @param methodVisitor The method visitor to write the frame to. * @param translationMode The translation mode to apply. * @param methodDescription The method description for which the frame is written. * @param additionalTypes The additional types to consider part of the instrumented method's parameters. * @param type The frame's type. * @param localVariableLength The local variable length. * @param localVariable An array containing the types of the current local variables. * @param stackSize The size of the operand stack. * @param stack An array containing the types of the current operand stack. */ protected void translateFrame(MethodVisitor methodVisitor, TranslationMode translationMode, MethodDescription methodDescription, TypeList additionalTypes, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { switch (type) { case Opcodes.F_SAME: case Opcodes.F_SAME1: break; case Opcodes.F_APPEND: currentFrameDivergence += localVariableLength; break; case Opcodes.F_CHOP: currentFrameDivergence -= localVariableLength; break; case Opcodes.F_FULL: case Opcodes.F_NEW: if (methodDescription.getParameters().size() + (methodDescription.isStatic() ? 0 : 1) > localVariableLength) { throw new IllegalStateException("Inconsistent frame length for " + methodDescription + ": " + localVariableLength); } int offset; if (methodDescription.isStatic()) { offset = 0; } else { if (!translationMode.isPossibleThisFrameValue(instrumentedType, instrumentedMethod, localVariable[0])) { throw new IllegalStateException(methodDescription + " is inconsistent for 'this' reference: " + localVariable[0]); } offset = 1; } for (int index = 0; index < methodDescription.getParameters().size(); index++) { if (!toFrame(methodDescription.getParameters().get(index).getType().asErasure()).equals(localVariable[index + offset])) { throw new IllegalStateException(methodDescription + " is inconsistent at " + index + ": " + localVariable[index + offset]); } } Object[] translated = new Object[localVariableLength - methodDescription.getParameters().size() - (methodDescription.isStatic() ? 0 : 1) + instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1) + additionalTypes.size()]; int index = translationMode.copy(instrumentedType, instrumentedMethod, methodDescription, localVariable, translated); for (TypeDescription typeDescription : additionalTypes) { translated[index++] = toFrame(typeDescription); } System.arraycopy(localVariable, methodDescription.getParameters().size() + (methodDescription.isStatic() ? 0 : 1), translated, index, translated.length - index); localVariableLength = translated.length; localVariable = translated; currentFrameDivergence = translated.length - index; break; default: throw new IllegalArgumentException("Unexpected frame type: " + type); } methodVisitor.visitFrame(type, localVariableLength, localVariable, stackSize, stack); } @Override public void injectReturnFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0 && !instrumentedMethod.isConstructor()) { if (instrumentedMethod.getReturnType().represents(void.class)) { methodVisitor.visitFrame(Opcodes.F_SAME, EMPTY.length, EMPTY, EMPTY.length, EMPTY); } else { methodVisitor.visitFrame(Opcodes.F_SAME1, EMPTY.length, EMPTY, 1, new Object[]{toFrame(instrumentedMethod.getReturnType().asErasure())}); } } else { injectFullFrame(methodVisitor, requiredTypes, instrumentedMethod.getReturnType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(instrumentedMethod.getReturnType().asErasure())); } } @Override public void injectExceptionFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { methodVisitor.visitFrame(Opcodes.F_SAME1, EMPTY.length, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)}); } else { injectFullFrame(methodVisitor, requiredTypes, Collections.singletonList(TypeDescription.THROWABLE)); } } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) { if (!expandFrames && currentFrameDivergence == 0 && (secondary || !instrumentedMethod.isConstructor())) { if (secondary) { methodVisitor.visitFrame(Opcodes.F_SAME, EMPTY.length, EMPTY, EMPTY.length, EMPTY); } else { Object[] local = new Object[yieldedTypes.size()]; int index = 0; for (TypeDescription typeDescription : yieldedTypes) { local[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, EMPTY.length, EMPTY); } } else { injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), Collections.<TypeDescription>emptyList()); } } /** * Injects a full stack map frame. * * @param methodVisitor The method visitor onto which to write the stack map frame. * @param typesInArray The types that were added to the local variable array additionally to the values of the instrumented method. * @param typesOnStack The types currently on the operand stack. */ protected void injectFullFrame(MethodVisitor methodVisitor, List<? extends TypeDescription> typesInArray, List<? extends TypeDescription> typesOnStack) { Object[] localVariable = new Object[instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1) + typesInArray.size()]; int index = 0; if (!instrumentedMethod.isStatic()) { localVariable[index++] = toFrame(instrumentedType); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { localVariable[index++] = toFrame(typeDescription); } for (TypeDescription typeDescription : typesInArray) { localVariable[index++] = toFrame(typeDescription); } index = 0; Object[] stackType = new Object[typesOnStack.size()]; for (TypeDescription typeDescription : typesOnStack) { stackType[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(expandFrames ? Opcodes.F_NEW : Opcodes.F_FULL, localVariable.length, localVariable, stackType.length, stackType); currentFrameDivergence = 0; } /** * A translation mode that determines how the fixed frames of the instrumented method are written. */ protected enum TranslationMode { /** * A translation mode that simply copies the original frames which are available when translating frames of the instrumented method. */ COPY { @Override protected int copy(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodDescription methodDescription, Object[] localVariable, Object[] translated) { int length = instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1); System.arraycopy(localVariable, 0, translated, 0, length); return length; } @Override protected boolean isPossibleThisFrameValue(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Object frame) { if (instrumentedMethod.isConstructor()) { return Opcodes.UNINITIALIZED_THIS.equals(frame); } return toFrame(instrumentedType).equals(frame); } }, /** * A translation mode for the entry advice that considers that the {@code this} reference might not be initialized for a constructor. */ ENTRY { @Override protected int copy(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodDescription methodDescription, Object[] localVariable, Object[] translated) { int index = 0; if (!instrumentedMethod.isStatic()) { translated[index++] = instrumentedMethod.isConstructor() ? Opcodes.UNINITIALIZED_THIS : toFrame(instrumentedType); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { translated[index++] = toFrame(typeDescription); } return index; } @Override protected boolean isPossibleThisFrameValue(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Object frame) { return instrumentedMethod.isConstructor() ? Opcodes.UNINITIALIZED_THIS.equals(frame) : toFrame(instrumentedType).equals(frame); } }, /** * A translation mode for an exit advice where the {@code this} reference is always initialized. */ EXIT { @Override protected int copy(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodDescription methodDescription, Object[] localVariable, Object[] translated) { int index = 0; if (!instrumentedMethod.isStatic()) { translated[index++] = toFrame(instrumentedType); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { translated[index++] = toFrame(typeDescription); } return index; } @Override protected boolean isPossibleThisFrameValue(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Object frame) { return toFrame(instrumentedType).equals(frame); } }; /** * Copies the fixed parameters of the instrumented method onto the operand stack. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method. * @param methodDescription The method for which a frame is created. * @param localVariable The original local variable array. * @param translated The array containing the translated frames. * @return The amount of frames added to the translated frame array. */ protected abstract int copy(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodDescription methodDescription, Object[] localVariable, Object[] translated); protected abstract boolean isPossibleThisFrameValue(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Object frame); } /** * A stack map frame handler for an advice method. */ protected class ForAdvice implements StackMapFrameHandler.ForAdvice { /** * The method description for which frames are translated. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * A list of intermediate types to be considered as part of the instrumented method's steady signature. */ protected final TypeList requiredTypes; /** * The types that this method yields as a result. */ private final TypeList yieldedTypes; /** * The translation mode to apply for this advice method. Should be either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}. */ protected final TranslationMode translationMode; /** * Creates a new meta data handler for an advice method. * * @param adviceMethod The method description for which frames are translated. * @param requiredTypes A list of expected types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that this method yields as a result. * @param translationMode The translation mode to apply for this advice method. Should be * either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}. */ protected ForAdvice(MethodDescription.InDefinedShape adviceMethod, TypeList requiredTypes, TypeList yieldedTypes, TranslationMode translationMode) { this.adviceMethod = adviceMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; this.translationMode = translationMode; } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { Default.this.translateFrame(methodVisitor, translationMode, adviceMethod, requiredTypes, type, localVariableLength, localVariable, stackSize, stack); } @Override public void injectReturnFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { if (yieldedTypes.isEmpty() || adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitFrame(Opcodes.F_SAME, EMPTY.length, EMPTY, EMPTY.length, EMPTY); } else { methodVisitor.visitFrame(Opcodes.F_SAME1, EMPTY.length, EMPTY, 1, new Object[]{toFrame(adviceMethod.getReturnType().asErasure())}); } } else { injectFullFrame(methodVisitor, requiredTypes, yieldedTypes.isEmpty() || adviceMethod.getReturnType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(adviceMethod.getReturnType().asErasure())); } } @Override public void injectExceptionFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { methodVisitor.visitFrame(Opcodes.F_SAME1, EMPTY.length, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)}); } else { injectFullFrame(methodVisitor, requiredTypes, Collections.singletonList(TypeDescription.THROWABLE)); } } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) { if ((!expandFrames && currentFrameDivergence == 0 && yieldedTypes.size() < 4)) { if (secondary || yieldedTypes.isEmpty()) { methodVisitor.visitFrame(Opcodes.F_SAME, EMPTY.length, EMPTY, EMPTY.length, EMPTY); } else { Object[] local = new Object[yieldedTypes.size()]; int index = 0; for (TypeDescription typeDescription : yieldedTypes) { local[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, EMPTY.length, EMPTY); } } else { injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), Collections.<TypeDescription>emptyList()); } } } } } /** * A dispatcher for implementing advice. */ protected interface Dispatcher { /** * Indicates that a method does not represent advice and does not need to be visited. */ MethodVisitor IGNORE_METHOD = null; /** * Expresses that an annotation should not be visited. */ AnnotationVisitor IGNORE_ANNOTATION = null; /** * Returns {@code true} if this dispatcher is alive. * * @return {@code true} if this dispatcher is alive. */ boolean isAlive(); /** * A dispatcher that is not yet resolved. */ interface Unresolved extends Dispatcher { /** * Indicates that this dispatcher requires access to the class file declaring the advice method. * * @return {@code true} if this dispatcher requires access to the advice method's class file. */ boolean isBinary(); /** * Resolves this dispatcher as a dispatcher for entering a method. * * @param userFactories A list of custom factories for binding parameters of an advice method. * @param classReader A class reader to query for a class file which might be {@code null} if this dispatcher is not binary. * @return This dispatcher as a dispatcher for entering a method. */ Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader); /** * Resolves this dispatcher as a dispatcher for exiting a method. * * @param userFactories A list of custom factories for binding parameters of an advice method. * @param classReader A class reader to query for a class file which might be {@code null} if this dispatcher is not binary. * @param dispatcher The dispatcher for entering a method. * @return This dispatcher as a dispatcher for exiting a method. */ Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, Resolved.ForMethodEnter dispatcher); } /** * A suppression handler for optionally suppressing exceptions. */ interface SuppressionHandler { /** * Binds the suppression handler for instrumenting a specific method. * * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @return A bound version of the suppression handler. */ Bound bind(StackManipulation exceptionHandler); /** * A producer for a default return value if this is applicable. */ interface ReturnValueProducer { /** * Instructs this return value producer to assure the production of a default value for the return type of the currently handled method. * * @param methodVisitor The method visitor to write the default value to. */ void onDefaultValue(MethodVisitor methodVisitor); } /** * A bound version of a suppression handler that must not be reused. */ interface Bound { /** * Invoked to prepare the suppression handler, i.e. to write an exception handler entry if appropriate. * * @param methodVisitor The method visitor to apply the preparation to. */ void onPrepare(MethodVisitor methodVisitor); /** * Invoked at the start of a method. * * @param methodVisitor The method visitor of the instrumented method. */ void onStart(MethodVisitor methodVisitor); /** * Invoked at the end of a method. * * @param methodVisitor The method visitor of the instrumented method. * @param implementationContext The implementation context to use. * @param methodSizeHandler The advice method's method size handler. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param returnValueProducer A producer for defining a default return value of the advised method. */ void onEnd(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer); /** * Invoked at the end of a method. Additionally indicates that the handler block should be surrounding by a skipping instruction. This method * is always followed by a stack map frame (if it is required for the class level and class writer setting). * * @param methodVisitor The method visitor of the instrumented method. * @param implementationContext The implementation context to use. * @param methodSizeHandler The advice method's method size handler. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param returnValueProducer A producer for defining a default return value of the advised method. */ void onEndSkipped(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer); } /** * A non-operational suppression handler that does not suppress any method. */ enum NoOp implements SuppressionHandler, Bound { /** * The singleton instance. */ INSTANCE; @Override public Bound bind(StackManipulation exceptionHandler) { return this; } @Override public void onPrepare(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void onStart(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void onEnd(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { /* do nothing */ } @Override public void onEndSkipped(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { /* do nothing */ } } /** * A suppression handler that suppresses a given throwable type. */ @EqualsAndHashCode class Suppressing implements SuppressionHandler { /** * The suppressed throwable type. */ private final TypeDescription suppressedType; /** * Creates a new suppressing suppression handler. * * @param suppressedType The suppressed throwable type. */ protected Suppressing(TypeDescription suppressedType) { this.suppressedType = suppressedType; } /** * Resolves an appropriate suppression handler. * * @param suppressedType The suppressed type or {@link NoExceptionHandler} if no type should be suppressed. * @return An appropriate suppression handler. */ protected static SuppressionHandler of(TypeDescription suppressedType) { return suppressedType.represents(NoExceptionHandler.class) ? NoOp.INSTANCE : new Suppressing(suppressedType); } @Override public SuppressionHandler.Bound bind(StackManipulation exceptionHandler) { return new Bound(suppressedType, exceptionHandler); } /** * An active, bound suppression handler. */ protected static class Bound implements SuppressionHandler.Bound { /** * The suppressed throwable type. */ private final TypeDescription suppressedType; /** * The stack manipulation to apply within a suppression handler. */ private final StackManipulation exceptionHandler; /** * A label indicating the start of the method. */ private final Label startOfMethod; /** * A label indicating the end of the method. */ private final Label endOfMethod; /** * Creates a new active, bound suppression handler. * * @param suppressedType The suppressed throwable type. * @param exceptionHandler The stack manipulation to apply within a suppression handler. */ protected Bound(TypeDescription suppressedType, StackManipulation exceptionHandler) { this.suppressedType = suppressedType; this.exceptionHandler = exceptionHandler; startOfMethod = new Label(); endOfMethod = new Label(); } @Override public void onPrepare(MethodVisitor methodVisitor) { methodVisitor.visitTryCatchBlock(startOfMethod, endOfMethod, endOfMethod, suppressedType.getInternalName()); } @Override public void onStart(MethodVisitor methodVisitor) { methodVisitor.visitLabel(startOfMethod); } @Override public void onEnd(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { methodVisitor.visitLabel(endOfMethod); stackMapFrameHandler.injectExceptionFrame(methodVisitor); methodSizeHandler.requireStackSize(1 + exceptionHandler.apply(methodVisitor, implementationContext).getMaximalSize()); returnValueProducer.onDefaultValue(methodVisitor); } @Override public void onEndSkipped(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { Label endOfHandler = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfHandler); onEnd(methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, returnValueProducer); methodVisitor.visitLabel(endOfHandler); } } } } /** * Represents a resolved dispatcher. */ interface Resolved extends Dispatcher { /** * Binds this dispatcher for resolution to a specific method. * * @param instrumentedType The instrumented type. * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @return A dispatcher that is bound to the instrumented method. */ Bound bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler); /** * Represents a resolved dispatcher for entering a method. */ interface ForMethodEnter extends Resolved { /** * Returns the type that this dispatcher supplies as a result of its advice or a description of {@code void} if * no type is supplied as a result of the enter advice. * * @return The type that this dispatcher supplies as a result of its advice or a description of {@code void}. */ TypeDefinition getEnterType(); /** * Returns {@code true} if the first discovered line number information should be prepended to the advice code. * * @return {@code true} if the first discovered line number information should be prepended to the advice code. */ boolean isPrependLineNumber(); @Override Bound.ForMethodEnter bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler); /** * A skip dispatcher is responsible for skipping the instrumented method depending on the * return value of the enter advice method. */ interface SkipDispatcher { /** * Applies this skip dispatcher. * * @param methodVisitor The method visitor to write to. * @param methodSizeHandler The method size handler of the advice method to use. * @param stackMapFrameHandler The stack map frame handler of the advice method to use. * @param instrumentedMethod The instrumented method. * @param skipHandler The skip handler to use. */ void apply(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, Bound.SkipHandler skipHandler); /** * A disabled skip dispatcher where the instrumented method is always executed. */ enum Disabled implements SkipDispatcher { /** * The singleton instance. */ INSTANCE; @Override public void apply(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, Bound.SkipHandler skipHandler) { /* do nothing */ } } /** * A skip dispatcher where the instrumented method is skipped for any default value of the advice method's return type. * If the return type is {@code boolean}, the relationship is inversed, where the instrumented is skipped for a {@code true} * return value. */ enum ForValue implements SkipDispatcher { /** * A skip dispatcher for a {@code boolean}, {@code byte}, {@code short}, {@code char} or {@code int} value. */ FOR_INTEGER(Opcodes.ILOAD, Opcodes.IFNE, Opcodes.IFEQ) { @Override protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { /* do nothing */ } }, /** * A skip dispatcher for a {@code long} value. */ FOR_LONG(Opcodes.LLOAD, Opcodes.IFNE, Opcodes.IFEQ) { @Override protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { methodVisitor.visitInsn(Opcodes.L2I); } }, /** * A skip dispatcher for a {@code float} value. */ FOR_FLOAT(Opcodes.FLOAD, Opcodes.IFNE, Opcodes.IFEQ) { @Override protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { methodVisitor.visitInsn(Opcodes.FCONST_0); methodVisitor.visitInsn(Opcodes.FCMPL); methodSizeHandler.requireStackSize(2); } }, /** * A skip dispatcher for a {@code double} value. */ FOR_DOUBLE(Opcodes.DLOAD, Opcodes.IFNE, Opcodes.IFEQ) { @Override protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { methodVisitor.visitInsn(Opcodes.DCONST_0); methodVisitor.visitInsn(Opcodes.DCMPL); methodSizeHandler.requireStackSize(4); } }, /** * A skip dispatcher for a reference value. */ FOR_REFERENCE(Opcodes.ALOAD, Opcodes.IFNONNULL, Opcodes.IFNULL) { @Override protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { /* do nothing */ } }; /** * The load opcode for this skip dispatcher. */ private final int load; /** * The jump instruction that triggers skipping upon observing a value's default value. */ private final int defaultJump; /** * The jump instruction that triggers skipping upon observing a value's non-default value. */ private final int nonDefaultJump; /** * Creates a new skip dispatcher. * * @param load The load opcode for this skip dispatcher. * @param defaultJump The jump instruction that triggers skipping upon observing a value's default value. * @param nonDefaultJump The jump instruction that triggers skipping upon observing a value's non-default value. */ ForValue(int load, int defaultJump, int nonDefaultJump) { this.load = load; this.defaultJump = defaultJump; this.nonDefaultJump = nonDefaultJump; } /** * Creates an appropriate skip dispatcher. * * @param typeDefinition The type for which to skip a value. * @param inverted {@code true} if the skip condition should be inverted to trigger upon non-default values. * @return An appropriate skip dispatcher. */ protected static SkipDispatcher of(TypeDefinition typeDefinition, boolean inverted) { ForValue skipDispatcher; if (typeDefinition.represents(long.class)) { skipDispatcher = FOR_LONG; } else if (typeDefinition.represents(float.class)) { skipDispatcher = FOR_FLOAT; } else if (typeDefinition.represents(double.class)) { skipDispatcher = FOR_DOUBLE; } else if (typeDefinition.represents(void.class)) { throw new IllegalStateException("Cannot skip on default value for void return type"); } else if (typeDefinition.isPrimitive()) { // anyOf(byte, short, char, int) skipDispatcher = FOR_INTEGER; } else { skipDispatcher = FOR_REFERENCE; } return inverted ? skipDispatcher.inverted() : skipDispatcher; } @Override public void apply(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, Bound.SkipHandler skipHandler) { doApply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, skipHandler, false); } /** * Applies this skip dispatcher. * * @param methodVisitor The method visitor to write to. * @param methodSizeHandler The method size handler of the advice method to use. * @param stackMapFrameHandler The stack map frame handler of the advice method to use. * @param instrumentedMethod The instrumented method. * @param skipHandler The skip handler to use. * @param inverted {@code true} if the skip condition should be inverted. */ protected void doApply(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, Bound.SkipHandler skipHandler, boolean inverted) { methodVisitor.visitVarInsn(load, instrumentedMethod.getStackSize()); convertValue(methodVisitor, methodSizeHandler); Label noSkip = new Label(); methodVisitor.visitJumpInsn(inverted ? nonDefaultJump : defaultJump, noSkip); skipHandler.apply(methodVisitor); methodVisitor.visitLabel(noSkip); stackMapFrameHandler.injectCompletionFrame(methodVisitor, true); } /** * Converts the return value to an {@code int} value. * * @param methodVisitor The method visitor to use. * @param methodSizeHandler The method size handler of the advice method to use. */ protected abstract void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler); /** * Returns an inverted version of this skip dispatcher. * * @return An inverted version of this skip dispatcher. */ private SkipDispatcher inverted() { return new Inverted(); } /** * An inverted version of a value-based skipped dispatcher that triggers upon observing a non-default value. */ protected class Inverted implements SkipDispatcher { @Override public void apply(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, Bound.SkipHandler skipHandler) { doApply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, skipHandler, true); } /** * Returns the outer instance. * * @return The outer instance. */ private SkipDispatcher getOuter() { return ForValue.this; } @Override // HE: Remove when Lombok support for getOuter is added. public int hashCode() { return ForValue.this.hashCode(); } @Override // HE: Remove when Lombok support for getOuter is added. public boolean equals(Object other) { if (other == this) return true; if (other == null || other.getClass() != getClass()) return false; Inverted inverted = (Inverted) other; return inverted.getOuter().equals(ForValue.this); } } } /** * A skip dispatcher that skips a value if it is of a given instance. */ @EqualsAndHashCode class ForType implements SkipDispatcher { /** * The type for which to skip instances. */ private final TypeDescription typeDescription; /** * Creates a new skip dispatcher for a given type. * * @param typeDescription The type for which to skip instances. */ protected ForType(TypeDescription typeDescription) { this.typeDescription = typeDescription; } /** * Creates a skip dispatcher for an advice method. * * @param adviceMethod The advice method for which to resolve a skip dispatcher. * @return An appropriate skip dispatcher. */ public static SkipDispatcher of(MethodDescription adviceMethod) { return of(adviceMethod.getDeclaredAnnotations() .ofType(OnMethodEnter.class) .getValue(SKIP_ON) .resolve(TypeDescription.class), adviceMethod); } /** * Creates a skip dispatcher for a given annotation type and advice method. * * @param typeDescription The type that was specified as an annotation value. * @param adviceMethod The advice method. * @return An appropriate skip dispatcher. */ protected static SkipDispatcher of(TypeDescription typeDescription, MethodDescription adviceMethod) { if (typeDescription.represents(void.class)) { return Disabled.INSTANCE; } else if (typeDescription.represents(OnDefaultValue.class)) { return ForValue.of(adviceMethod.getReturnType(), false); } else if (typeDescription.represents(OnNonDefaultValue.class)) { return ForValue.of(adviceMethod.getReturnType(), true); } else if (typeDescription.isPrimitive() || adviceMethod.getReturnType().isPrimitive()) { throw new IllegalStateException("Cannot skip method by instance type for primitive return value on " + adviceMethod); } else { return new ForType(typeDescription); } } @Override public void apply(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, Bound.SkipHandler skipHandler) { methodVisitor.visitVarInsn(Opcodes.ALOAD, instrumentedMethod.getStackSize()); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, typeDescription.getInternalName()); Label noSkip = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFEQ, noSkip); skipHandler.apply(methodVisitor); methodVisitor.visitLabel(noSkip); stackMapFrameHandler.injectCompletionFrame(methodVisitor, true); } } } } /** * Represents a resolved dispatcher for exiting a method. */ interface ForMethodExit extends Resolved { /** * Returns the type of throwable for which this exit advice is supposed to be invoked. * * @return The {@link Throwable} type for which to invoke this exit advice or a description of {@link NoExceptionHandler} * if this exit advice does not expect to be invoked upon any throwable. */ TypeDescription getThrowable(); @Override Bound.ForMethodExit bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler); } } /** * A bound resolution of an advice method. */ interface Bound { /** * Prepares the advice method's exception handlers. */ void prepare(); /** * A skip handler is responsible for writing code that skips the invocation of the original code * within the instrumented method. */ interface SkipHandler { /** * Applies this skip handler. * * @param methodVisitor The method visitor to write the code to. */ void apply(MethodVisitor methodVisitor); } /** * A bound dispatcher for a method enter. */ interface ForMethodEnter extends Bound { /** * Applies this dispatcher. * * @param skipHandler The skip handler to use. */ void apply(SkipHandler skipHandler); } /** * A bound dispatcher for a method exit. */ interface ForMethodExit extends Bound { /** * Applies this dispatcher. */ void apply(); } } /** * An implementation for inactive devise that does not write any byte code. */ enum Inactive implements Dispatcher.Unresolved, Resolved.ForMethodEnter, Resolved.ForMethodExit, Bound.ForMethodEnter, Bound.ForMethodExit { /** * The singleton instance. */ INSTANCE; @Override public boolean isAlive() { return false; } @Override public boolean isBinary() { return false; } @Override public TypeDescription getThrowable() { return NoExceptionHandler.DESCRIPTION; } @Override public TypeDefinition getEnterType() { return TypeDescription.VOID; } @Override public boolean isPrependLineNumber() { return false; } @Override public Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader) { return this; } @Override public Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, Resolved.ForMethodEnter dispatcher) { return this; } @Override public void prepare() { /* do nothing */ } @Override public void apply() { /* do nothing */ } @Override public void apply(SkipHandler skipHandler) { /* do nothing */ } @Override public Inactive bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler) { return this; } } /** * A dispatcher for an advice method that is being inlined into the instrumented method. */ @EqualsAndHashCode class Inlining implements Unresolved { /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * Creates a dispatcher for inlined advice method. * * @param adviceMethod The advice method. */ protected Inlining(MethodDescription.InDefinedShape adviceMethod) { this.adviceMethod = adviceMethod; } @Override public boolean isAlive() { return true; } @Override public boolean isBinary() { return true; } @Override public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader) { return new Resolved.ForMethodEnter(adviceMethod, userFactories, classReader); } @Override public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, Dispatcher.Resolved.ForMethodEnter dispatcher) { return Resolved.ForMethodExit.of(adviceMethod, userFactories, classReader, dispatcher.getEnterType()); } /** * A resolved version of a dispatcher. */ protected abstract static class Resolved implements Dispatcher.Resolved { /** * Indicates a read-only mapping for an offset. */ private static final boolean READ_ONLY = true; /** * The represented advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * A class reader to query for the class file of the advice method. */ protected final ClassReader classReader; /** * An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter. */ protected final Map<Integer, OffsetMapping> offsetMappings; /** * The suppression handler to use. */ protected final SuppressionHandler suppressionHandler; /** * Creates a new resolved version of a dispatcher. * * @param adviceMethod The represented advice method. * @param factories A list of factories to resolve for the parameters of the advice method. * @param classReader A class reader to query for the class file of the advice method. * @param throwableType The type to handle by a suppression handler or {@link NoExceptionHandler} to not handle any exceptions. */ protected Resolved(MethodDescription.InDefinedShape adviceMethod, List<OffsetMapping.Factory<?>> factories, ClassReader classReader, TypeDescription throwableType) { this.adviceMethod = adviceMethod; Map<TypeDescription, OffsetMapping.Factory<?>> offsetMappings = new HashMap<TypeDescription, OffsetMapping.Factory<?>>(); for (OffsetMapping.Factory<?> factory : factories) { offsetMappings.put(new TypeDescription.ForLoadedType(factory.getAnnotationType()), factory); } this.offsetMappings = new HashMap<Integer, OffsetMapping>(); for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) { OffsetMapping offsetMapping = null; for (AnnotationDescription annotationDescription : parameterDescription.getDeclaredAnnotations()) { OffsetMapping.Factory<?> factory = offsetMappings.get(annotationDescription.getAnnotationType()); if (factory != null) { @SuppressWarnings("unchecked") OffsetMapping current = factory.make(parameterDescription, (AnnotationDescription.Loadable) annotationDescription.prepare(factory.getAnnotationType()), OffsetMapping.Factory.INLINING); if (offsetMapping == null) { offsetMapping = current; } else { throw new IllegalStateException(parameterDescription + " is bound to both " + current + " and " + offsetMapping); } } } this.offsetMappings.put(parameterDescription.getOffset(), offsetMapping == null ? new OffsetMapping.ForArgument.Unresolved(parameterDescription) : offsetMapping); } this.classReader = classReader; suppressionHandler = SuppressionHandler.Suppressing.of(throwableType); } @Override public boolean isAlive() { return true; } /** * Applies a resolution for a given instrumented method. * * @param methodVisitor A method visitor for writing byte code to the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod A description of the instrumented method. * @param suppressionHandler The bound suppression handler that is used for suppressing exceptions of this advice method. * @return A method visitor for visiting the advice method's byte code. */ protected abstract MethodVisitor apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, SuppressionHandler.Bound suppressionHandler); @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Inlining.Resolved resolved = (Inlining.Resolved) object; return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings) && suppressionHandler.equals(resolved.suppressionHandler); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public int hashCode() { int result = adviceMethod.hashCode(); result = 31 * result + offsetMappings.hashCode(); result = 31 * result + suppressionHandler.hashCode(); return result; } /** * A bound advice method that copies the code by first extracting the exception table and later appending the * code of the method without copying any meta data. */ protected abstract class AdviceMethodInliner extends ClassVisitor implements Bound { /** * A description of the instrumented type. */ protected final TypeDescription instrumentedType; /** * The instrumented method. */ protected final MethodDescription instrumentedMethod; /** * The method visitor for writing the instrumented method. */ protected final MethodVisitor methodVisitor; /** * The implementation context to use. */ protected final Implementation.Context implementationContext; /** * The assigner to use. */ protected final Assigner assigner; /** * A handler for computing the method size requirements. */ protected final MethodSizeHandler.ForInstrumentedMethod methodSizeHandler; /** * A handler for translating and injecting stack map frames. */ protected final StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler; /** * A bound suppression handler that is used for suppressing exceptions of this advice method. */ protected final SuppressionHandler.Bound suppressionHandler; /** * A class reader for parsing the class file containing the represented advice method. */ protected final ClassReader classReader; /** * The labels that were found during parsing the method's exception handler in the order of their discovery. */ protected List<Label> labels; /** * Creates a new advice method inliner. * * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param classReader A class reader for parsing the class file containing the represented advice method. */ protected AdviceMethodInliner(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, ClassReader classReader) { super(Opcodes.ASM5); this.instrumentedType = instrumentedType; this.instrumentedMethod = instrumentedMethod; this.methodVisitor = methodVisitor; this.implementationContext = implementationContext; this.assigner = assigner; this.methodSizeHandler = methodSizeHandler; this.stackMapFrameHandler = stackMapFrameHandler; this.suppressionHandler = suppressionHandler; this.classReader = classReader; labels = new ArrayList<Label>(); } @Override public void prepare() { classReader.accept(new ExceptionTableExtractor(), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); suppressionHandler.onPrepare(methodVisitor); } /** * Inlines the advice method. */ protected void doApply() { classReader.accept(this, ClassReader.SKIP_DEBUG | stackMapFrameHandler.getReaderHint()); } @Override public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) { return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor) ? new ExceptionTableSubstitutor(Inlining.Resolved.this.apply(methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, instrumentedType, instrumentedMethod, suppressionHandler)) : IGNORE_METHOD; } /** * A class visitor that extracts the exception tables of the advice method. */ protected class ExceptionTableExtractor extends ClassVisitor { /** * Creates a new exception table extractor. */ protected ExceptionTableExtractor() { super(Opcodes.ASM5); } @Override public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) { return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor) ? new ExceptionTableCollector(methodVisitor) : IGNORE_METHOD; } } /** * A visitor that only writes try-catch-finally blocks to the supplied method visitor. All labels of these tables are collected * for substitution when revisiting the reminder of the method. */ protected class ExceptionTableCollector extends MethodVisitor { /** * The method visitor for which the try-catch-finally blocks should be written. */ private final MethodVisitor methodVisitor; /** * Creates a new exception table collector. * * @param methodVisitor The method visitor for which the try-catch-finally blocks should be written. */ protected ExceptionTableCollector(MethodVisitor methodVisitor) { super(Opcodes.ASM5); this.methodVisitor = methodVisitor; } @Override public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { methodVisitor.visitTryCatchBlock(start, end, handler, type); labels.addAll(Arrays.asList(start, end, handler)); } @Override public AnnotationVisitor visitTryCatchAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return methodVisitor.visitTryCatchAnnotation(typeReference, typePath, descriptor, visible); } } /** * A label substitutor allows to visit an advice method a second time after the exception handlers were already written. * Doing so, this visitor substitutes all labels that were already created during the first visit to keep the mapping * consistent. It is not required to resolve labels for non-code instructions as meta information is not propagated to * the target method visitor for advice code. */ protected class ExceptionTableSubstitutor extends MethodVisitor { /** * A map containing resolved substitutions. */ private final Map<Label, Label> substitutions; /** * The current index of the visited labels that are used for try-catch-finally blocks. */ private int index; /** * Creates a label substitor. * * @param methodVisitor The method visitor for which to substitute labels. */ protected ExceptionTableSubstitutor(MethodVisitor methodVisitor) { super(Opcodes.ASM5, methodVisitor); substitutions = new IdentityHashMap<Label, Label>(); } @Override public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { substitutions.put(start, labels.get(index++)); substitutions.put(end, labels.get(index++)); Label actualHandler = labels.get(index++); substitutions.put(handler, actualHandler); ((CodeTranslationVisitor) mv).propagateHandler(actualHandler); } @Override public AnnotationVisitor visitTryCatchAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public void visitLabel(Label label) { super.visitLabel(resolve(label)); } @Override public void visitJumpInsn(int opcode, Label label) { super.visitJumpInsn(opcode, resolve(label)); } @Override public void visitTableSwitchInsn(int minimum, int maximum, Label defaultOption, Label... label) { super.visitTableSwitchInsn(minimum, maximum, defaultOption, resolve(label)); } @Override public void visitLookupSwitchInsn(Label defaultOption, int[] keys, Label[] label) { super.visitLookupSwitchInsn(resolve(defaultOption), keys, resolve(label)); } /** * Resolves an array of labels. * * @param label The labels to resolved. * @return An array containing the resolved arrays. */ private Label[] resolve(Label[] label) { Label[] resolved = new Label[label.length]; int index = 0; for (Label aLabel : label) { resolved[index++] = resolve(aLabel); } return resolved; } /** * Resolves a single label if mapped or returns the original label. * * @param label The label to resolve. * @return The resolved label. */ private Label resolve(Label label) { Label substitution = substitutions.get(label); return substitution == null ? label : substitution; } } } /** * A resolved dispatcher for implementing method enter advice. */ protected static class ForMethodEnter extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodEnter { /** * The skip dispatcher to use. */ private final SkipDispatcher skipDispatcher; /** * {@code true} if the first discovered line number information should be prepended to the advice code. */ private final boolean prependLineNumber; /** * Creates a new resolved dispatcher for implementing method enter advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader A class reader to query for the class file of the advice method. */ @SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6 protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader) { super(adviceMethod, CompoundList.of(Arrays.<OffsetMapping.Factory<?>>asList(OffsetMapping.ForArgument.Unresolved.Factory.INSTANCE, OffsetMapping.ForAllArguments.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, OffsetMapping.ForField.Unresolved.Factory.INSTANCE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForUnusedValue.Factory.INSTANCE, OffsetMapping.ForStubValue.INSTANCE, OffsetMapping.ForThrowable.Factory.INSTANCE, new OffsetMapping.Illegal(Thrown.class), new OffsetMapping.Illegal(Enter.class), new OffsetMapping.Illegal(Return.class)), userFactories), classReader, adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER).resolve(TypeDescription.class)); skipDispatcher = SkipDispatcher.ForType.of(adviceMethod); prependLineNumber = adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(PREPEND_LINE_NUMBER).resolve(Boolean.class); } @Override public Bound.ForMethodEnter bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler) { return new AdviceMethodInliner(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, suppressionHandler.bind(exceptionHandler), classReader, skipDispatcher); } @Override public TypeDefinition getEnterType() { return adviceMethod.getReturnType(); } @Override public boolean isPrependLineNumber() { return prependLineNumber; } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, SuppressionHandler.Bound suppressionHandler) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedType, instrumentedMethod, assigner, OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod))); } return new CodeTranslationVisitor.ForMethodEnter(methodVisitor, implementationContext, methodSizeHandler.bindEntry(adviceMethod), stackMapFrameHandler.bindEntry(adviceMethod), instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; Inlining.Resolved.ForMethodEnter that = (Inlining.Resolved.ForMethodEnter) object; return prependLineNumber == that.prependLineNumber && skipDispatcher.equals(that.skipDispatcher); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public int hashCode() { int result = super.hashCode(); result = 31 * result + skipDispatcher.hashCode(); result = 31 * result + (prependLineNumber ? 1 : 0); return result; } /** * An advice method inliner for a method enter. */ protected class AdviceMethodInliner extends Inlining.Resolved.AdviceMethodInliner implements Bound.ForMethodEnter { /** * The skip dispatcher to use. */ private final SkipDispatcher skipDispatcher; /** * Creates a new advice method inliner for a method enter. * * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod A description of the instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param classReader A class reader for parsing the class file containing the represented advice method. * @param skipDispatcher The skip dispatcher to use. */ protected AdviceMethodInliner(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, ClassReader classReader, SkipDispatcher skipDispatcher) { super(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, suppressionHandler, classReader); this.skipDispatcher = skipDispatcher; } @Override public void apply(SkipHandler skipHandler) { doApply(); skipDispatcher.apply(methodVisitor, methodSizeHandler.bindEntry(adviceMethod), stackMapFrameHandler.bindEntry(adviceMethod), instrumentedMethod, skipHandler); } } } /** * A resolved dispatcher for implementing method exit advice. */ protected abstract static class ForMethodExit extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodExit { /** * The additional stack size to consider when accessing the local variable array. */ private final TypeDefinition enterType; /** * Creates a new resolved dispatcher for implementing method exit advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader The class reader for parsing the advice method's class file. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, TypeDefinition enterType) { super(adviceMethod, CompoundList.of(Arrays.asList(OffsetMapping.ForArgument.Unresolved.Factory.INSTANCE, OffsetMapping.ForAllArguments.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, OffsetMapping.ForField.Unresolved.Factory.INSTANCE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForUnusedValue.Factory.INSTANCE, OffsetMapping.ForStubValue.INSTANCE, new OffsetMapping.ForEnterValue.Factory(enterType), OffsetMapping.ForReturnValue.Factory.INSTANCE, OffsetMapping.ForThrowable.Factory.of(adviceMethod) ), userFactories), classReader, adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT).resolve(TypeDescription.class)); this.enterType = enterType; } /** * Resolves exit advice that handles exceptions depending on the specification of the exit advice. * * @param adviceMethod The advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader The class reader for parsing the advice method's class file. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @return An appropriate exit handler. */ protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, TypeDefinition enterType) { TypeDescription throwable = adviceMethod.getDeclaredAnnotations() .ofType(OnMethodExit.class) .getValue(ON_THROWABLE).resolve(TypeDescription.class); return throwable.represents(NoExceptionHandler.class) ? new WithoutExceptionHandler(adviceMethod, userFactories, classReader, enterType) : new WithExceptionHandler(adviceMethod, userFactories, classReader, enterType, throwable); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, SuppressionHandler.Bound suppressionHandler) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedType, instrumentedMethod, assigner, OffsetMapping.Context.ForMethodExit.of(enterType))); } return new CodeTranslationVisitor.ForMethodExit(methodVisitor, implementationContext, methodSizeHandler.bindExit(adviceMethod, getThrowable().represents(NoExceptionHandler.class)), stackMapFrameHandler.bindExit(adviceMethod), instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler, enterType.getStackSize().getSize() + getPadding().getSize()); } @Override public Bound.ForMethodExit bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler) { return new AdviceMethodInliner(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, suppressionHandler.bind(exceptionHandler), classReader); } /** * Returns the additional padding this exit advice implies. * * @return The additional padding this exit advice implies. */ protected abstract StackSize getPadding(); /** * An advice method inliner for a method exit. */ protected class AdviceMethodInliner extends Inlining.Resolved.AdviceMethodInliner implements Bound.ForMethodExit { /** * Creates a new advice method inliner for a method exit. * * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod A description of the instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param classReader A class reader for parsing the class file containing the represented advice method. */ public AdviceMethodInliner(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, ClassReader classReader) { super(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, suppressionHandler, classReader); } @Override public void apply() { doApply(); } } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; Inlining.Resolved.ForMethodExit that = (Inlining.Resolved.ForMethodExit) object; return enterType.equals(that.enterType); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public int hashCode() { int result = super.hashCode(); result = 31 * result + enterType.hashCode(); return result; } /** * Implementation of exit advice that handles exceptions. */ @EqualsAndHashCode(callSuper = true) protected static class WithExceptionHandler extends Inlining.Resolved.ForMethodExit { /** * The type of the handled throwable type for which this advice is invoked. */ private final TypeDescription throwable; /** * Creates a new resolved dispatcher for implementing method exit advice that handles exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader The class reader for parsing the advice method's class file. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @param throwable The type of the handled throwable type for which this advice is invoked. */ protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, TypeDefinition enterType, TypeDescription throwable) { super(adviceMethod, userFactories, classReader, enterType); this.throwable = throwable; } @Override protected StackSize getPadding() { return throwable.getStackSize(); } @Override public TypeDescription getThrowable() { return throwable; } } /** * Implementation of exit advice that ignores exceptions. */ protected static class WithoutExceptionHandler extends Inlining.Resolved.ForMethodExit { /** * Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader A class reader to query for the class file of the advice method. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, TypeDefinition enterType) { super(adviceMethod, userFactories, classReader, enterType); } @Override protected StackSize getPadding() { return StackSize.ZERO; } @Override public TypeDescription getThrowable() { return NoExceptionHandler.DESCRIPTION; } } } } /** * A visitor for translating an advice method's byte code for inlining into the instrumented method. */ protected abstract static class CodeTranslationVisitor extends MethodVisitor implements SuppressionHandler.ReturnValueProducer { /** * The original method visitor to which all instructions are eventually written to. */ protected final MethodVisitor methodVisitor; /** * The implementation context to use. */ protected final Context implementationContext; /** * A handler for computing the method size requirements. */ protected final MethodSizeHandler.ForAdvice methodSizeHandler; /** * A handler for translating and injecting stack map frames. */ protected final StackMapFrameHandler.ForAdvice stackMapFrameHandler; /** * The instrumented method. */ protected final MethodDescription instrumentedMethod; /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * A mapping of offsets to resolved target offsets in the instrumented method. */ private final Map<Integer, OffsetMapping.Target> offsetMappings; /** * A handler for optionally suppressing exceptions. */ private final SuppressionHandler.Bound suppressionHandler; /** * A label indicating the end of the advice byte code. */ protected final Label endOfMethod; /** * Creates a new code translation visitor. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param implementationContext The implementation context to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod The instrumented method. * @param adviceMethod The advice method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param suppressionHandler The suppression handler to use. */ protected CodeTranslationVisitor(MethodVisitor methodVisitor, Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, MethodDescription.InDefinedShape adviceMethod, Map<Integer, OffsetMapping.Target> offsetMappings, SuppressionHandler.Bound suppressionHandler) { super(Opcodes.ASM5, new StackAwareMethodVisitor(methodVisitor, instrumentedMethod)); this.methodVisitor = methodVisitor; this.implementationContext = implementationContext; this.methodSizeHandler = methodSizeHandler; this.stackMapFrameHandler = stackMapFrameHandler; this.instrumentedMethod = instrumentedMethod; this.adviceMethod = adviceMethod; this.offsetMappings = offsetMappings; this.suppressionHandler = suppressionHandler; endOfMethod = new Label(); } /** * Propagates a label for an exception handler that is typically suppressed by the overlaying * {@link Resolved.AdviceMethodInliner.ExceptionTableSubstitutor}. * * @param label The label to register as a target for an exception handler. */ protected void propagateHandler(Label label) { ((StackAwareMethodVisitor) mv).register(label, Collections.singletonList(StackSize.SINGLE)); } @Override public void visitParameter(String name, int modifiers) { /* do nothing */ } @Override public AnnotationVisitor visitAnnotationDefault() { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitTypeAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitParameterAnnotation(int index, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public void visitAttribute(Attribute attribute) { /* do nothing */ } @Override public void visitCode() { suppressionHandler.onStart(methodVisitor); } @Override public void visitFrame(int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { stackMapFrameHandler.translateFrame(methodVisitor, type, localVariableLength, localVariable, stackSize, stack); } @Override public void visitEnd() { suppressionHandler.onEnd(methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, this); methodVisitor.visitLabel(endOfMethod); onMethodReturn(); stackMapFrameHandler.injectCompletionFrame(methodVisitor, false); } @Override public void visitMaxs(int stackSize, int localVariableLength) { methodSizeHandler.recordMaxima(stackSize, localVariableLength); } @Override public void visitVarInsn(int opcode, int offset) { OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { StackManipulation stackManipulation; StackSize expectedGrowth; switch (opcode) { case Opcodes.ILOAD: case Opcodes.FLOAD: case Opcodes.ALOAD: stackManipulation = target.resolveRead(); expectedGrowth = StackSize.SINGLE; break; case Opcodes.DLOAD: case Opcodes.LLOAD: stackManipulation = target.resolveRead(); expectedGrowth = StackSize.DOUBLE; break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: case Opcodes.LSTORE: case Opcodes.DSTORE: stackManipulation = target.resolveWrite(); expectedGrowth = StackSize.ZERO; break; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } methodSizeHandler.recordPadding(stackManipulation.apply(mv, implementationContext).getMaximalSize() - expectedGrowth.getSize()); } else { mv.visitVarInsn(opcode, adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize())); } } @Override public void visitIincInsn(int offset, int value) { OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { methodSizeHandler.recordPadding(target.resolveIncrement(value).apply(mv, implementationContext).getMaximalSize()); } else { mv.visitIincInsn(adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize()), value); } } /** * Adjusts the offset of a variable instruction within the advice method such that no arguments to * the instrumented method are overridden. * * @param offset The original offset. * @return The adjusted offset. */ protected abstract int adjust(int offset); @Override public abstract void visitInsn(int opcode); /** * Invoked after returning from the advice method. */ protected abstract void onMethodReturn(); /** * A code translation visitor that retains the return value of the represented advice method. */ protected static class ForMethodEnter extends CodeTranslationVisitor { /** * {@code true} if the method can return non-exceptionally. */ private boolean doesReturn; /** * Creates a code translation visitor for translating exit advice. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param implementationContext The implementation context to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod The instrumented method. * @param adviceMethod The advice method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param suppressionHandler The suppression handler to use. */ protected ForMethodEnter(MethodVisitor methodVisitor, Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, MethodDescription.InDefinedShape adviceMethod, Map<Integer, OffsetMapping.Target> offsetMappings, SuppressionHandler.Bound suppressionHandler) { super(methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler); doesReturn = false; } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: ((StackAwareMethodVisitor) mv).drainStack(); break; case Opcodes.IRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.ISTORE, Opcodes.ILOAD, StackSize.SINGLE)); break; case Opcodes.ARETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.ASTORE, Opcodes.ALOAD, StackSize.SINGLE)); break; case Opcodes.FRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.FSTORE, Opcodes.FLOAD, StackSize.SINGLE)); break; case Opcodes.LRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.LSTORE, Opcodes.LLOAD, StackSize.DOUBLE)); break; case Opcodes.DRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.DSTORE, Opcodes.DLOAD, StackSize.DOUBLE)); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); doesReturn = true; } @Override protected int adjust(int offset) { return offset; } @Override public void onDefaultValue(MethodVisitor methodVisitor) { if (adviceMethod.getReturnType().represents(boolean.class) || adviceMethod.getReturnType().represents(byte.class) || adviceMethod.getReturnType().represents(short.class) || adviceMethod.getReturnType().represents(char.class) || adviceMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); } else if (adviceMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); } else if (adviceMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); } else if (adviceMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); } else if (!adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); } doesReturn = true; } @Override protected void onMethodReturn() { Type returnType = Type.getType(adviceMethod.getReturnType().asErasure().getDescriptor()); if (doesReturn && !returnType.equals(Type.VOID_TYPE)) { stackMapFrameHandler.injectReturnFrame(methodVisitor); methodVisitor.visitVarInsn(returnType.getOpcode(Opcodes.ISTORE), instrumentedMethod.getStackSize()); } } } /** * A code translation visitor that discards the return value of the represented advice method. */ protected static class ForMethodExit extends CodeTranslationVisitor { /** * The padding after the instrumented method's arguments in the local variable array. */ private final int padding; /** * Creates a code translation visitor for translating exit advice. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param implementationContext The implementation context to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod The instrumented method. * @param adviceMethod The advice method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param suppressionHandler The suppression handler to use. * @param padding The padding after the instrumented method's arguments in the local variable array. */ protected ForMethodExit(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription instrumentedMethod, MethodDescription.InDefinedShape adviceMethod, Map<Integer, OffsetMapping.Target> offsetMappings, SuppressionHandler.Bound suppressionHandler, int padding) { super(methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler); this.padding = padding; } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: break; case Opcodes.IRETURN: case Opcodes.ARETURN: case Opcodes.FRETURN: mv.visitInsn(Opcodes.POP); break; case Opcodes.LRETURN: case Opcodes.DRETURN: mv.visitInsn(Opcodes.POP2); break; default: mv.visitInsn(opcode); return; } ((StackAwareMethodVisitor) mv).drainStack(); mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } @Override protected int adjust(int offset) { return instrumentedMethod.getReturnType().getStackSize().getSize() + padding + offset; } @Override public void onDefaultValue(MethodVisitor methodVisitor) { /* do nothing */ } @Override protected void onMethodReturn() { /* do nothing */ } } } } /** * A dispatcher for an advice method that is being invoked from the instrumented method. */ @EqualsAndHashCode class Delegating implements Unresolved { /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * Creates a new delegating advice dispatcher. * * @param adviceMethod The advice method. */ protected Delegating(MethodDescription.InDefinedShape adviceMethod) { this.adviceMethod = adviceMethod; } @Override public boolean isAlive() { return true; } @Override public boolean isBinary() { return false; } @Override public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader) { return new Resolved.ForMethodEnter(adviceMethod, userFactories); } @Override public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory<?>> userFactories, ClassReader classReader, Dispatcher.Resolved.ForMethodEnter dispatcher) { return Resolved.ForMethodExit.of(adviceMethod, userFactories, dispatcher.getEnterType()); } /** * A resolved version of a dispatcher. * * @param <T> The type of advice dispatcher that is bound. */ protected abstract static class Resolved<T extends Bound> implements Dispatcher.Resolved { /** * Indicates a read-only mapping for an offset. */ private static final boolean READ_ONLY = true; /** * The represented advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter. */ protected final List<OffsetMapping> offsetMappings; /** * The suppression handler to use. */ protected final SuppressionHandler suppressionHandler; /** * Creates a new resolved version of a dispatcher. * * @param adviceMethod The represented advice method. * @param factories A list of factories to resolve for the parameters of the advice method. * @param throwableType The type to handle by a suppression handler or {@link NoExceptionHandler} to not handle any exceptions. */ protected Resolved(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> factories, TypeDescription throwableType) { this.adviceMethod = adviceMethod; Map<TypeDescription, OffsetMapping.Factory<?>> offsetMappings = new HashMap<TypeDescription, OffsetMapping.Factory<?>>(); for (OffsetMapping.Factory<?> factory : factories) { offsetMappings.put(new TypeDescription.ForLoadedType(factory.getAnnotationType()), factory); } this.offsetMappings = new ArrayList<OffsetMapping>(); for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) { OffsetMapping offsetMapping = null; for (AnnotationDescription annotationDescription : parameterDescription.getDeclaredAnnotations()) { OffsetMapping.Factory<?> factory = offsetMappings.get(annotationDescription.getAnnotationType()); if (factory != null) { @SuppressWarnings("unchecked") OffsetMapping current = factory.make(parameterDescription, (AnnotationDescription.Loadable) annotationDescription.prepare(factory.getAnnotationType()), OffsetMapping.Factory.DELEGATION); if (offsetMapping == null) { offsetMapping = current; } else { throw new IllegalStateException(parameterDescription + " is bound to both " + current + " and " + offsetMapping); } } } this.offsetMappings.add(offsetMapping == null ? new OffsetMapping.ForArgument.Unresolved(parameterDescription) : offsetMapping); } suppressionHandler = SuppressionHandler.Suppressing.of(throwableType); } @Override public boolean isAlive() { return true; } @Override public T bind(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler) { if (!adviceMethod.isVisibleTo(instrumentedType)) { throw new IllegalStateException(adviceMethod + " is not visible to " + instrumentedMethod.getDeclaringType()); } return resolve(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, exceptionHandler); } /** * Binds this dispatcher for resolution to a specific method. * * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod The instrumented method that is being bound. * @param methodVisitor The method visitor for writing to the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @return An appropriate bound advice dispatcher. */ protected abstract T resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler); @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Delegating.Resolved<?> resolved = (Delegating.Resolved<?>) object; return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings) && suppressionHandler.equals(resolved.suppressionHandler); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public int hashCode() { int result = adviceMethod.hashCode(); result = 31 * result + offsetMappings.hashCode(); result = 31 * result + suppressionHandler.hashCode(); return result; } /** * A bound advice method that copies the code by first extracting the exception table and later appending the * code of the method without copying any meta data. */ protected abstract static class AdviceMethodWriter implements Bound, SuppressionHandler.ReturnValueProducer { /** * Indicates an empty local variable array which is not required for calling a method. */ private static final int EMPTY = 0; /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * The instrumented method. */ protected final MethodDescription instrumentedMethod; /** * The offset mappings available to this advice. */ private final List<OffsetMapping.Target> offsetMappings; /** * The method visitor for writing the instrumented method. */ protected final MethodVisitor methodVisitor; /** * The implementation context to use. */ protected final Implementation.Context implementationContext; /** * A handler for computing the method size requirements. */ protected final MethodSizeHandler.ForAdvice methodSizeHandler; /** * A handler for translating and injecting stack map frmes. */ protected final StackMapFrameHandler.ForAdvice stackMapFrameHandler; /** * A bound suppression handler that is used for suppressing exceptions of this advice method. */ private final SuppressionHandler.Bound suppressionHandler; /** * Creates a new advice method writer. * * @param adviceMethod The advice method. * @param instrumentedMethod The instrumented method. * @param offsetMappings The offset mappings available to this advice. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. */ protected AdviceMethodWriter(MethodDescription.InDefinedShape adviceMethod, MethodDescription instrumentedMethod, List<OffsetMapping.Target> offsetMappings, MethodVisitor methodVisitor, Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler) { this.adviceMethod = adviceMethod; this.instrumentedMethod = instrumentedMethod; this.offsetMappings = offsetMappings; this.methodVisitor = methodVisitor; this.implementationContext = implementationContext; this.methodSizeHandler = methodSizeHandler; this.stackMapFrameHandler = stackMapFrameHandler; this.suppressionHandler = suppressionHandler; } @Override public void prepare() { suppressionHandler.onPrepare(methodVisitor); } /** * Writes the advice method invocation. */ protected void doApply() { suppressionHandler.onStart(methodVisitor); int index = 0, currentStackSize = 0, maximumStackSize = 0; for (OffsetMapping.Target offsetMapping : offsetMappings) { currentStackSize += adviceMethod.getParameters().get(index++).getType().getStackSize().getSize(); maximumStackSize = Math.max(maximumStackSize, currentStackSize + offsetMapping.resolveRead() .apply(methodVisitor, implementationContext) .getMaximalSize()); } methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, adviceMethod.getDeclaringType().getInternalName(), adviceMethod.getInternalName(), adviceMethod.getDescriptor(), false); onMethodReturn(); suppressionHandler.onEndSkipped(methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, this); stackMapFrameHandler.injectCompletionFrame(methodVisitor, false); methodSizeHandler.recordMaxima(Math.max(maximumStackSize, adviceMethod.getReturnType().getStackSize().getSize()), EMPTY); } /** * Invoked directly after the advice method was called. */ protected abstract void onMethodReturn(); /** * An advice method writer for a method entry. */ protected static class ForMethodEnter extends AdviceMethodWriter implements Bound.ForMethodEnter { /** * The skip dispatcher to use. */ private final Resolved.ForMethodEnter.SkipDispatcher skipDispatcher; /** * Creates a new advice method writer. * * @param adviceMethod The advice method. * @param instrumentedMethod The instrumented method. * @param offsetMappings The offset mappings available to this advice. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param skipDispatcher The skip dispatcher to use. */ protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, MethodDescription instrumentedMethod, List<OffsetMapping.Target> offsetMappings, MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, Resolved.ForMethodEnter.SkipDispatcher skipDispatcher) { super(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, suppressionHandler); this.skipDispatcher = skipDispatcher; } @Override protected void onMethodReturn() { if (adviceMethod.getReturnType().represents(boolean.class) || adviceMethod.getReturnType().represents(byte.class) || adviceMethod.getReturnType().represents(short.class) || adviceMethod.getReturnType().represents(char.class) || adviceMethod.getReturnType().represents(int.class)) { methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(long.class)) { methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(float.class)) { methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(double.class)) { methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); } else if (!adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); } } @Override public void apply(SkipHandler skipHandler) { doApply(); skipDispatcher.apply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, skipHandler); } @Override public void onDefaultValue(MethodVisitor methodVisitor) { if (adviceMethod.getReturnType().represents(boolean.class) || adviceMethod.getReturnType().represents(byte.class) || adviceMethod.getReturnType().represents(short.class) || adviceMethod.getReturnType().represents(char.class) || adviceMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); } else if (!adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); } } } /** * An advice method writer for a method exit. */ protected static class ForMethodExit extends AdviceMethodWriter implements Bound.ForMethodExit { /** * Creates a new advice method writer. * * @param adviceMethod The advice method. * @param instrumentedMethod The instrumented method. * @param offsetMappings The offset mappings available to this advice. * @param methodVisitor The method visitor for writing the instrumented method. * @param implementationContext The implementation context to use. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. */ protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod, MethodDescription instrumentedMethod, List<OffsetMapping.Target> offsetMappings, MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler) { super(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, implementationContext, methodSizeHandler, stackMapFrameHandler, suppressionHandler); } @Override public void apply() { doApply(); } @Override protected void onMethodReturn() { switch (adviceMethod.getReturnType().getStackSize()) { case ZERO: return; case SINGLE: methodVisitor.visitInsn(Opcodes.POP); return; case DOUBLE: methodVisitor.visitInsn(Opcodes.POP2); return; default: throw new IllegalStateException("Unexpected size: " + adviceMethod.getReturnType().getStackSize()); } } @Override public void onDefaultValue(MethodVisitor methodVisitor) { /* do nothing */ } } } /** * A resolved dispatcher for implementing method enter advice. */ protected static class ForMethodEnter extends Delegating.Resolved<Bound.ForMethodEnter> implements Dispatcher.Resolved.ForMethodEnter { /** * The skip dispatcher to use. */ private final SkipDispatcher skipDispatcher; /** * {@code true} if the first discovered line number information should be prepended to the advice code. */ private final boolean prependLineNumber; /** * Creates a new resolved dispatcher for implementing method enter advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. */ @SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6 protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories) { super(adviceMethod, CompoundList.of(Arrays.<OffsetMapping.Factory<?>>asList(OffsetMapping.ForArgument.Unresolved.Factory.INSTANCE, OffsetMapping.ForAllArguments.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, OffsetMapping.ForField.Unresolved.Factory.INSTANCE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForUnusedValue.Factory.INSTANCE, OffsetMapping.ForStubValue.INSTANCE, new OffsetMapping.Illegal(Thrown.class), new OffsetMapping.Illegal(Enter.class), new OffsetMapping.Illegal(Return.class)), userFactories), adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER).resolve(TypeDescription.class)); skipDispatcher = SkipDispatcher.ForType.of(adviceMethod); prependLineNumber = adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(PREPEND_LINE_NUMBER).resolve(Boolean.class); } @Override public TypeDefinition getEnterType() { return adviceMethod.getReturnType(); } @Override public boolean isPrependLineNumber() { return prependLineNumber; } @Override protected Bound.ForMethodEnter resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler) { List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size()); for (OffsetMapping offsetMapping : this.offsetMappings) { offsetMappings.add(offsetMapping.resolve(instrumentedType, instrumentedMethod, assigner, OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod))); } return new AdviceMethodWriter.ForMethodEnter(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, implementationContext, methodSizeHandler.bindEntry(adviceMethod), stackMapFrameHandler.bindEntry(adviceMethod), suppressionHandler.bind(exceptionHandler), skipDispatcher); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; Delegating.Resolved.ForMethodEnter that = (Delegating.Resolved.ForMethodEnter) object; return prependLineNumber == that.prependLineNumber && skipDispatcher.equals(that.skipDispatcher); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public int hashCode() { int result = super.hashCode(); result = 31 * result + skipDispatcher.hashCode(); result = 31 * result + (prependLineNumber ? 1 : 0); return result; } } /** * A resolved dispatcher for implementing method exit advice. */ protected abstract static class ForMethodExit extends Delegating.Resolved<Bound.ForMethodExit> implements Dispatcher.Resolved.ForMethodExit { /** * The additional stack size to consider when accessing the local variable array. */ private final TypeDefinition enterType; /** * Creates a new resolved dispatcher for implementing method exit advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, TypeDefinition enterType) { super(adviceMethod, CompoundList.of(Arrays.asList(OffsetMapping.ForArgument.Unresolved.Factory.INSTANCE, OffsetMapping.ForAllArguments.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, OffsetMapping.ForField.Unresolved.Factory.INSTANCE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForUnusedValue.Factory.INSTANCE, OffsetMapping.ForStubValue.INSTANCE, new OffsetMapping.ForEnterValue.Factory(enterType), OffsetMapping.ForReturnValue.Factory.INSTANCE, OffsetMapping.ForThrowable.Factory.of(adviceMethod) ), userFactories), adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT).resolve(TypeDescription.class)); this.enterType = enterType; } /** * Resolves exit advice that handles exceptions depending on the specification of the exit advice. * * @param adviceMethod The advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @return An appropriate exit handler. */ protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, TypeDefinition enterType) { TypeDescription throwable = adviceMethod.getDeclaredAnnotations() .ofType(OnMethodExit.class) .getValue(ON_THROWABLE).resolve(TypeDescription.class); return throwable.represents(NoExceptionHandler.class) ? new WithoutExceptionHandler(adviceMethod, userFactories, enterType) : new WithExceptionHandler(adviceMethod, userFactories, enterType, throwable); } @Override protected Bound.ForMethodExit resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, MethodSizeHandler.ForInstrumentedMethod methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, StackManipulation exceptionHandler) { List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size()); for (OffsetMapping offsetMapping : this.offsetMappings) { offsetMappings.add(offsetMapping.resolve(instrumentedType, instrumentedMethod, assigner, OffsetMapping.Context.ForMethodExit.of(enterType))); } return new AdviceMethodWriter.ForMethodExit(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, implementationContext, methodSizeHandler.bindExit(adviceMethod, getThrowable().represents(NoExceptionHandler.class)), stackMapFrameHandler.bindExit(adviceMethod), suppressionHandler.bind(exceptionHandler)); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; Delegating.Resolved.ForMethodExit that = (Delegating.Resolved.ForMethodExit) object; return enterType.equals(that.enterType); } @Override // HE: Remove after Lombok resolves ambiguous type names correctly. public int hashCode() { int result = super.hashCode(); result = 31 * result + enterType.hashCode(); return result; } /** * Implementation of exit advice that handles exceptions. */ @EqualsAndHashCode(callSuper = true) protected static class WithExceptionHandler extends Delegating.Resolved.ForMethodExit { /** * The type of the handled throwable type for which this advice is invoked. */ private final TypeDescription throwable; /** * Creates a new resolved dispatcher for implementing method exit advice that handles exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @param throwable The type of the handled throwable type for which this advice is invoked. */ protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, TypeDefinition enterType, TypeDescription throwable) { super(adviceMethod, userFactories, enterType); this.throwable = throwable; } @Override public TypeDescription getThrowable() { return throwable; } } /** * Implementation of exit advice that ignores exceptions. */ protected static class WithoutExceptionHandler extends Delegating.Resolved.ForMethodExit { /** * Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory<?>> userFactories, TypeDefinition enterType) { super(adviceMethod, userFactories, enterType); } @Override public TypeDescription getThrowable() { return NoExceptionHandler.DESCRIPTION; } } } } } } /** * A method visitor that weaves the advice methods' byte codes. */ protected abstract static class AdviceVisitor extends ExceptionTableSensitiveMethodVisitor implements Dispatcher.Bound.SkipHandler { /** * Indicates a zero offset. */ private static final int NO_OFFSET = 0; /** * The actual method visitor that is underlying this method visitor to which all instructions are written. */ protected final MethodVisitor methodVisitor; /** * A description of the instrumented method. */ protected final MethodDescription instrumentedMethod; /** * The required padding before using local variables after the instrumented method's arguments. */ private final int padding; /** * The dispatcher to be used for method entry. */ private final Dispatcher.Bound.ForMethodEnter methodEnter; /** * The dispatcher to be used for method exit. */ protected final Dispatcher.Bound.ForMethodExit methodExit; /** * A handler for computing the method size requirements. */ protected final MethodSizeHandler.ForInstrumentedMethod methodSizeHandler; /** * A handler for translating and injecting stack map frames. */ protected final StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler; /** * Creates a new advice visitor. * * @param methodVisitor The actual method visitor that is underlying this method visitor to which all instructions are written. * @param delegate A delegate to which all instructions of the original method are written to. Must delegate to {@code methodVisitor}. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod The instrumented method. * @param methodEnter The method enter advice. * @param methodExit The method exit advice. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected AdviceVisitor(MethodVisitor methodVisitor, MethodVisitor delegate, Context implementationContext, Assigner assigner, StackManipulation exceptionHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, List<? extends TypeDescription> yieldedTypes, int writerFlags, int readerFlags) { super(Opcodes.ASM5, delegate); this.methodVisitor = methodVisitor; this.instrumentedMethod = instrumentedMethod; padding = methodEnter.getEnterType().getStackSize().getSize(); List<TypeDescription> requiredTypes = methodEnter.getEnterType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(methodEnter.getEnterType().asErasure()); methodSizeHandler = MethodSizeHandler.Default.of(instrumentedMethod, requiredTypes, yieldedTypes, writerFlags); stackMapFrameHandler = StackMapFrameHandler.Default.of(instrumentedType, instrumentedMethod, requiredTypes, yieldedTypes, implementationContext.getClassFileVersion(), writerFlags, readerFlags); this.methodEnter = methodEnter.bind(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, exceptionHandler); this.methodExit = methodExit.bind(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler, exceptionHandler); } @Override protected void onAfterExceptionTable() { methodEnter.prepare(); onUserPrepare(); methodExit.prepare(); methodEnter.apply(this); onUserStart(); } /** * Invoked when the user method's exception handler (if any) is supposed to be prepared. */ protected abstract void onUserPrepare(); /** * Writes the advice for entering the instrumented method. */ protected abstract void onUserStart(); @Override protected void onVisitVarInsn(int opcode, int offset) { mv.visitVarInsn(opcode, resolve(offset)); } @Override protected void onVisitIincInsn(int offset, int increment) { mv.visitIincInsn(resolve(offset), increment); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. */ protected void variable(int opcode) { variable(opcode, NO_OFFSET); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. * @param offset The additional offset of the variable. */ protected void variable(int opcode, int offset) { methodVisitor.visitVarInsn(opcode, instrumentedMethod.getStackSize() + padding + offset); } @Override public void visitFrame(int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { stackMapFrameHandler.translateFrame(methodVisitor, type, localVariableLength, localVariable, stackSize, stack); } @Override public void visitMaxs(int stackSize, int localVariableLength) { onUserEnd(); methodVisitor.visitMaxs(methodSizeHandler.compoundStackSize(stackSize), methodSizeHandler.compoundLocalVariableLength(localVariableLength)); } @Override public void visitLocalVariable(String name, String descriptor, String signature, Label start, Label end, int index) { mv.visitLocalVariable(name, descriptor, signature, start, end, resolve(index)); } @Override public AnnotationVisitor visitLocalVariableAnnotation(int typeReference, TypePath typePath, Label[] start, Label[] end, int[] index, String descriptor, boolean visible) { return mv.visitLocalVariableAnnotation(typeReference, typePath, start, end, resolve(index), descriptor, visible); } /** * Resolves the index of a local variable in the context of the instrumentation. * * @param index The indices to adjust. * @return An array with adjusted indices. */ private int[] resolve(int[] index) { int[] resolved = new int[index.length]; for (int anIndex = 0; anIndex < index.length; anIndex++) { resolved[anIndex] = resolve(index[anIndex]); } return resolved; } /** * Resolves the index of a local variable in the context of the instrumentation. * * @param index The index to adjust. * @return The adjusted index. */ private int resolve(int index) { return index < instrumentedMethod.getStackSize() ? index : padding + index; } /** * Writes the advice for completing the instrumented method. */ protected abstract void onUserEnd(); /** * An advice visitor that does not apply exit advice. */ protected static class WithoutExitAdvice extends AdviceVisitor { /** * Creates an advice visitor that does not apply exit advice. * * @param methodVisitor The method visitor for the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected WithoutExitAdvice(MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, StackManipulation exceptionHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, int writerFlags, int readerFlags) { super(methodVisitor, methodVisitor, implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, Dispatcher.Inactive.INSTANCE, Collections.<TypeDescription>emptyList(), writerFlags, readerFlags); } @Override protected void onUserPrepare() { /* do nothing */ } @Override protected void onUserStart() { /* do nothing */ } @Override protected void onUserEnd() { /* do nothing */ } @Override public void apply(MethodVisitor methodVisitor) { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.IRETURN); } else if (instrumentedMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); methodVisitor.visitInsn(Opcodes.LRETURN); } else if (instrumentedMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); methodVisitor.visitInsn(Opcodes.FRETURN); } else if (instrumentedMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); methodVisitor.visitInsn(Opcodes.DRETURN); } else if (instrumentedMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.RETURN); } else { methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitInsn(Opcodes.ARETURN); } } } /** * An advice visitor that applies exit advice. */ protected abstract static class WithExitAdvice extends AdviceVisitor { /** * Indicates the handler for the value returned by the advice method. */ protected final Label returnHandler; /** * {@code true} if the advice method ever returns non-exceptionally. */ protected boolean doesReturn; /** * Creates an advice visitor that applies exit advice. * * @param methodVisitor The method visitor for the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected WithExitAdvice(MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, StackManipulation exceptionHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, List<? extends TypeDescription> yieldedTypes, int writerFlags, int readerFlags) { super(methodVisitor, new StackAwareMethodVisitor(methodVisitor, instrumentedMethod), implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, methodExit, yieldedTypes, writerFlags, readerFlags); returnHandler = new Label(); doesReturn = false; } @Override public void apply(MethodVisitor methodVisitor) { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); } else if (instrumentedMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); } else if (instrumentedMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); } else if (instrumentedMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); } else if (!instrumentedMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); } methodVisitor.visitJumpInsn(Opcodes.GOTO, returnHandler); doesReturn = true; } @Override protected void onVisitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: ((StackAwareMethodVisitor) mv).drainStack(); break; case Opcodes.IRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.ISTORE, Opcodes.ILOAD, StackSize.SINGLE)); break; case Opcodes.FRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.FSTORE, Opcodes.FLOAD, StackSize.SINGLE)); break; case Opcodes.DRETURN: methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.DSTORE, Opcodes.DLOAD, StackSize.DOUBLE)); break; case Opcodes.LRETURN: methodSizeHandler.requireLocalVariableLength((((StackAwareMethodVisitor) mv).drainStack(Opcodes.LSTORE, Opcodes.LLOAD, StackSize.DOUBLE))); break; case Opcodes.ARETURN: methodSizeHandler.requireLocalVariableLength((((StackAwareMethodVisitor) mv).drainStack(Opcodes.ASTORE, Opcodes.ALOAD, StackSize.SINGLE))); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, returnHandler); doesReturn = true; } @Override protected void onUserEnd() { Type returnType = Type.getType(instrumentedMethod.getReturnType().asErasure().getDescriptor()); methodVisitor.visitLabel(returnHandler); if (doesReturn) { stackMapFrameHandler.injectReturnFrame(methodVisitor); if (!returnType.equals(Type.VOID_TYPE)) { variable(returnType.getOpcode(Opcodes.ISTORE)); } } onUserReturn(); methodExit.apply(); onExitAdviceReturn(); if (returnType.equals(Type.VOID_TYPE)) { methodVisitor.visitInsn(Opcodes.RETURN); } else { variable(returnType.getOpcode(Opcodes.ILOAD)); methodVisitor.visitInsn(returnType.getOpcode(Opcodes.IRETURN)); } } /** * Invoked after the user method has returned. */ protected abstract void onUserReturn(); /** * Invoked after the exit advice method has returned. */ protected abstract void onExitAdviceReturn(); /** * An advice visitor that does not capture exceptions. */ protected static class WithoutExceptionHandling extends WithExitAdvice { /** * Creates a new advice visitor that does not capture exceptions. * * @param methodVisitor The method visitor for the instrumented method. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @param instrumentedType A description of the instrumented type. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected WithoutExceptionHandling(MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, StackManipulation exceptionHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, int writerFlags, int readerFlags) { super(methodVisitor, implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, methodExit, instrumentedMethod.getReturnType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(instrumentedMethod.getReturnType().asErasure()), writerFlags, readerFlags); } @Override protected void onUserPrepare() { /* empty */ } @Override protected void onUserStart() { /* empty */ } @Override protected void onUserReturn() { if (!doesReturn || !instrumentedMethod.getReturnType().represents(void.class)) { stackMapFrameHandler.injectCompletionFrame(methodVisitor, false); } } @Override protected void onExitAdviceReturn() { /* empty */ } } /** * An advice visitor that captures exceptions by weaving try-catch blocks around user code. */ protected static class WithExceptionHandling extends WithExitAdvice { /** * The type of the handled throwable type for which this advice is invoked. */ private final TypeDescription throwable; /** * Indicates the start of the user method. */ private final Label userStart; /** * Indicates the exception handler. */ private final Label exceptionHandler; /** * Creates a new advice visitor that captures exception by weaving try-catch blocks around user code. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedType A description of the instrumented type. * @param implementationContext The implementation context to use. * @param assigner The assigner to use. * @param exceptionHandler The stack manipulation to apply within a suppression handler. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. * @param throwable The type of the handled throwable type for which this advice is invoked. */ protected WithExceptionHandling(MethodVisitor methodVisitor, Implementation.Context implementationContext, Assigner assigner, StackManipulation exceptionHandler, TypeDescription instrumentedType, MethodDescription instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, int writerFlags, int readerFlags, TypeDescription throwable) { super(methodVisitor, implementationContext, assigner, exceptionHandler, instrumentedType, instrumentedMethod, methodEnter, methodExit, instrumentedMethod.getReturnType().represents(void.class) ? Collections.singletonList(TypeDescription.THROWABLE) : Arrays.asList(instrumentedMethod.getReturnType().asErasure(), TypeDescription.THROWABLE), writerFlags, readerFlags); this.throwable = throwable; userStart = new Label(); this.exceptionHandler = new Label(); } @Override protected void onUserPrepare() { methodVisitor.visitTryCatchBlock(userStart, returnHandler, exceptionHandler, throwable.getInternalName()); } @Override protected void onUserStart() { methodVisitor.visitLabel(userStart); } @Override protected void onUserReturn() { Label endOfHandler = new Label(); if (doesReturn) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfHandler); } methodVisitor.visitLabel(exceptionHandler); stackMapFrameHandler.injectExceptionFrame(methodVisitor); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); storeDefaultReturn(); if (doesReturn) { methodVisitor.visitLabel(endOfHandler); } stackMapFrameHandler.injectCompletionFrame(methodVisitor, false); } @Override protected void onExitAdviceReturn() { variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); Label endOfHandler = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNULL, endOfHandler); variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(endOfHandler); stackMapFrameHandler.injectCompletionFrame(methodVisitor, true); } /** * Stores a default return value in the designated slot of the local variable array. */ private void storeDefaultReturn() { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); variable(Opcodes.ISTORE); } else if (instrumentedMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); variable(Opcodes.LSTORE); } else if (instrumentedMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); variable(Opcodes.FSTORE); } else if (instrumentedMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); variable(Opcodes.DSTORE); } else if (!instrumentedMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE); } } } } } /** * A byte code appender for implementing {@link Advice}. */ @EqualsAndHashCode protected static class Appender implements ByteCodeAppender { /** * The advice to implement. */ private final Advice advice; /** * The current implementation target. */ private final Implementation.Target implementationTarget; /** * The delegate byte code appender. */ private final ByteCodeAppender delegate; /** * Creates a new appender for an advice component. * * @param advice The advice to implement. * @param implementationTarget The current implementation target. * @param delegate The delegate byte code appender. */ protected Appender(Advice advice, Target implementationTarget, ByteCodeAppender delegate) { this.advice = advice; this.implementationTarget = implementationTarget; this.delegate = delegate; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { EmulatingMethodVisitor emulatingMethodVisitor = new EmulatingMethodVisitor(methodVisitor, delegate); methodVisitor = advice.doWrap(implementationTarget.getInstrumentedType(), instrumentedMethod, emulatingMethodVisitor, implementationContext, AsmVisitorWrapper.NO_FLAGS, AsmVisitorWrapper.NO_FLAGS); return emulatingMethodVisitor.resolve(methodVisitor, implementationContext, instrumentedMethod); } /** * A method visitor that allows for the emulation of a full method visitor invocation circle without delegating initial * and ending visitations to the underlying visitor. */ protected static class EmulatingMethodVisitor extends MethodVisitor { /** * The delegate byte code appender. */ private final ByteCodeAppender delegate; /** * The currently recorded minimal required stack size. */ private int stackSize; /** * The currently recorded minimal required local variable array length. */ private int localVariableLength; /** * Creates a new emulating method visitor. * * @param methodVisitor The underlying method visitor. * @param delegate The delegate byte code appender. */ protected EmulatingMethodVisitor(MethodVisitor methodVisitor, ByteCodeAppender delegate) { super(Opcodes.ASM5, methodVisitor); this.delegate = delegate; } /** * Resolves this this advice emulating method visitor for its delegate. * * @param methodVisitor The method visitor to apply. * @param implementationContext The implementation context to apply. * @param instrumentedMethod The instrumented method. * @return The resulting size of the implemented method. */ protected ByteCodeAppender.Size resolve(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) { methodVisitor.visitCode(); Size size = delegate.apply(methodVisitor, implementationContext, instrumentedMethod); methodVisitor.visitMaxs(size.getOperandStackSize(), size.getLocalVariableSize()); methodVisitor.visitEnd(); return new ByteCodeAppender.Size(stackSize, localVariableLength); } @Override public void visitCode() { /* do nothing */ } @Override public void visitMaxs(int stackSize, int localVariableLength) { this.stackSize = stackSize; this.localVariableLength = localVariableLength; } @Override public void visitEnd() { /* do nothing */ } } } /** * <p> * Indicates that this method should be inlined before the matched method is invoked. Any class must declare * at most one method with this annotation. The annotated method must be static. When instrumenting constructors, * the {@code this} values can only be accessed for writing fields but not for reading fields or invoking methods. * </p> * <p> * The annotated method can return a value that is made accessible to another method annotated by {@link OnMethodExit}. * </p> * * @see Advice * @see Argument * @see This */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.METHOD) public @interface OnMethodEnter { Class<?> skipOn() default void.class; /** * If set to {@code true}, the instrumented method's line number information is adjusted such that stack traces generated within * this advice method appear as if they were generated within the first line of the instrumented method. If set to {@code false}, * no line number information is made available for such stack traces. * * @return {@code true} if this advice code should appear as if it was added within the first line of the instrumented method. */ boolean prependLineNumber() default true; /** * Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method * is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code * with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods. * When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to * set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into * the instrumented method. * * @return {@code true} if the annotated method should be inlined into the instrumented method. */ boolean inline() default true; /** * Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution. By default, * any such exception is silently suppressed. Custom behavior can be configured by using {@link Advice#withExceptionHandler(StackManipulation)}. * * @return The type of {@link Throwable} to suppress. * @see Advice#withExceptionPrinting() */ Class<? extends Throwable> suppress() default NoExceptionHandler.class; } /** * <p> * Indicates that this method should be executed before exiting the instrumented method. Any class must declare * at most one method with this annotation. The annotated method must be static. * </p> * <p> * By default, the annotated method is not invoked if the instrumented method terminates exceptionally. This behavior * can be changed by setting the {@link OnMethodExit#onThrowable()} property to an exception type for which this advice * method should be invoked. By setting the value to {@link Throwable}, the advice method is always invoked. * </p> * * @see Advice * @see Argument * @see This * @see Enter * @see Return * @see Thrown */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.METHOD) public @interface OnMethodExit { /** * Indicates a {@link Throwable} super type for which this exit advice is invoked if it was thrown from the instrumented method. * If an exception is thrown, it is available via the {@link Thrown} parameter annotation. If a method returns exceptionally, * any parameter annotated with {@link Return} is assigned the parameter type's default value. * * @return The type of {@link Throwable} for which this exit advice handler is invoked. */ Class<? extends Throwable> onThrowable() default NoExceptionHandler.class; /** * Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method * is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code * with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods. * When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to * set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into * the instrumented method. * * @return {@code true} if the annotated method should be inlined into the instrumented method. */ boolean inline() default true; /** * Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution. By default, * any such exception is silently suppressed. Custom behavior can be configured by using {@link Advice#withExceptionHandler(StackManipulation)}. * * @return The type of {@link Throwable} to suppress. * @see Advice#withExceptionPrinting() */ Class<? extends Throwable> suppress() default NoExceptionHandler.class; } /** * <p> * Indicates that the annotated parameter should be mapped to the {@code this} reference of the instrumented method. * </p> * <p> * <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with * {@link OnMethodEnter} where the {@code this} reference is not available. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface This { /** * Determines if the parameter should be assigned {@code null} if the instrumented method is static or a constructor within * an entry method. * * @return {@code true} if the value assignment is optional. */ boolean optional() default false; /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the type declaring the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}. * If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented method's declaring type. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * The typing that should be applied when assigning the {@code this} value. * * @return The typing to apply upon assignment. */ Assigner.Typing typing() default Assigner.Typing.STATIC; } /** * Indicates that the annotated parameter should be mapped to the parameter with index {@link Argument#value()} of * the instrumented method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface Argument { /** * Returns the index of the mapped parameter. * * @return The index of the mapped parameter. */ int value(); /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}. * If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * The typing that should be applied when assigning the argument. * * @return The typing to apply upon assignment. */ Assigner.Typing typing() default Assigner.Typing.STATIC; } /** * Assigns an array containing all arguments of the instrumented method to the annotated parameter. The annotated parameter must * be an array type. If the annotation indicates writability, the assigned array must have at least as many values as the * instrumented method or an {@link ArrayIndexOutOfBoundsException} is thrown. */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface AllArguments { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the type declaring the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}. * If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented method's declaring type. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * The typing that should be applied when assigning the arguments. * * @return The typing to apply upon assignment. */ Assigner.Typing typing() default Assigner.Typing.STATIC; } /** * <p> * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented * method terminates exceptionally, the type's default value is assigned to the parameter, i.e. {@code 0} for numeric types * and {@code null} for reference types. If the return type is {@code void}, the annotated value is {@code null} if and only if * {@link Return#typing()} is set to {@link Assigner.Typing#DYNAMIC}. * </p> * <p> * <b>Note</b>: This annotation must only be used on exit advice methods. * </p> * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface Return { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}. * If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * Determines the typing that is applied when assigning the return value. * * @return The typing to apply when assigning the annotated parameter. */ Assigner.Typing typing() default Assigner.Typing.STATIC; } /** * <p> * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented method terminates * regularly, {@code null} is assigned to the annotated parameter. Note that the Java runtime does not enforce checked exceptions. In order to * capture any error, the parameter type should be of type {@link Throwable}. * </p> * <p> * <b>Note</b>: This annotation must only be used on exit advice methods. * </p> * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface Thrown { boolean readOnly() default true; /** * Determines the typing that is applied when assigning the captured {@link Throwable} to the annotated parameter. * * @return The typing to apply when assigning the annotated parameter. */ Assigner.Typing typing() default Assigner.Typing.DYNAMIC; } /** * <p> * Indicates that the annotated parameter should be mapped to a field in the scope of the instrumented method. * </p> * <p> * <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with * {@link OnMethodEnter} and a non-static field where the {@code this} reference is not available. * </p> * <p> * <b>Note</b>: As the mapping is virtual, Byte Buddy might be required to reserve more space on the operand stack than the * optimal value when accessing this parameter. This does not normally matter as the additional space requirement is minimal. * However, if the runtime performance of class creation is secondary, one can require ASM to recompute the optimal frames by * setting {@link ClassWriter#COMPUTE_MAXS}. This is however only relevant when writing to a non-static field. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface FieldValue { /** * Returns the name of the field. * * @return The name of the field. */ String value(); /** * Returns the type that declares the field that should be mapped to the annotated parameter. If this property * is set to {@code void}, the field is looked up implicitly within the instrumented class's class hierarchy. * The value can also be set to {@link TargetType} in order to look up the type on the instrumented type. * * @return The type that declares the field, {@code void} if this type should be determined implicitly or * {@link TargetType} for the instrumented type. */ Class<?> declaringType() default void.class; /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the mapped field type if the typing is not also set to {@link Assigner.Typing#DYNAMIC}. * If this property is set to {@code true}, the annotated parameter can be any super type of the field type. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * The typing that should be applied when assigning the field value. * * @return The typing to apply upon assignment. */ Assigner.Typing typing() default Assigner.Typing.STATIC; } /** * <p> * Indicates that the annotated parameter should be mapped to a string representation of the instrumented method, * a constant representing the {@link Class} declaring the adviced method or a {@link Method}, {@link Constructor} * or {@code java.lang.reflect.Executable} representing this method. * </p> * <p> * <b>Note</b>: A constant representing a {@link Method} or {@link Constructor} is not cached but is recreated for * every read. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface Origin { /** * Indicates that the origin string should be indicated by the {@link Object#toString()} representation of the instrumented method. */ String DEFAULT = ""; /** * Returns the pattern the annotated parameter should be assigned. By default, the {@link Origin#toString()} representation * of the method is assigned. Alternatively, a pattern can be assigned where: * <ul> * <li>{@code #t} inserts the method's declaring type.</li> * <li>{@code #m} inserts the name of the method ({@code <init>} for constructors and {@code <clinit>} for static initializers).</li> * <li>{@code #d} for the method's descriptor.</li> * <li>{@code #s} for the method's signature.</li> * <li>{@code #r} for the method's return type.</li> * </ul> * Any other {@code #} character must be escaped by {@code \} which can be escaped by itself. This property is ignored if the annotated * parameter is of type {@link Class}. * * @return The pattern the annotated parameter should be assigned. */ String value() default DEFAULT; } /** * <p> * Indicates that the annotated parameter should be mapped to the value that is returned by the advice method that is annotated * by {@link OnMethodEnter}. * </p> * <p><b>Note</b></p>: This annotation must only be used within an exit advice and is only meaningful in combination with an entry advice. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface Enter { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}. * If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * The typing that should be applied when assigning the enter value. * * @return The typing to apply upon assignment. */ Assigner.Typing typing() default Assigner.Typing.STATIC; } /** * Indicates that the annotated parameter should always return a default a boxed version of the instrumented methods return value * (i.e. {@code 0} for numeric values, {@code false} for {@code boolean} types and {@code null} for reference types). The annotated * parameter must be of type {@link Object} and cannot be assigned a value. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface StubValue { /* empty */ } /** * Indicates that the annotated parameter should always return a default value (i.e. {@code 0} for numeric values, {@code false} * for {@code boolean} types and {@code null} for reference types). Any assignments to this variable are without any effect. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @java.lang.annotation.Target(ElementType.PARAMETER) public @interface Unused { /* empty */ } /** * A builder step for creating an {@link Advice} that uses custom mappings of annotations to constant pool values. */ @EqualsAndHashCode public static class WithCustomMapping { /** * A map containing dynamically computed constant pool values that are mapped by their triggering annotation type. */ private final Map<Class<? extends Annotation>, OffsetMapping.Factory<?>> offsetMappings; /** * Creates a new custom mapping builder step without including any custom mappings. */ protected WithCustomMapping() { this(Collections.<Class<? extends Annotation>, OffsetMapping.Factory<?>>emptyMap()); } /** * Creates a new custom mapping builder step with the given custom mappings. * * @param offsetMappings A map containing dynamically computed constant pool values that are mapped by their triggering annotation type. */ protected WithCustomMapping(Map<Class<? extends Annotation>, OffsetMapping.Factory<?>> offsetMappings) { this.offsetMappings = offsetMappings; } /** * Binds the supplied annotation to a type constant of the supplied value. Constants can be strings, method handles, method types * and any primitive or the value {@code null}. * * @param type The type of the annotation being bound. * @param value The value to bind to the annotation. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, Object value) { return bind(type, OffsetMapping.ForStackManipulation.Factory.of(type, value)); } /** * Binds the supplied annotation to the value of the supplied field. The field must be visible by the * instrumented type and must be declared by a super type of the instrumented field. * * @param type The type of the annotation being bound. * @param field The field to bind to this annotation. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, Field field) { return bind(type, new FieldDescription.ForLoadedField(field)); } /** * Binds the supplied annotation to the value of the supplied field. The field must be visible by the * instrumented type and must be declared by a super type of the instrumented field. * * @param type The type of the annotation being bound. * @param fieldDescription The field to bind to this annotation. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, FieldDescription fieldDescription) { return bind(type, new OffsetMapping.ForField.Resolved.Factory<T>(type, fieldDescription)); } /** * Binds the supplied annotation to the supplied parameter's argument. * * @param type The type of the annotation being bound. * @param method The method that defines the parameter. * @param index The index of the parameter. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, Method method, int index) { if (index < 0) { throw new IllegalArgumentException("A parameter cannot be negative: " + index); } else if (method.getParameterTypes().length <= index) { throw new IllegalArgumentException(method + " does not declare a parameter with index " + index); } return bind(type, new MethodDescription.ForLoadedMethod(method).getParameters().get(index)); } /** * Binds the supplied annotation to the supplied parameter's argument. * * @param type The type of the annotation being bound. * @param constructor The constructor that defines the parameter. * @param index The index of the parameter. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, Constructor<?> constructor, int index) { if (index < 0) { throw new IllegalArgumentException("A parameter cannot be negative: " + index); } else if (constructor.getParameterTypes().length <= index) { throw new IllegalArgumentException(constructor + " does not declare a parameter with index " + index); } return bind(type, new MethodDescription.ForLoadedConstructor(constructor).getParameters().get(index)); } /** * Binds the supplied annotation to the supplied parameter's argument. * * @param type The type of the annotation being bound. * @param parameterDescription The parameter for which to bind an argument. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, ParameterDescription parameterDescription) { return bind(type, new OffsetMapping.ForArgument.Resolved.Factory<T>(type, parameterDescription)); } /** * Binds the supplied annotation to the supplied fixed value. * * @param type The type of the annotation being bound. * @param value The value to bind to this annotation. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ @SuppressWarnings("unchecked") public <T extends Annotation> WithCustomMapping bindSerialized(Class<T> type, Serializable value) { return bindSerialized(type, value, (Class<Serializable>) value.getClass()); } /** * Binds the supplied annotation to the supplied fixed value. * * @param type The type of the annotation being bound. * @param value The value to bind to this annotation. * @param targetType The type of {@code value} as which the instance should be treated. * @param <T> The annotation type. * @param <S> The type of the serialized instance. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation, S extends Serializable> WithCustomMapping bindSerialized(Class<T> type, S value, Class<? super S> targetType) { return bind(type, OffsetMapping.ForSerializedValue.Factory.of(type, value, targetType)); } /** * Binds the supplied annotation to the annotation's property of the specified name. * * @param type The type of the annotation being bound. * @param property The name of the annotation property to be bound. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation during binding. */ public <T extends Annotation> WithCustomMapping bindProperty(Class<T> type, String property) { return bind(type, OffsetMapping.ForStackManipulation.OfAnnotationProperty.of(type, property)); } public <T extends Annotation> WithCustomMapping bind(Class<T> type, StackManipulation stackManipulation, java.lang.reflect.Type targetType) { return bind(type, stackManipulation, TypeDefinition.Sort.describe(targetType)); } public <T extends Annotation> WithCustomMapping bind(Class<T> type, StackManipulation stackManipulation, TypeDescription.Generic targetType) { return bind(type, new OffsetMapping.ForStackManipulation.Factory<T>(type, stackManipulation, targetType)); } /** * Binds an annotation type to dynamically computed value. Whenever the {@link Advice} component discovers the given annotation on * a parameter of an advice method, the dynamic value is asked to provide a value that is then assigned to the parameter in question. * * @param type The annotation type that triggers the mapping. * @param offsetMapping The dynamic value that is computed for binding the parameter to a value. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<T> type, OffsetMapping.Factory<? super T> offsetMapping) { Map<Class<? extends Annotation>, OffsetMapping.Factory<?>> offsetMappings = new HashMap<Class<? extends Annotation>, OffsetMapping.Factory<?>>(this.offsetMappings); if (!type.isAnnotation()) { throw new IllegalArgumentException("Not an annotation type: " + type); } else if (offsetMappings.put(type, offsetMapping) != null) { throw new IllegalArgumentException("Annotation type already mapped: " + type); } return new WithCustomMapping(offsetMappings); } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param advice The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(Class<?> advice) { return to(advice, ClassFileLocator.ForClassLoader.of(advice.getClassLoader())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param advice The type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(Class<?> advice, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(advice), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param advice A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(TypeDescription advice, ClassFileLocator classFileLocator) { return Advice.to(advice, classFileLocator, new ArrayList<OffsetMapping.Factory<?>>(offsetMappings.values())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(Class<?> enterAdvice, Class<?> exitAdvice) { ClassLoader enterLoader = enterAdvice.getClassLoader(), exitLoader = exitAdvice.getClassLoader(); return to(enterAdvice, exitAdvice, enterLoader == exitLoader ? ClassFileLocator.ForClassLoader.of(enterLoader) : new ClassFileLocator.Compound(ClassFileLocator.ForClassLoader.of(enterLoader), ClassFileLocator.ForClassLoader.of(exitLoader))); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(Class<?> enterAdvice, Class<?> exitAdvice, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(enterAdvice), new TypeDescription.ForLoadedType(exitAdvice), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational * class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set * to {@code false} are resolvable by the returned instance. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice) { return to(enterAdvice, exitAdvice, ClassFileLocator.NoOp.INSTANCE); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param enterAdvice The type declaring the enter advice. * @param exitAdvice The type declaring the exit advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice, ClassFileLocator classFileLocator) { return Advice.to(enterAdvice, exitAdvice, classFileLocator, new ArrayList<OffsetMapping.Factory<?>>(offsetMappings.values())); } } /** * A marker class that indicates that an advice method does not suppress any {@link Throwable}. */ private static class NoExceptionHandler extends Throwable { /** * A description of the {@link NoExceptionHandler} type. */ private static final TypeDescription DESCRIPTION = new TypeDescription.ForLoadedType(NoExceptionHandler.class); /** * A private constructor as this class is not supposed to be invoked. */ private NoExceptionHandler() { throw new UnsupportedOperationException("This marker class is not supposed to be instantiated"); } } public static final class OnDefaultValue { /** * A private constructor as this class is not supposed to be invoked. */ private OnDefaultValue() { throw new UnsupportedOperationException("This marker class is not supposed to be instantiated"); } } public static final class OnNonDefaultValue { /** * A private constructor as this class is not supposed to be invoked. */ private OnNonDefaultValue() { throw new UnsupportedOperationException("This marker class is not supposed to be instantiated"); } } }
package io.spacedog.client.data; import java.util.Objects; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.spacedog.client.http.SpaceFields; import io.spacedog.utils.Exceptions; import io.spacedog.utils.Json; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = Visibility.NONE, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public class DataWrap<K> implements DataObject, SpaceFields { public static final long MATCH_ANY_VERSIONS = -3L; private K source; private Class<K> sourceClass; private String id; private String type; private long version = MATCH_ANY_VERSIONS; private Object[] sort; private float score; public DataWrap() { } public static <K> DataWrap<K> wrap(K source) { return new DataWrap<K>().source(source); } public static <K> DataWrap<K> wrap(Class<K> sourceClass) { return new DataWrap<K>().sourceClass(sourceClass); } @SuppressWarnings("unchecked") public Class<K> sourceClass() { if (sourceClass == null) if (source != null) return (Class<K>) source.getClass(); return sourceClass; } public DataWrap<K> sourceClass(Class<K> sourceClass) { this.sourceClass = sourceClass; return this; } @JsonProperty public K source() { return source; } public DataWrap<K> source(K source) { this.source = source; return this; } @JsonProperty public String id() { return id; } public DataWrap<K> id(String id) { this.id = id; return this; } @JsonProperty public String type() { if (type == null) { Class<K> sourceClass = sourceClass(); return sourceClass() == null ? null : sourceClass.getSimpleName().toLowerCase(); } return type; } public DataWrap<K> type(String type) { this.type = type; return this; } @JsonProperty public long version() { return version; } public DataWrap<K> version(long version) { this.version = version; return this; } @JsonProperty public float score() { return score; } public DataWrap<K> score(float score) { this.score = score; return this; } @JsonProperty public Object[] sort() { return sort; } public DataWrap<K> sort(Object[] sort) { this.sort = sort; return this; } public boolean isCreated() { DateTime createdAt = createdAt(); DateTime updatedAt = updatedAt(); return createdAt != null && updatedAt != null && createdAt.equals(updatedAt); } @Override public String owner() { K source = source(); if (source instanceof DataObject) return ((DataObject) source).owner(); if (source instanceof ObjectNode) { JsonNode node = ((ObjectNode) source).get(OWNER_FIELD); return Json.isNull(node) ? null : node.asText(); } return null; } @Override public void owner(String owner) { K source = source(); if (source instanceof DataObject) ((DataObject) source).owner(owner); else if (source instanceof ObjectNode) ((ObjectNode) source).put(OWNER_FIELD, owner); else throw Exceptions.unsupportedOperation(source.getClass()); } @Override public String group() { K source = source(); if (source instanceof DataObject) return ((DataObject) source).group(); if (source instanceof ObjectNode) { JsonNode node = ((ObjectNode) source).get(GROUP_FIELD); return Json.isNull(node) ? null : node.asText(); } return null; } @Override public void group(String group) { K source = source(); if (source instanceof DataObject) ((DataObject) source).group(group); else if (source instanceof ObjectNode) ((ObjectNode) source).put(GROUP_FIELD, group); else throw Exceptions.unsupportedOperation(source.getClass()); } @Override public DateTime createdAt() { K source = source(); if (source instanceof DataObject) return ((DataObject) source).createdAt(); if (source instanceof ObjectNode) return Json.toPojo(((ObjectNode) source).get(CREATED_AT_FIELD), DateTime.class); return null; } @Override public void createdAt(DateTime createdAt) { K source = source(); if (source instanceof DataObject) ((DataObject) source).createdAt(createdAt); else if (source instanceof ObjectNode) ((ObjectNode) source).put(CREATED_AT_FIELD, createdAt.toString()); else throw Exceptions.unsupportedOperation(source.getClass()); } @Override public DateTime updatedAt() { K source = source(); if (source instanceof DataObject) return ((DataObject) source).updatedAt(); if (source instanceof ObjectNode) return Json.toPojo(((ObjectNode) source).get(UPDATED_AT_FIELD), DateTime.class); return null; } @Override public void updatedAt(DateTime updatedAt) { K source = source(); if (source instanceof DataObject) ((DataObject) source).updatedAt(updatedAt); else if (source instanceof ObjectNode) ((ObjectNode) source).put(UPDATED_AT_FIELD, updatedAt.toString()); else throw Exceptions.unsupportedOperation(source.getClass()); } @Override @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj instanceof DataWrap == false) return false; DataWrap<K> wrap = (DataWrap<K>) obj; return Objects.equals(id(), wrap.id()) && Objects.equals(source(), wrap.source()) && Objects.equals(sourceClass(), wrap.sourceClass()) && Objects.equals(type(), wrap.type()) && version() == wrap.version(); } @Override public String toString() { return String.format("DataWrap[%s][%s][%s][%s]", type(), id(), version(), source()); } }
package org.jetel.component; import java.io.FileWriter; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.connection.jdbc.DBConnection; import org.jetel.connection.jdbc.SQLCloverCallableStatement; import org.jetel.connection.jdbc.specific.DBConnectionInstance; import org.jetel.connection.jdbc.specific.JdbcSpecific.OperationType; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.parser.DataParser; import org.jetel.database.IConnection; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.JetelException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.AutoFilling; import org.jetel.util.ReadableChannelIterator; import org.jetel.util.file.FileUtils; import org.jetel.util.joinKey.JoinKeyUtils; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.property.RefResFlag; import org.jetel.util.string.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * <h3>DatabaseExecute Component</h3> * <!-- This component executes specified command (SQL/DML) against specified DB. --> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>DBExecute</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>This component executes specified command(s) (SQL/DML) against specified DB</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0] (<i>optional</i>) - stored procedure input parameters or sql statements</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>[0] (<i>optional</i>) - stored procedure output parameters and/or query result set<br> * [1] (<i>optional</i>) - errors: field with <i>ErrCode</i> autofilling is filled by error code,field with <i>ErrText</i> * autofilling is field by error message </td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"DB_EXECUTE"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>dbConnection</b></td><td>id of the Database Connection object to be used to access the database</td> * <tr><td><b>sqlQuery</b></td><td>SQL/DML/DDL statement(s) which has to be executed on database. In case you want to * call stored procedure or function with parameters or producing output data set, it has to be in form: * <i>{[? = ]call procedreName([?[,?...]])}</i> (Note: remember to close statement in curly brackets), when input/output parameters * has to be set in proper attribute. If several statements should be executed, separate them by [;] (semicolon - default value; see sqlStatementDelimiter). They will be executed one by one.</td> * </tr> * <tr><td><b>inParameters</b></td><td>when calling stored procedure/function with input parameters. Maps out * which input fields would be treated as proper input parameters. Parameters are counted from 1. Form:<i> * 1:=$inField1;...n:=$infieldN<i></td> * <tr><td><b>outParameters</b></td><td>when calling stored procedure/function with output parameters or returning value. Maps out * which output fields would be treated as proper output parameters. Parameters are counted from 1. If function return * a value, this is the first parameter Form:<i> 1:=$outField1;...n:=$outfieldN<i></td> * <tr><td><b>outputFields</b></td><td>when stored procedure/function returns set of data its output will be parsed * to given output fields. This is list of output fields delimited by semicolon.<i></td> * <tr><td><b>sqlStatementDelimiter</b><br><i>optional</i></td><td>delimiter of sql statement in sqlQuery attribute</td> * <tr><td><b>url</b><br><i>optional</i></td><td>url location of the query<br>the query will be loaded from file referenced by the url or * read from input port (see {@link DataReader} component)</td> * <tr><td><b>charset </b><i>optional</i></td><td>encoding of extern query</td></tr> * <tr><td><b>inTransaction<br><i>optional</i></b></td><td>one of: <i>ONE,SET,ALL</i> specifying whether statement(s) should be executed * in transaction. For <ul><li>ONE - commit is perform after each query execution</li> * <li>SET - for each input record there are executed all statements. After set of statements there is called commit, so if * error occurred during execution of any statement, all statements for this record would be rolled back</li> * <li>ALL - commit is called only after all statements, so if error occurred all operations would be rolled back</li></ul> * Default is <i>SET</i>.<br> * <i>Works only if database supports transactions.</i></td></tr> * <tr><td><b>printStatements</b><br><i>optional</i></td><td>Specifies whether SQL commands are outputted to stdout. Default - No</td></tr> * <tr><td><b>callStatement</b><br><i>optional</i></td><td>boolean value (Y/N) - specifies whether SQL commands should be treated as stored procedure calls - using JDBC CallableStatement. Default - "N"</td></tr> * <tr><td>&lt;SQLCode&gt;<br><i><small>!!XML tag!!</small></i></td><td>This tag allows for specifying more than one statement. See example below.</td></tr> * <tr><td><b>errorActions </b><i>optional</i></td><td>defines if graph is to stop, when sql statement throws Sql Exception. * Available actions are: STOP or CONTINUE. For CONTINUE action, error message is logged to console or file (if errorLog attribute * is specified) and for STOP exception is populated and graph execution is stopped. <br> * Error action can be set for each exception error code (value1=action1;value2=action2;...) or for all values the same action (STOP * or CONTINUE). It is possible to define error actions for some values and for all other values (MIN_INT=myAction). * Default value is <i>STOP</i></td></tr> * <tr><td><b>errorLog</b><br><i>optional</i></td><td>path to the error log file. Each error (after which graph continues) is logged in * following way: slqQuery;errorCode;errorMessage - fields are delimited by Defaults.Component.KEY_FIELDS_DELIMITER.</td></tr> * </table> * * <h4>Example:</h4> * <pre>&lt;Node id="DATABASE_RUN" type="DB_EXECUTE" dbConnection="NorthwindDB" sqlQuery="drop table employee_z"/&gt;</pre> * <pre>&lt;Node id="DATABASE_RUN" type="DB_EXECUTE" dbConnection="NorthwindDB" inTransaction="Y"&gt; * &lt;SQLCode&gt; * create table testTab ( * name varchar(20) * ); * * insert into testTab ('nobody'); * insert into testTab ('somebody'); * &lt;/SQLCode&gt; * &lt;/Node&gt; </pre> * <pre> * &lt;Node dbConnection="Connection1" id="DB_EXECUTE1" type="DB_EXECUTE"&gt; * &lt;attr name="sqlQuery">create table proc_table ( * id INTEGER, * string VARCHAR(80), * date DATETIME * ); * CREATE PROCEDURE SPDownload * &#64;last_dl_ts DATETIME * AS * BEGIN * SELECT id, string, date * FROM proc_table * WHERE date >= &#64;last_dl_ts * END;&gt;&lt;/attr&gt; * &lt;/Node&gt;</pre> * <pre> * &lt;Node callStatement="true" dbConnection="Connection1" id="DB_EXECUTE2" inParameters="1:=$date" * outputFields="id;string;date" type="DB_EXECUTE" sqlQuery="{call SPDownload(?)}" &gt; * * &lt;Node dbConnection="Connection0" errorActions="MIN_INT=CONTINUE;" id="DB_EXECUTE0" printStatements="true" * type="DB_EXECUTE" url="port:$0.field1:discrete"/> * * @author dpavlis, avackova (avackova@javlinconsulting.cz) * @since Jan 17 2004 * @revision $Revision$ * @created 22. ?ervenec 2003 * @see org.jetel.database.AnalyzeDB */ public class DBExecute extends Node { public static final String XML_PRINTSTATEMENTS_ATTRIBUTE = "printStatements"; public static final String XML_INTRANSACTION_ATTRIBUTE = "inTransaction"; public static final String XML_SQLCODE_ELEMENT = "SQLCode"; public static final String XML_DBCONNECTION_ATTRIBUTE = "dbConnection"; public static final String XML_SQLQUERY_ATTRIBUTE = "sqlQuery"; public static final String XML_DBSQL_ATTRIBUTE = "dbSQL"; public static final String XML_URL_ATTRIBUTE = "url"; public static final String XML_PROCEDURE_CALL_ATTRIBUTE = "callStatement"; public static final String XML_STATEMENT_DELIMITER = "sqlStatementDelimiter"; public static final String XML_CHARSET_ATTRIBUTE = "charset"; public static final String XML_IN_PARAMETERS = "inParameters"; public static final String XML_OUT_PARAMETERS = "outParameters"; public static final String XML_OUTPUT_FIELDS = "outputFields"; private static final String XML_ERROR_ACTIONS_ATTRIBUTE = "errorActions"; private static final String XML_ERROR_LOG_ATTRIBUTE = "errorLog"; private enum InTransaction { ONE, SET, ALL, NEVER_COMMIT; } private DBConnection dbConnection; private DBConnectionInstance connectionInstance; private String dbConnectionName; private String sqlQuery; private String[] dbSQL; private InTransaction transaction = InTransaction.SET; private boolean printStatements = false; private boolean procedureCall = false; private String sqlStatementDelimiter; /** Description of the Field */ public final static String COMPONENT_TYPE = "DB_EXECUTE"; private final static String DEFAULT_SQL_STATEMENT_DELIMITER = ";"; private final static String PARAMETERS_SET_DELIMITER = " private final static int READ_FROM_PORT = 0; private final static int WRITE_TO_PORT = 0; private final static int ERROR_PORT = 1; static Log logger = LogFactory.getLog(DBExecute.class); private Statement sqlStatement; private SQLCloverCallableStatement[] callableStatement; private DataRecord inRecord, outRecord; private Map<Integer, String>[] inParams, outParams; private String[] outputFields; private String fileUrl; private String charset; private String errorActionsString; private Map<Integer, ErrorAction> errorActions = new HashMap<Integer, ErrorAction>(); private String errorLogURL; private FileWriter errorLog; private int errorCodeFieldNum; private int errMessFieldNum; private DataRecord errRecord; private OutputPort errPort; private ReadableChannelIterator channelIterator; private OutputPort outPort; private DataParser parser; private DataRecordMetadata statementMetadata; /** * Constructor for the DBExecute object * * @param id Description of Parameter * @param dbConnectionName Description of Parameter * @param dbSQL Description of the Parameter * @since September 27, 2002 */ public DBExecute(String id, String dbConnectionName, String dbSQL) { super(id); this.dbConnectionName=dbConnectionName; this.sqlQuery=dbSQL; } /** *Constructor for the DBExecute object * * @param id Description of the Parameter * @param dbConnectionName Description of the Parameter * @param dbSQL Description of the Parameter */ public DBExecute(String id, String dbConnectionName, String[] dbSQL) { super(id); this.dbConnectionName = dbConnectionName; this.dbSQL = dbSQL; // default } public DBExecute(String id, DBConnection dbConnection, String dbSQL){ super(id); this.dbConnection=dbConnection; this.sqlQuery=dbSQL; } public DBExecute(String id, DBConnection dbConnection, String dbSQL[]){ super(id); this.dbSQL=dbSQL; this.dbConnection=dbConnection; } /** * Description of the Method * * @exception ComponentNotReadyException Description of Exception * @since September 27, 2002 */ public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); // get dbConnection from graph if (dbConnection == null){ IConnection conn = getGraph().getConnection(dbConnectionName); if(conn == null) { throw new ComponentNotReadyException("Can't find DBConnection ID: " + dbConnectionName); } if(!(conn instanceof DBConnection)) { throw new ComponentNotReadyException("Connection with ID: " + dbConnectionName + " isn't instance of the DBConnection class."); } dbConnection = (DBConnection) conn; } if (!dbConnection.isInitialized()) { dbConnection.init(); } if (dbSQL==null){ String delimiter = sqlStatementDelimiter !=null ? sqlStatementDelimiter : DEFAULT_SQL_STATEMENT_DELIMITER; if (sqlQuery != null) { // temporary fix for issue 3472, if match contains odd count of single or double qoutes, // it is not removed from string - lkrejci // TODO: create sql parser which will detect all comments correctly. Matcher matcher = dbConnection.getJdbcSpecific().getCommentsPattern().matcher(sqlQuery); boolean result = matcher.find(); String sqlQueryWithouComments; if (result) { boolean replace; int countSingleQoute; int countDoubleQoute; StringBuffer sb = new StringBuffer(); do { replace = true; if (sqlQuery.charAt(matcher.start()) == '-') { int lastSingleQuote = sqlQuery.lastIndexOf("'", matcher.start()); int lastDoubleQuote = sqlQuery.lastIndexOf("\"", matcher.start()); if (lastSingleQuote != -1 || lastDoubleQuote != -1) { char[] chars = sqlQuery.substring(matcher.start(), matcher.end()).toCharArray(); countSingleQoute = 0; countDoubleQoute = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == '\'') { countSingleQoute++; } else if (chars[i] == '"') { countDoubleQoute++; } } replace = ((countSingleQoute % 2 == 1) || (countDoubleQoute % 2 == 1)) ? false : true; } } if (replace) { matcher.appendReplacement(sb, ""); } result=matcher.find(); } while (result); matcher.appendTail(sb); sqlQueryWithouComments = sb.toString(); } else { sqlQueryWithouComments = sqlQuery; } // end of issue 3472 temporary fix String[] parts = StringUtils.split(sqlQueryWithouComments,delimiter); ArrayList<String> tmp = new ArrayList<String>(); for(String part: parts) { if (part.trim().length() > 0) { tmp.add(part); } } dbSQL = tmp.toArray(new String[tmp.size()]); }else{//read statements from file or input port channelIterator = new ReadableChannelIterator(getInputPort(READ_FROM_PORT), getGraph().getRuntimeContext().getContextURL(), fileUrl); channelIterator.setCharset(charset); channelIterator.setDictionary(getGraph().getDictionary()); channelIterator.init(); //statements are single strings delimited by delimiter (see above) statementMetadata = new DataRecordMetadata("_statement_metadata_", DataRecordMetadata.DELIMITED_RECORD); statementMetadata.setFieldDelimiter(delimiter); DataFieldMetadata statementField = new DataFieldMetadata("_statement_field_", DataFieldMetadata.STRING_FIELD, null); statementField.setEofAsDelimiter(true); statementField.setTrim(true); statementMetadata.addField(statementField); parser = charset != null ? new DataParser(charset) : new DataParser(); parser.init(statementMetadata); } } if (printStatements && dbSQL != null){ for (int i = 0; i < dbSQL.length; i++) { logger.info(dbSQL[i]); } } if ((outPort = getOutputPort(WRITE_TO_PORT)) != null) { outRecord = new DataRecord(outPort.getMetadata()); outRecord.init(); } errPort = getOutputPort(ERROR_PORT); if (errPort != null){ errRecord = new DataRecord(errPort.getMetadata()); errRecord.init(); errorCodeFieldNum = errRecord.getMetadata().findAutoFilledField(AutoFilling.ERROR_CODE); errMessFieldNum = errRecord.getMetadata().findAutoFilledField(AutoFilling.ERROR_MESSAGE); } errorActions = new HashMap<Integer, ErrorAction>(); if (errorActionsString != null){ String[] actions = StringUtils.split(errorActionsString); if (actions.length == 1 && !actions[0].contains("=")){ errorActions.put(Integer.MIN_VALUE, ErrorAction.valueOf(actions[0].trim().toUpperCase())); }else{ String[] action; for (String string : actions) { action = JoinKeyUtils.getMappingItemsFromMappingString(string); try { errorActions.put(Integer.parseInt(action[0]), ErrorAction.valueOf(action[1].toUpperCase())); } catch (NumberFormatException e) { if (action[0].equals(ComponentXMLAttributes.STR_MIN_INT)) { errorActions.put(Integer.MIN_VALUE, ErrorAction.valueOf(action[1].toUpperCase())); } } } } }else{ errorActions.put(Integer.MIN_VALUE, ErrorAction.DEFAULT_ERROR_ACTION); } } @Override public synchronized void reset() throws ComponentNotReadyException { super.reset(); } @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); if (firstRun()) { //a phase-dependent part of initialization initConnection(); } else { if (getGraph().getRuntimeContext().isBatchMode() && dbConnection.isThreadSafeConnections()) { initConnection(); } if (outRecord != null) { outRecord.reset(); } if (errRecord != null) { errRecord.reset(); } } if (getInPorts().size() > 0) { inRecord = new DataRecord(getInputPort(READ_FROM_PORT).getMetadata()); inRecord.init(); } initStatements(); if (errorLogURL != null) { try { errorLog = new FileWriter(FileUtils.getFile(getGraph().getRuntimeContext().getContextURL(), errorLogURL)); } catch (IOException e) { throw new ComponentNotReadyException(this, XML_ERROR_LOG_ATTRIBUTE, e.getMessage()); } } } @Override public void postExecute() throws ComponentNotReadyException { super.postExecute(); if (errorLog != null){ try { errorLog.flush(); } catch (IOException e) { throw new ComponentNotReadyException(this, XML_ERROR_LOG_ATTRIBUTE, e.getMessage()); } try { errorLog.close(); } catch (IOException e) { throw new ComponentNotReadyException(this, XML_ERROR_LOG_ATTRIBUTE, e.getMessage()); } } try { if (callableStatement != null) { for (SQLCloverCallableStatement statement : callableStatement) { statement.close(); } } if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException e) { logger.warn("SQLException when closing statement", e); } if (getGraph().getRuntimeContext().isBatchMode()) { dbConnection.closeConnection(getId(), procedureCall ? OperationType.CALL : OperationType.WRITE); } } private void initConnection() throws ComponentNotReadyException { try { if (procedureCall) { connectionInstance = dbConnection.getConnection(getId(), OperationType.CALL); } else { connectionInstance = dbConnection.getConnection(getId(), OperationType.WRITE); } } catch (JetelException e) { throw new ComponentNotReadyException(e); } } private void initStatements() throws ComponentNotReadyException { try { // prepare statements if are not read from file or port if (procedureCall) { int resultSetType = dbConnection.getJdbcDriver().getResultSetType(); if (dbSQL != null) { callableStatement = new SQLCloverCallableStatement[dbSQL.length]; for (int i = 0; i < callableStatement.length; i++) { callableStatement[i] = new SQLCloverCallableStatement( connectionInstance, dbSQL[i], inRecord, outRecord, resultSetType); if (inParams != null) { callableStatement[i].setInParameters(inParams[i]); } if (outParams != null) { callableStatement[i].setOutParameters(outParams[i]); } callableStatement[i].setOutputFields(outputFields); callableStatement[i].prepareCall(); } } else if (inParams != null) { throw new ComponentNotReadyException(this, XML_SQLQUERY_ATTRIBUTE, "Can't read statement and parameters from input port"); } else { callableStatement = new SQLCloverCallableStatement[1]; } } else { sqlStatement = connectionInstance.getSqlConnection().createStatement(); } // this does not work for some drivers try { // -pnajvar // This was bugfix #2207 but seems to cause more trouble than good // Rather, set transaction to default empty // if (DefaultConnection.isTransactionsSupported(connectionInstance.getSqlConnection())) { // connectionInstance.getSqlConnection().setAutoCommit(false); // Autocommit should be disabled only if multiple queries are executed within a single transaction. // Otherwise some queries might fail. connectionInstance.getSqlConnection().setAutoCommit(transaction == InTransaction.ONE); } catch (SQLException ex) { if (transaction != InTransaction.ONE) { throw new ComponentNotReadyException("Can't disable AutoCommit mode for DB: " + dbConnection + " !"); } } } catch (SQLException e) { throw new ComponentNotReadyException(this, XML_SQLCODE_ELEMENT, e.getMessage()); } catch (Exception e) { throw new ComponentNotReadyException(e); } } /** * Sets the transaction attribute of the DBExecute object * * @param transaction The new transaction value */ public void setTransaction(String transaction){ try { this.transaction = InTransaction.valueOf(transaction.toUpperCase()); } catch (IllegalArgumentException e) { if (Boolean.parseBoolean(transaction)) { this.transaction = InTransaction.ALL; } } } public void setPrintStatements(boolean printStatements){ this.printStatements=printStatements; } private void handleException(SQLException e, DataRecord inRecord, int queryIndex) throws IOException, InterruptedException, SQLException{ ErrorAction action = errorActions.get(e.getErrorCode()); if (action == null) { action = errorActions.get(Integer.MIN_VALUE); if (action == null) { action = ErrorAction.DEFAULT_ERROR_ACTION; } } if (action == ErrorAction.CONTINUE) { if (errRecord != null) { if (inRecord != null) { errRecord.copyFieldsByName(inRecord); } if (errorCodeFieldNum != -1) { errRecord.getField(errorCodeFieldNum).setValue(e.getErrorCode()); } if (errMessFieldNum != -1) { errRecord.getField(errMessFieldNum).setValue(e.getMessage()); } errPort.writeRecord(errRecord); }else if (errorLog != null){ errorLog.write(queryIndex > -1 ? dbSQL[queryIndex] : "commit"); errorLog.write(Defaults.Component.KEY_FIELDS_DELIMITER); errorLog.write(String.valueOf(e.getErrorCode())); errorLog.write(Defaults.Component.KEY_FIELDS_DELIMITER); errorLog.write(e.getMessage()); errorLog.write("\n"); }else{ logger.warn(e.getMessage()); } }else{ if (errorLog != null){ errorLog.flush(); errorLog.close(); } try { connectionInstance.getSqlConnection().rollback(); } catch (SQLException e1) { logger.warn("Can't rollback!!", e); } throw e; } } private void dbCommit() throws IOException, InterruptedException, SQLException{ if (!connectionInstance.getSqlConnection().getAutoCommit()) { try { connectionInstance.getSqlConnection().commit(); } catch (SQLException e) { handleException(e, inRecord, -1); } } } @Override public Result execute() throws Exception { try { if (channelIterator != null) { DataRecord statementRecord; ReadableByteChannel tmp;//TODO remove it !!!!!! while (channelIterator.hasNext()) { tmp = channelIterator.next(); if (tmp == null) break; parser.setDataSource(tmp); statementRecord = new DataRecord(statementMetadata); statementRecord.init(); int index = 0; //read statements from byte channel while ((statementRecord = parser.getNext(statementRecord)) != null) { if (printStatements) { logger.info("Executing statement: " + statementRecord.getField(0).toString()); } try { if (procedureCall) { callableStatement[0] = new SQLCloverCallableStatement(connectionInstance, statementRecord.getField(0).toString(), null, outRecord, dbConnection.getJdbcDriver().getResultSetType()); callableStatement[0].prepareCall(); executeCall(callableStatement[0], index); }else{ sqlStatement.executeUpdate(statementRecord.getField(0).toString()); } } catch (SQLException e) { handleException(e, null, index); } index++; if (transaction == InTransaction.ONE){ dbCommit(); } } if (transaction == InTransaction.SET){ dbCommit(); } } }else{//sql statements are "solid" (set as sql query) InputPort inPort = getInputPort(READ_FROM_PORT); if (inPort != null) { inRecord = inPort.readRecord(inRecord); } if (inPort == null || inRecord != null) do { for (int i = 0; i < dbSQL.length; i++){ try { if (procedureCall) { executeCall(callableStatement[i], i); }else{ sqlStatement.executeUpdate(dbSQL[i]); } } catch (SQLException e) { handleException(e, inRecord, i); } if (transaction == InTransaction.ONE){ dbCommit(); } } if (transaction == InTransaction.SET){ dbCommit(); } if (inPort != null) { inRecord = inPort.readRecord(inRecord); } } while (runIt && inRecord != null); } if (runIt && transaction == InTransaction.ALL){ dbCommit(); } if (!runIt) { connectionInstance.getSqlConnection().rollback(); } } finally { broadcastEOF(); } return runIt ? Result.FINISHED_OK : Result.ABORTED; } /** * Executes call and sends results to output port * * @param callableStatement callable sql clover statement * @param i number of statement (for proper setting output parameters) * @throws SQLException * @throws IOException * @throws InterruptedException */ private void executeCall(SQLCloverCallableStatement callableStatement, int i) throws SQLException, IOException, InterruptedException{ boolean sendOut = outParams != null && i < outParams.length && outParams[i] != null; /* * pnajvar- * sendOut only if outParams is different than "result_set" * This is a workaround which should be reviewed by the one who implemented this method * as I don't have any knowledge why "send out if any output parameters even when isNext()==false" behavior */ if (sendOut && outParams[i].containsValue(SQLCloverCallableStatement.RESULT_SET_OUTPARAMETER_NAME)){ sendOut = false; } callableStatement.executeCall(); if (outPort != null) { // if (sendOut) { // outPort.writeRecord(callableStatement.getOutRecord()); // sendOut = callableStatement.isNext(); // } while (sendOut); // order in this is important - isNext() THEN sendOut while(callableStatement.isNext() || sendOut) { outPort.writeRecord(callableStatement.getOutRecord()); sendOut = false; } } } /** * Description of the Method * * @return Description of the Returned Value * @since September 27, 2002 */ @Override public void toXML(Element xmlElement) { // set attributes of DBExecute super.toXML(xmlElement); xmlElement.setAttribute(XML_DBCONNECTION_ATTRIBUTE, this.dbConnectionName); xmlElement.setAttribute(XML_PRINTSTATEMENTS_ATTRIBUTE, String.valueOf(this.printStatements)); xmlElement.setAttribute(XML_INTRANSACTION_ATTRIBUTE, String.valueOf(this.transaction)); xmlElement.setAttribute(XML_PROCEDURE_CALL_ATTRIBUTE,String.valueOf(procedureCall)); if (sqlStatementDelimiter!=null){ xmlElement.setAttribute(XML_STATEMENT_DELIMITER, sqlStatementDelimiter); } if (outputFields != null){ xmlElement.setAttribute(XML_OUTPUT_FIELDS, StringUtils.stringArraytoString(outputFields, Defaults.Component.KEY_FIELDS_DELIMITER)); } StringBuilder attr = new StringBuilder(); if (inParams != null) { for (int i = 0; i < inParams.length; i++) { attr.append(StringUtils.mapToString(inParams[i], Defaults.ASSIGN_SIGN, Defaults.Component.KEY_FIELDS_DELIMITER)); attr.append(PARAMETERS_SET_DELIMITER); } xmlElement.setAttribute(XML_IN_PARAMETERS, attr.toString()); } attr.setLength(0); if (outParams != null) { for (int i = 0; i < outParams.length; i++) { attr.append(StringUtils.mapToString(outParams[i], Defaults.ASSIGN_SIGN, Defaults.Component.KEY_FIELDS_DELIMITER)); attr.append(PARAMETERS_SET_DELIMITER); } xmlElement.setAttribute(XML_OUT_PARAMETERS, attr.toString()); } // use attribute for single SQL command, SQLCode element for multiple if (this.dbSQL.length == 1) { xmlElement.setAttribute(XML_SQLQUERY_ATTRIBUTE, this.dbSQL[0]); }else if (fileUrl != null){ xmlElement.setAttribute(XML_URL_ATTRIBUTE, fileUrl); if (charset != null) { xmlElement.setAttribute(XML_CHARSET_ATTRIBUTE, charset); } }else { Document doc = xmlElement.getOwnerDocument(); Element childElement = doc.createElement(ComponentXMLAttributes.XML_ATTRIBUTE_NODE_NAME); childElement.setAttribute(ComponentXMLAttributes.XML_ATTRIBUTE_NODE_NAME_ATTRIBUTE, XML_SQLCODE_ELEMENT); // join given SQL commands StringBuffer buf = new StringBuffer(dbSQL[0]); String delimiter = sqlStatementDelimiter !=null ? sqlStatementDelimiter : DEFAULT_SQL_STATEMENT_DELIMITER; for (int i=1; i<dbSQL.length; i++) { buf.append(delimiter + dbSQL[i] + "\n"); } Text textElement = doc.createTextNode(buf.toString()); childElement.appendChild(textElement); xmlElement.appendChild(childElement); } if (errorActionsString != null){ xmlElement.setAttribute(XML_ERROR_ACTIONS_ATTRIBUTE, errorActionsString); } if (errorLogURL != null){ xmlElement.setAttribute(XML_ERROR_LOG_ATTRIBUTE, errorLogURL); } } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since September 27, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes( xmlElement, graph); org.w3c.dom.Node childNode; ComponentXMLAttributes xattribsChild; DBExecute executeSQL; String query = null, fileURL = null; try { if (xattribs.exists(XML_URL_ATTRIBUTE)) { fileURL = xattribs.getStringEx(XML_URL_ATTRIBUTE, RefResFlag.SPEC_CHARACTERS_OFF); } else if (xattribs.exists(XML_SQLQUERY_ATTRIBUTE)) { query = xattribs.getString(XML_SQLQUERY_ATTRIBUTE); } else if (xattribs.exists(XML_DBSQL_ATTRIBUTE)) { query = xattribs.getString(XML_DBSQL_ATTRIBUTE); } else if (xattribs.exists(XML_SQLCODE_ELEMENT)) { query = xattribs.getString(XML_SQLCODE_ELEMENT); } else {// we try to get it from child text node - slightly obsolete // now childNode = xattribs.getChildNode(xmlElement, XML_SQLCODE_ELEMENT); if (childNode == null) { throw new RuntimeException("Can't find <SQLCode> node !"); } xattribsChild = new ComponentXMLAttributes((Element)childNode, graph); query = xattribsChild.getText(childNode); } executeSQL = new DBExecute(xattribs .getString(XML_ID_ATTRIBUTE), xattribs .getString(XML_DBCONNECTION_ATTRIBUTE), query); if (fileURL != null) { executeSQL.setFileURL(fileURL); if (xattribs.exists(XML_CHARSET_ATTRIBUTE)) { executeSQL.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE)); } } if (xattribs.exists(XML_INTRANSACTION_ATTRIBUTE)) { executeSQL.setTransaction(xattribs .getString(XML_INTRANSACTION_ATTRIBUTE)); } if (xattribs.exists(XML_PRINTSTATEMENTS_ATTRIBUTE)) { executeSQL.setPrintStatements(xattribs .getBoolean(XML_PRINTSTATEMENTS_ATTRIBUTE)); } if (xattribs.exists(XML_PROCEDURE_CALL_ATTRIBUTE)){ executeSQL.setProcedureCall(xattribs.getBoolean(XML_PROCEDURE_CALL_ATTRIBUTE)); } if (xattribs.exists(XML_IN_PARAMETERS)){ executeSQL.setInParameters(xattribs.getString(XML_IN_PARAMETERS)); } if (xattribs.exists(XML_OUT_PARAMETERS)){ executeSQL.setOutParameters(xattribs.getString(XML_OUT_PARAMETERS)); } if (xattribs.exists(XML_OUTPUT_FIELDS)){ executeSQL.setOutputFields(xattribs.getString(XML_OUTPUT_FIELDS).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); } if (xattribs.exists(XML_STATEMENT_DELIMITER)){ executeSQL.setSqlStatementDelimiter(xattribs.getString(XML_STATEMENT_DELIMITER)); } if (xattribs.exists(XML_ERROR_ACTIONS_ATTRIBUTE)){ executeSQL.setErrorActions(xattribs.getString(XML_ERROR_ACTIONS_ATTRIBUTE)); } if (xattribs.exists(XML_ERROR_LOG_ATTRIBUTE)){ executeSQL.setErrorLog(xattribs.getString(XML_ERROR_LOG_ATTRIBUTE)); } } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } return executeSQL; } public void setCharset(String charset) { this.charset = charset; } public void setFileURL(String fileURL) { this.fileUrl = fileURL; } public void setErrorLog(String errorLog) { this.errorLogURL = errorLog; } public void setErrorActions(String string) { this.errorActionsString = string; } public void setInParameters(String string) { String[] inParameters = string.split(PARAMETERS_SET_DELIMITER); inParams = new HashMap[inParameters.length]; for (int i = 0; i < inParameters.length; i++) { inParams[i] = convertMappingToMap(inParameters[i]); } } public void setOutParameters(String string) { String[] outParameters = string.split(PARAMETERS_SET_DELIMITER); outParams = new HashMap[outParameters.length]; for (int i = 0; i < outParameters.length; i++) { outParams[i] = convertMappingToMap(outParameters[i]); } } public static Map<Integer, String> convertMappingToMap(String mapping){ if (StringUtils.isEmpty(mapping)) return null; String[] mappings = mapping.split(Defaults.Component.KEY_FIELDS_DELIMITER); HashMap<Integer, String> result = new HashMap<Integer, String>(); int assignIndex; boolean isFieldInicator = mapping.indexOf(Defaults.CLOVER_FIELD_INDICATOR) > -1; int assignSignLength = Defaults.ASSIGN_SIGN.length(); for (int i = 0; i < mappings.length; i++) { assignIndex = mappings[i].indexOf(Defaults.ASSIGN_SIGN); if (assignIndex > -1) { if (mappings[i].startsWith(Defaults.CLOVER_FIELD_INDICATOR)) { result.put(Integer.parseInt(mappings[i].substring(assignIndex + assignSignLength).trim()), isFieldInicator ? mappings[i].substring(Defaults.CLOVER_FIELD_INDICATOR.length(), assignIndex).trim() : mappings[i].substring(0, assignIndex).trim()); } else { result.put(Integer.parseInt(mappings[i].substring(0, assignIndex).trim()), isFieldInicator ? mappings[i].substring(assignIndex + assignSignLength).trim().substring(Defaults.CLOVER_FIELD_INDICATOR.length()): mappings[i].substring(assignIndex + assignSignLength).trim()); } }else{ result.put(i+1, isFieldInicator ? mappings[i].trim().substring(Defaults.CLOVER_FIELD_INDICATOR.length()) : mappings[i].trim()); } } return result.size() > 0 ? result : null; } /** * Description of the Method * * @return Description of the Return Value */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if(!checkInputPorts(status, 0, 1) || !checkOutputPorts(status, 0, 2)) { return status; } if (charset != null && !Charset.isSupported(charset)) { status.add(new ConfigurationProblem( "Charset "+charset+" not supported!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } try { if (dbConnection == null){ IConnection conn = getGraph().getConnection(dbConnectionName); if(conn == null) { throw new ComponentNotReadyException("Can't find DBConnection ID: " + dbConnectionName); } if(!(conn instanceof DBConnection)) { throw new ComponentNotReadyException("Connection with ID: " + dbConnectionName + " isn't instance of the DBConnection class."); } } if (errorActionsString != null){ ErrorAction.checkActions(errorActionsString); } if (errorLog != null){ FileUtils.canWrite(getGraph().getRuntimeContext().getContextURL(), errorLogURL); } if (getOutputPort(WRITE_TO_PORT) == null && procedureCall && (dbSQL != null || sqlQuery != null) && outParams != null) { status.add(new ConfigurationProblem("Output port must be defined when output parameters are set.", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } } catch (ComponentNotReadyException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); if(!StringUtils.isEmpty(e.getAttributeName())) { problem.setAttributeName(e.getAttributeName()); } status.add(problem); } return status; } public String getType(){ return COMPONENT_TYPE; } public boolean isProcedureCall() { return procedureCall; } public void setProcedureCall(boolean procedureCall) { this.procedureCall = procedureCall; } /** * @return the sqlStatementDelimiter */ public String getSqlStatementDelimiter() { return sqlStatementDelimiter; } /** * @param sqlStatementDelimiter the sqlStatementDelimiter to set */ public void setSqlStatementDelimiter(String sqlStatementDelimiter) { this.sqlStatementDelimiter = sqlStatementDelimiter; } public void setOutputFields(String[] outputFields) { this.outputFields = outputFields; } }
package org.jetel.component; import java.io.FileInputStream; import java.io.IOException; import java.security.InvalidParameterException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.IntegerDataField; import org.jetel.data.StringDataField; import org.jetel.data.parser.XLSDataParser; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ParserExceptionHandlerFactory; import org.jetel.exception.PolicyType; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.Node; import org.jetel.graph.TransformationGraph; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.SynchronizeUtils; import org.w3c.dom.Element; /** * @author avackova * */ public class XLSReader extends Node { public final static String COMPONENT_TYPE = "XLS_READER"; static Log logger = LogFactory.getLog(XLSReader.class); /** XML attribute names */ private static final String XML_STARTROW_ATTRIBUTE = "startRow"; private static final String XML_FINALROW_ATTRIBUTE = "finalRow"; private static final String XML_MAXERRORCOUNT_ATTRIBUTE = "maxErrorCount"; private final static String XML_FILE_ATTRIBUTE = "fileURL"; private final static String XML_CHARSET_ATTRIBUTE = "charset"; private final static String XML_DATAPOLICY_ATTRIBUTE = "dataPolicy"; private final static String XML_SHEETNAME_ATTRIBUTE = "sheetName"; private final static int OUTPUT_PORT = 0; private String fileURL; private int startRow = -1; private int finalRow = -1; private int maxErrorCount = -1; private XLSDataParser parser; private PolicyType policyType = PolicyType.STRICT; private String sheetName; /** * @param id */ public XLSReader(String id, String fileURL) { super(id); this.fileURL = fileURL; parser = new XLSDataParser(); } public XLSReader(String id, String fileURL, String charset) { super(id); this.fileURL = fileURL; parser = new XLSDataParser(charset); } /* (non-Javadoc) * @see org.jetel.graph.Node#getType() */ @Override public String getType() { return COMPONENT_TYPE; } /* (non-Javadoc) * @see org.jetel.graph.Node#run() */ @Override public void run() { DataRecord record = new DataRecord(getOutputPort(OUTPUT_PORT).getMetadata()); record.init(); int errorCount = 0; int diffRow = (startRow != -1) ? finalRow - startRow : finalRow - 1; try{ while (((record) != null) && runIt) { try { record = parser.getNext(record); if (record!=null){ writeRecordBroadcast(record); SynchronizeUtils.cloverYield(); }else{ broadcastEOF(); } }catch(BadDataFormatException bdfe){ if(policyType == PolicyType.STRICT) { throw bdfe; } else { logger.info(bdfe.getMessage()); if(maxErrorCount != -1 && ++errorCount > maxErrorCount) { logger.error("DataParser (" + getName() + "): Max error count exceeded."); break; } } } if(finalRow != -1 && parser.getRecordCount() > diffRow) { break; } } } catch (IOException ex) { resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg = ex.getClass().getName()+" : "+ ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; return; } // parser.close(); if (runIt) { resultMsg = "OK"; } else { resultMsg = "STOPPED"; } resultCode = Node.RESULT_OK; } /* * (non-Javadoc) * * @see org.jetel.graph.GraphElement#checkConfig() */ @Override public boolean checkConfig() { return true; } public static Node fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException { XLSReader aXLSReader = null; ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); try { if (xattribs.exists(XML_CHARSET_ATTRIBUTE)) { aXLSReader = new XLSReader(xattribs.getString(Node.XML_ID_ATTRIBUTE), xattribs.getString(XML_FILE_ATTRIBUTE), xattribs.getString(XML_CHARSET_ATTRIBUTE)); } else { aXLSReader = new XLSReader(xattribs.getString(Node.XML_ID_ATTRIBUTE), xattribs.getString(XML_FILE_ATTRIBUTE)); } aXLSReader.setPolicyType(xattribs.getString(XML_DATAPOLICY_ATTRIBUTE, null)); if (xattribs.exists(XML_STARTROW_ATTRIBUTE)){ aXLSReader.setStartRow(xattribs.getInteger(XML_STARTROW_ATTRIBUTE)); } if (xattribs.exists(XML_FINALROW_ATTRIBUTE)){ aXLSReader.setFinalRow(xattribs.getInteger(XML_FINALROW_ATTRIBUTE)); } if (xattribs.exists(XML_MAXERRORCOUNT_ATTRIBUTE)){ aXLSReader.setMaxErrorCount(xattribs.getInteger(XML_MAXERRORCOUNT_ATTRIBUTE)); } if (xattribs.exists(XML_SHEETNAME_ATTRIBUTE)){ aXLSReader.setSheetName(xattribs.getString(XML_SHEETNAME_ATTRIBUTE)); } } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } return aXLSReader; } public void setPolicyType(String strPolicyType) { setPolicyType(PolicyType.valueOfIgnoreCase(strPolicyType)); } public void setPolicyType(PolicyType policyType) { this.policyType = policyType; parser.setExceptionHandler(ParserExceptionHandlerFactory.getHandler(policyType)); } public int getStartRow() { return startRow; } /** * @param startRow The startRow to set. */ public void setStartRow(int startRecord) { if(startRecord < 0 || (finalRow != -1 && startRecord > finalRow)) { throw new InvalidParameterException("Invalid StartRecord parametr."); } this.startRow = startRecord; parser.setFirstRow(startRecord); } /** * @return Returns the finalRow. */ public int getFinalRow() { return finalRow; } /** * @param finalRow The finalRow to set. */ public void setFinalRow(int finalRecord) { if(finalRecord < 0 || (startRow != -1 && startRow > finalRecord)) { throw new InvalidParameterException("Invalid finalRow parameter."); } this.finalRow = finalRecord; } /** * @param finalRow The finalRow to set. */ public void setMaxErrorCount(int maxErrorCount) { if(maxErrorCount < 0) { throw new InvalidParameterException("Invalid maxErrorCount parameter."); } this.maxErrorCount = maxErrorCount; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public void init() throws ComponentNotReadyException { if (outPorts.size() < 1) { throw new ComponentNotReadyException(getId() + ": one output port can be defined!"); } try { if (sheetName!=null){ parser.setSheetName(sheetName); } parser.open(new FileInputStream(fileURL), getOutputPort(OUTPUT_PORT).getMetadata()); } catch (IOException ex) { throw new ComponentNotReadyException(getId() + "IOError: " + ex.getMessage()); } } private void setSheetName(String sheetName) { this.sheetName = sheetName; } }
package com.codeforces.commons.io; import com.codeforces.commons.collection.MapBuilder; import com.codeforces.commons.collection.SetBuilder; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; import java.util.Set; /** * @author Mike Mirzayanov */ public class MimeUtil { public static final String DEFAULT_MIME_TYPE = Type.TEXT_PLAIN; private static final Map<String, String> MIME_TYPE_BY_EXTENSION = new MapBuilder<String, String>() .put(".tif", Type.IMAGE_TIFF) .put(".tiff", Type.IMAGE_TIFF) .put(".gif", Type.IMAGE_GIF) .put(".png", Type.IMAGE_PNG) .put(".jpg", Type.IMAGE_JPEG) .put(".jpe", Type.IMAGE_JPEG) .put(".jpeg", Type.IMAGE_JPEG) .put(".bmp", Type.IMAGE_BMP) .put(".html", Type.TEXT_HTML) .put(".js", Type.APPLICATION_JAVASCRIPT) .put(".css", Type.TEXT_CSS) .put(".ps", Type.APPLICATION_POSTSCRIPT) .put(".xml", Type.APPLICATION_XML) .put(".json", Type.APPLICATION_JSON) .put(".dot", Type.APPLICATION_MSWORD) .put(".doc", Type.APPLICATION_MSWORD) .put(".docx", Type.APPLICATION_MSWORD) .put(".rtf", Type.APPLICATION_RTF) .put(".odt", "application/vnd.oasis.opendocument.text") .put(".pdf", Type.APPLICATION_PDF) .put(".tex", Type.APPLICATION_X_TEX) .put(".csv", "text/csv") .put(".mp", Type.TEXT_X_METAPOST) .put(".exe", Type.APPLICATION_OCTET_STREAM) .put(".dll", "application/x-msdownload") .put(".zip", Type.APPLICATION_ZIP) .put(".tar", "application/x-tar-compressed") .put(".rar", "application/x-rar-compressed") .put(".7z", Type.APPLICATION_X_7Z_COMPRESSED) .put(".jnlp", "application/x-java-jnlp-file") .put(".bat", "application/bat") .put(".sh", "application/x-sh") .put(".avi", Type.VIDEO_X_MSVIDEO) .put(".wmv", Type.VIDEO_X_MS_WMV) .put(".mov", Type.VIDEO_QUICKTIME) .put(".3gp", Type.VIDEO_3GPP) .put(".mp4", Type.VIDEO_MP4) .put(".flv", Type.VIDEO_FLV) .put(".mpeg", Type.VIDEO_MPEG) .put(".ogg", Type.VIDEO_OGG) .put(".webm", Type.VIDEO_WEBM) .buildUnmodifiable(); private MimeUtil() { throw new UnsupportedOperationException(); } @Nonnull public static String getContentTypeByFile(@Nonnull String fileName) { return getContentTypeByFile(fileName, DEFAULT_MIME_TYPE); } @Nullable public static String getContentTypeByFile(@Nonnull String fileName, @Nullable String defaultMimeType) { String mimeType = MIME_TYPE_BY_EXTENSION.get(FileUtil.getExt(fileName)); return mimeType == null ? defaultMimeType : mimeType; } public static boolean isKnownMimeType(@Nonnull String mimeType) { return KnownMimeTypesHolder.KNOWN_MIME_TYPES.contains(mimeType); } @Nonnull public static Set<String> getKnownMimeTypes() { return KnownMimeTypesHolder.KNOWN_MIME_TYPES; } private static final class KnownMimeTypesHolder { private static final Set<String> KNOWN_MIME_TYPES = new SetBuilder<String>() .addAll(MIME_TYPE_BY_EXTENSION.values()) .add(DEFAULT_MIME_TYPE) .buildUnmodifiable(); private KnownMimeTypesHolder() { throw new UnsupportedOperationException(); } } public static final class Type { public static final String TEXT_PLAIN = "text/plain"; public static final String TEXT_HTML = "text/html"; public static final String TEXT_CSS = "text/css"; public static final String TEXT_X_METAPOST = "text/x-metapost"; public static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; public static final String APPLICATION_XML = "application/xml"; public static final String APPLICATION_JSON = "application/json"; public static final String APPLICATION_JAVASCRIPT = "application/javascript"; public static final String APPLICATION_PDF = "application/pdf"; public static final String APPLICATION_POSTSCRIPT = "application/postscript"; public static final String APPLICATION_MSWORD = "application/msword"; public static final String APPLICATION_RTF = "application/rtf"; public static final String APPLICATION_X_TEX = "application/x-tex"; public static final String APPLICATION_ZIP = "application/zip"; public static final String APPLICATION_X_7Z_COMPRESSED = "application/x-7z-compressed"; public static final String APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; public static final String IMAGE_JPEG = "image/jpeg"; public static final String IMAGE_PNG = "image/png"; public static final String IMAGE_GIF = "image/gif"; public static final String IMAGE_TIFF = "image/tiff"; public static final String IMAGE_BMP = "image/bmp"; public static final String VIDEO_X_MSVIDEO = "video/x-msvideo"; public static final String VIDEO_AVI = "video/x-msvideo"; public static final String VIDEO_WMV = "video/x-ms-wmv"; public static final String VIDEO_X_MS_WMV = "video/x-ms-wmv"; public static final String VIDEO_MOV = "video/quicktime"; public static final String VIDEO_QUICKTIME = "video/quicktime"; public static final String VIDEO_3GP = "video/3gpp"; public static final String VIDEO_3GPP = "video/3gpp"; public static final String VIDEO_MP4 = "video/mp4"; public static final String VIDEO_FLV = "video/x-flv"; public static final String VIDEO_MPEG = "video/mpeg"; public static final String VIDEO_OGG = "video/ogg"; public static final String VIDEO_WEBM = "video/webm"; private Type() { throw new UnsupportedOperationException(); } } }
/** * This snippet multiplies 2 polynomials with possibly negative coefficients very efficiently using * the Fast Fourier Transform. NOTE: This code only works for polynomials with coefficients in the * range of a signed integer. * * <p>Time Complexity: O( nlogn ) * * @author David Brink */ package com.williamfiset.algorithms.math; public class FastFourierTransform { // p is a prime number set to be larger than 2^31-1 private static long p = 4300210177L; // q is 2^64 mod p used to compute x*y mod p // Note: If x*y mod p is negative it is because 2^64 // has been subtracted and so it must be added again. private static long q = 857728777; // A number that has order 2^20 modulo p private static long zeta = 3273; private static int exp = 20; private static long[] powers; static { powers = new long[(1 << exp) + 1]; powers[0] = 1; for (int i = 1; i < powers.length; i++) powers[i] = mult(zeta, powers[i - 1]); } // Computes the polynomial product modulo p public static long[] multiply(long[] x, long[] y) { // If the coefficients are negative place them in the range of [0, p) for (int i = 0; i < x.length; i++) if (x[i] < 0) x[i] += p; for (int i = 0; i < y.length; i++) if (y[i] < 0) y[i] += p; int zLength = x.length + y.length - 1; int logN = 32 - Integer.numberOfLeadingZeros(zLength - 1); long[] xx = transform(x, logN, false); long[] yy = transform(y, logN, false); long[] zz = new long[1 << logN]; for (int i = 0; i < zz.length; i++) zz[i] = mult(xx[i], yy[i]); long[] nZ = transform(zz, logN, true); long[] z = new long[zLength]; long nInverse = p - ((p - 1) >>> logN); for (int i = 0; i < z.length; i++) { z[i] = mult(nInverse, nZ[i]); // Allow for negative coefficients. If you know the answer cannot be // greater than 2^31-1 subtract p to obtain the negative coefficient. if (z[i] >= Integer.MAX_VALUE) z[i] -= p; } return z; } private static long mult(long x, long y) { long z = x * y; if (z < 0) { z = z % p + q; return z < 0 ? z + p : z; } if (z < (1L << 56) && x > (1 << 28) && y > (1 << 28)) { z = z % p + q; return z < p ? z : z - p; } return z % p; } private static long[] transform(long[] v, int logN, boolean inverse) { int n = 1 << logN; long[] w = new long[n]; for (int i = 0; i < v.length; i++) w[Integer.reverse(i) >>> 32 - logN] = v[i]; for (int i = 0; i < logN; i++) { int jMax = 1 << i; int kStep = 2 << i; int index = 0; int step = 1 << exp - i - 1; if (inverse) { index = 1 << exp; step = -step; } for (int j = 0; j < jMax; j++) { long zeta = powers[index]; index += step; for (int k = j; k < n; k += kStep) { int kk = jMax | k; long x = w[k]; long y = mult(zeta, w[kk]); long z = x + y; w[k] = z < p ? z : z - p; z = x - y; w[kk] = z < 0 ? z + p : z; } } } return w; } /* Example usage */ public static void main(String[] args) { // 1*x^0 + 5*x^1 + 3*x^2 + 2*x^3 long[] polynomial1 = {1, 5, 3, 2}; // 0*x^0 + 0*x^1 + 6*x^2 + 2*x^3 + 5*x^4 long[] polynomial2 = {0, 0, 6, 2, 5}; // Multiply the polynomials using the FFT algorithm long[] result = FastFourierTransform.multiply(polynomial1, polynomial2); // Prints [0, 0, 6, 32, 33, 43, 19, 10] or equivalently // 6*x^2 + 32*x^3 + 33*x^4 + 43*x^5 + 19*x^6 + 10*x^7 System.out.println(java.util.Arrays.toString(result)); } }
package to.etc.util; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.net.URL; import java.net.URLClassLoader; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; final public class ClassUtil { private ClassUtil() { } /** * Calls the given method with the given parameters in a given class instance. Used to access * classes whose definition are not to be linked to the code. * * @throws NoSuchMethodException if no suitable method can be found in the object. */ @Nullable static public Object callMethod(@NonNull final Object on, @NonNull final String name, @NonNull final Object... param) throws Exception { Method m = findMethod(on.getClass(), name, param); if(m == null) throw new NoSuchMethodException("A suitable method " + name + " cannot be found"); try { return m.invoke(on, param); } catch(InvocationTargetException itx) { if(itx.getCause() instanceof Exception) throw (Exception) itx.getCause(); throw itx; } } /** * Calls the given method with the given parameters in a given class instance. Used to access * classes whose definition are not to be linked to the code. * * @throws NoSuchMethodException if no suitable method can be found in the object. */ @Nullable static public Object callMethod(@NonNull final Object on, @NonNull final String name, @NonNull Class[] formals, @NonNull final Object... instances) throws Exception { Method m = findMethod(on.getClass(), name, formals); if(m == null) throw new NoSuchMethodException("A suitable method " + name + " cannot be found"); try { return m.invoke(on, instances); } catch(InvocationTargetException itx) { if(itx.getCause() instanceof Exception) throw (Exception) itx.getCause(); throw itx; } } @Nullable static public Method findMethod(@NonNull final Class< ? > clz, @NonNull final String name, @NonNull final Class< ? >... param) { try { return clz.getMethod(name, param); } catch(Exception x) { } try { return clz.getDeclaredMethod(name, param); } catch(Exception x) { return null; } } /** * Tries to find a method that can be called using the specified parameters. */ @Nullable static public Method findMethod(@NonNull final Class< ? > clz, @NonNull final String name, @NonNull final Object... param) { boolean hard = false; Class< ? >[] par = new Class< ? >[param.length]; for(int i = param.length; --i >= 0;) { Object v = param[i]; if(v == null) { hard = true; par[i] = null; } else { par[i] = v.getClass(); } } //-- If not hard get method by types if(!hard) return findMethod(clz, name, par); //-- Find the best fit Method[] mar = clz.getMethods(); Method res = null; for(Method m : mar) { if(!m.getName().equals(name)) continue; Class< ? >[] far = m.getParameterTypes(); if(far.length != par.length) continue; boolean ok = true; for(int j = far.length; --j >= 0;) { if(!far[j].isAssignableFrom(par[j])) { ok = false; break; } } if(!ok) continue; //-- This is a candidate - if(res != null) throw new IllegalStateException("Ambiguous method to call: " + res + " or " + m); res = m; } return res; } private static class Info { public Info() { } public boolean isPrivate; public Method getter; public List<Method> setterList = new ArrayList<Method>(); } static private final Map<Class< ? >, ClassInfo> m_classMap = new HashMap<Class< ? >, ClassInfo>(); /** * Get introspected bean information for the class. This info is cached so access will be fast after the 1st try. */ @NonNull static synchronized public ClassInfo getClassInfo(@NonNull Class< ? > clz) { ClassInfo ci = m_classMap.get(clz); if(ci == null) { List<PropertyInfo> proplist = calculateProperties(clz); ci = new ClassInfo(clz, proplist); m_classMap.put(clz, ci); } return ci; } @Nullable static public PropertyInfo findPropertyInfo(@NonNull Class< ? > clz, @NonNull String property) { return getClassInfo(clz).findProperty(property); } @NonNull static public List<PropertyInfo> getProperties(@NonNull final Class< ? > cl) { ClassInfo ci = getClassInfo(cl); return ci.getProperties(); } /** * DO NOT USE - uncached calculation of a class's properties. * @param cl * @return */ @NonNull static public List<PropertyInfo> calculateProperties(@NonNull final Class< ? > cl) { return calculateProperties(cl, true); } /** * DO NOT USE - uncached calculation of a class's properties. */ @NonNull static public List<PropertyInfo> calculateProperties(@NonNull final Class< ? > cl, boolean publicOnly) { Map<String, Info> map = new HashMap<String, Info>(); //-- First handle private properties if(! publicOnly) { for(Method m : cl.getDeclaredMethods()) { checkPropertyMethod(map, m, publicOnly); } } //-- And let those be overridden by public ones for(Method m : cl.getMethods()) { checkPropertyMethod(map, m, publicOnly); } //-- Construct actual list List<PropertyInfo> res = new ArrayList<PropertyInfo>(); for(String name : map.keySet()) { Info i = map.get(name); if(i.getter == null) continue; Method setter = null; for(Method m : i.setterList) { if(m.getParameterTypes()[0] == i.getter.getReturnType()) { setter = m; break; } } // if(setter == null) jal 20100205 read-only properties should be allowed explicitly. // continue; Class<?> resolvedPropertyType = findGenericGetterType(cl, i.getter); if(resolvedPropertyType == null) resolvedPropertyType = i.getter.getReturnType(); res.add(new PropertyInfo(name, i.getter, setter, resolvedPropertyType)); } return res; } private static void checkPropertyMethod(Map<String, Info> map, Method m, boolean publicOnly) { //-- Check if this is a valid getter, int mod = m.getModifiers(); if(Modifier.isStatic(mod) || (publicOnly && !Modifier.isPublic(mod)) ) return; String name = m.getName(); boolean setter = false; StringBuilder sb = new StringBuilder(40); if(name.startsWith("get")) { sb.append(name, 3, name.length()); } else if(name.startsWith("is")) { sb.append(name, 2, name.length()); } else if(name.startsWith("set")) { sb.append(name, 3, name.length()); setter = true; } else return; if(sb.length() == 0) // just "is", "get" or "set". return; //-- Check parameters Class< ? >[] param = m.getParameterTypes(); if(setter) { if(param.length != 1) return; } else { if(param.length != 0) return; } //-- Construct name. if(sb.length() == 1) sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); else { if(!Character.isUpperCase(sb.charAt(1))) { sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); } } boolean pvt = Modifier.isPrivate(mod); name = sb.toString(); Info i = map.get(name); if(i == null) { i = new Info(); map.put(name, i); } //-- Private rules: a property is private only if the getter is private. if(pvt) { if(! setter) { i.isPrivate = true; } } else if(i.isPrivate && ! setter) { i.isPrivate = false; //i.getter = null; //i.setterList.clear(); } if(setter) i.setterList.add(m); else { //-- The stupid generics impl will generate Object-returning property methods also, but we need the actual typed one.. if(i.getter == null) i.getter = m; else { if(i.getter.getReturnType().isAssignableFrom(m.getReturnType())) i.getter = m; } } } @NonNull static public String getMethodName(@NonNull String prefix, @NonNull String property) { StringBuilder sb = new StringBuilder(); sb.append(prefix); if(property.length() > 0) { sb.append(Character.toUpperCase(property.charAt(0))); sb.append(property, 1, property.length()); } return sb.toString(); } /** * Generic caller of a method using reflection. This prevents us from having * to link to the stupid Oracle driver. */ @Nullable static public Object callObjectMethod(@NonNull final Object src, @NonNull final String name, @NonNull final Class< ? >[] types, @NonNull final Object... parameters) throws SQLException { try { Method m = src.getClass().getMethod(name, types); return m.invoke(src, parameters); } catch(InvocationTargetException itx) { if(itx.getCause() instanceof SQLException) throw (SQLException) itx.getCause(); throw new RuntimeException(itx.getCause().toString(), itx.getCause()); } catch(Exception x) { throw new RuntimeException("Exception calling " + name + " on " + src + ": " + x, x); } } static public final Class< ? > loadClass(final ClassLoader cl, final String cname) { try { return cl.loadClass(cname); } catch(Exception x) {} return null; } @NonNull static public final <T> T loadInstance(@NonNull final ClassLoader cl, @NonNull Class<T> clz, @NonNull final String className) throws Exception { Class< ? > acl; try { acl = cl.loadClass(className); } catch(Exception x) { throw new RuntimeException("The class " + className + " cannot be found/loaded: " + x); } if(!clz.isAssignableFrom(acl)) throw new IllegalArgumentException("The class " + className + " is not a/does not implement " + clz.getName()); try { return (T) acl.newInstance(); } catch(Exception x) { throw new RuntimeException("Cannot instantiate " + acl + ": " + x); } } /** * Locates an annotation in an array of 'm, returns null if not found. */ @Nullable static public <T extends Annotation> T findAnnotation(@NonNull final Annotation[] ar, @NonNull final Class<T> clz) { for(Annotation a : ar) { if(a.annotationType() == clz) return (T) a; } return null; } static public void propertyNameToJava(@NonNull StringBuilder sb, @NonNull String in) { if(in.length() == 0) return; int len = sb.length(); sb.append(in); sb.setCharAt(len, Character.toUpperCase(sb.charAt(len))); } @NonNull static public String propertyNameToJava(@NonNull String in) { StringBuilder sb = new StringBuilder(); propertyNameToJava(sb, in); return sb.toString(); } /** * This tries to determine the value class for a property defined as some kind * of Collection&lt;T&gt; or T[]. If the type cannot be determined this returns * null. */ @Nullable static public Class< ? > findCollectionType(@NonNull Type genericType) { if(genericType instanceof Class< ? >) { Class< ? > cl = (Class< ? >) genericType; if(cl.isArray()) { return cl.getComponentType(); } } if(genericType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericType; Type raw = pt.getRawType(); //-- This must be a collection type of class. if(raw instanceof Class< ? >) { Class< ? > cl = (Class< ? >) raw; if(Collection.class.isAssignableFrom(cl)) { Type[] tar = pt.getActualTypeArguments(); if(tar != null && tar.length == 1) { // Collection<T> required return (Class< ? >) tar[0]; } } } } return null; } static public boolean isCollectionOrArrayType(@NonNull Class< ? > clz) { return clz.isArray() || Collection.class.isAssignableFrom(clz); } /* * Walk the class hierarchy and create a list that goes from base class to derived class. This includes both classes * and interfaces, where interfaces have "multiple bases". */ @NonNull static public List<Class< ? >> getClassHierarchy(@NonNull Class< ? > clzin) { List<Class< ? >> res = new ArrayList<Class< ? >>(); appendClassHierarchy(res, clzin); return res; } static public void appendClassHierarchy(@NonNull List<Class< ? >> res, @NonNull Class< ? > clzin) { if(res.contains(clzin)) return; //-- If this class has a superclass (it is not an interface and not Object) then add that 1st Class< ? > sclz = clzin.getSuperclass(); if(null != sclz) { appendClassHierarchy(res, sclz); // First add parts upside the hierarchy. } //-- Get all implemented interfaces as bases and add them 1st also Class< ? >[] ifar = clzin.getInterfaces(); for(Class< ? > iclz : ifar) { appendClassHierarchy(res, iclz); } if(res.contains(clzin)) return; res.add(clzin); } /** * Scan the classloader hierarchy and find all urls. */ @NonNull static public URL[] findUrlsFor(@NonNull ClassLoader loader) { List<URL> res = new ArrayList<URL>(); findUrlsFor(res, loader); return res.toArray(new URL[res.size()]); } /** * Checks to see what kind of classloader this is, and add all paths to my list. */ static private void findUrlsFor(@NonNull List<URL> result, @Nullable ClassLoader loader) { // System.out.println(".. loader="+loader); if(loader == null) return; if(loader instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader) loader; for(URL u : ucl.getURLs()) { result.add(u); } } ClassLoader parent = loader.getParent(); if(null != parent) findUrlsFor(result, parent); } @Nullable public static <T> Constructor<T> findConstructor(@NonNull Class<T> clz, @NonNull Class< ? >... formals) { try { return clz.getConstructor(formals); } catch(Exception x) { return null; } } public static <T> T callConstructor(Class<T> clz, Class< ? >[] formals, Object... args) throws Exception { Constructor<T> c = findConstructor(clz, formals); if(c == null) throw new IllegalStateException("Cannot find constructor in " + clz + " with args " + Arrays.toString(formals)); return c.newInstance(args); } /** * Finds sources for classes in the same project. Not meant for jar searching */ public static @Nullable File findSrcForModification(@NonNull String className) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final String rel = className.replace(".", "/") + ".class"; URL resource = classLoader.getResource(rel); if(resource == null) { return null; } final String path = resource.getFile(); if(resource.getProtocol().equals("jar")) { throw new Exception("Finding sources in jars for modifications is not supported."); } String srcRel = rel.substring(0, rel.length() - 5) + "java"; File root = new File(path.substring(0, path.length() - rel.length())); File[] files = new File[1]; find(root.getParentFile(), srcRel, files); return files[0]; } /** * Finds source folder for package in the same project. Not meant for jar searching */ public static @Nullable File findSrcFolderForModification(@NonNull String packageName) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final String rel = packageName.replace(".", "/"); URL resource = classLoader.getResource(rel); if(resource == null) { return null; } final String path = resource.getFile(); if(resource.getProtocol().equals("jar")) { throw new Exception("Finding sources in jars for modifications is not supported."); } File root = new File(path.substring(0, path.length() - rel.length())); File[] files = new File[1]; find(root.getParentFile(), rel, files); return files[0]; } /** * Searches for a file in a root recursively upwards and one level down every time. */ private static void find(@Nullable File root, @NonNull String srcRel, @NonNull File[] files) { if(root == null) { return; } File[] listFiles = root.listFiles(); if(listFiles != null) { for(int i = 0; i < listFiles.length; i++) { File child = listFiles[i]; File src = new File(child, srcRel); if(src.exists()) { files[0] = src; return; } } } find(root.getParentFile(), srcRel, files); } /** * Retrieves a value from an object using introspection. The name is the direct * name of a method that *must* exist; it does not add a "get". If the method * does not exist this throws an exception. */ static public final Object getClassValue(@NonNull final Object inst, @NonNull final String name) throws Exception { if(inst == null) throw new IllegalStateException("The input object is null"); Class< ? > clz = inst.getClass(); Method m; try { m = clz.getMethod(name); } catch(NoSuchMethodException x) { throw new IllegalStateException("Unknown method '" + name + "()' on class=" + clz); } try { return m.invoke(inst); } catch(IllegalAccessException iax) { throw new IllegalStateException("Cannot call method '" + name + "()' on class=" + clz + ": " + iax); } catch(InvocationTargetException itx) { Throwable c = itx.getCause(); if(c instanceof Exception) throw (Exception) c; else if(c instanceof Error) throw (Error) c; else throw itx; } } /** * Since annotations are not inherited, we do the extends search on super classed in order to be able to work also with annotations on inherited properties. */ @Nullable public static <T extends Annotation> T findAnnotationIncludingSuperClasses(@NonNull Method annotatedMethod, @NonNull Class<T> annotationType) { T annotation = annotatedMethod.getAnnotation(annotationType); if(annotation != null) { return annotation; } Class< ? > parent = annotatedMethod.getDeclaringClass().getSuperclass(); if(parent != null) { Method superMethod; try { superMethod = parent.getDeclaredMethod(annotatedMethod.getName()); if(superMethod != null) { return findAnnotationIncludingSuperClasses(superMethod, annotationType); } } catch(NoSuchMethodException | SecurityException e) { // no method } } return null; } /** * Get all annotations of a given type on a method or its base methods. */ @NonNull static public <T extends Annotation> List<T> getMethodAnnotations(Method m, Class<T> annotationType) { List<Class<?>> hierarchy = getClassHierarchy(m.getDeclaringClass()); // Full class hierarchy including interfaces List<T> result = new ArrayList<>(); for(Class<?> clz : hierarchy) { Method macc = findMethodInClass(m, clz); if(macc != null) addAnnotationIf(result, annotationType, macc); } return result; } @Nullable private static Method findMethodInClass(Method m, Class<?> clz) { Method macc; if(clz == m.getDeclaringClass()) { macc = m; } else { try { macc = clz.getDeclaredMethod(m.getName(), m.getParameterTypes()); } catch(NoSuchMethodException | SecurityException x) { macc = null; } } return macc; } @Nullable static public <T extends Annotation> T getMethodAnnotation(Method m, Class<T> annotationType) { T annotation = m.getAnnotation(annotationType); if(null != annotation) return annotation; List<Class<?>> hierarchy = getClassHierarchy(m.getDeclaringClass()); // Full class hierarchy including interfaces for(Class<?> clz : hierarchy) { Method macc = findMethodInClass(m, clz); if(macc != null) { annotation = macc.getAnnotation(annotationType); if(null != annotation) return annotation; } } return null; } static private <T extends Annotation> void addAnnotationIf(List<T> list, Class<T> annotationType, Method m) { T annotation = m.getAnnotation(annotationType); if(null != annotation) list.add(annotation); } static public <T extends Annotation> T getClassAnnotation(Class<?> clzIn, Class<T> annotationType) { List<Class<?>> hierarchy = getClassHierarchy(clzIn); // Full class hierarchy including interfaces for(Class<?> clz : hierarchy) { T annotation = clz.getAnnotation(annotationType); if(null != annotation) return annotation; } return null; } @NonNull public static List<Field> getAllFields(@NonNull Class<?> clz) { List<Field> all = new ArrayList<>(); calculateAllFields(all, clz); return all; } private static void calculateAllFields(List<Field> all, Class<?> clz) { for(Field declaredField : clz.getDeclaredFields()) { all.add(declaredField); } if(clz.getSuperclass() != Object.class) { calculateAllFields(all, clz.getSuperclass()); } } /* CODING: Generics resolution methods. */ @Nullable public static Class<?> findGenericGetterType(Class<?> instanceClass, Method getter) { Type grt = getter.getGenericReturnType(); if(grt instanceof Class) { return (Class<?>) grt; } //-- If it is a method type parameter then we don't know the type. for(TypeVariable<Method> typeParameter : getter.getTypeParameters()) { if(typeParameter.toString().equals(grt.toString())) { return null; } } var dcl = findSubClassParameterType(instanceClass, getter.getDeclaringClass(), grt); return dcl; } @Nullable public static Class<?> findSubClassParameterType(Class<?> instanceClass, Class<?> classOfInterest, Type valueType) { Map<Type, Type> typeMap = new HashMap<Type, Type>(); do { extractTypeArguments(typeMap, instanceClass); instanceClass = instanceClass.getSuperclass(); if(instanceClass == null) return null; // Subclass containing classOfInterest not found } while(classOfInterest != instanceClass); //ParameterizedType parameterizedType = (ParameterizedType) instanceClass.getGenericSuperclass(); Type actualType = valueType; if(typeMap.containsKey(actualType)) { actualType = typeMap.get(actualType); } if(actualType instanceof Class) { return (Class<?>) actualType; } return null; } /** * Creates a map of (formal, actual) types for a class. The actual can also be a type name (like T). */ private static void extractTypeArguments(Map <Type, Type> typeMap, Class <?> clazz) { Type genericSuperclass = clazz.getGenericSuperclass(); if(!(genericSuperclass instanceof ParameterizedType)) { return; } ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; Type[] typeParameter = ((Class<?>) parameterizedType.getRawType()).getTypeParameters(); Type[] actualTypeArgument = parameterizedType.getActualTypeArguments(); for(int i = 0; i < typeParameter.length; i++) { if(typeMap.containsKey(actualTypeArgument[i])) { actualTypeArgument[i] = typeMap.get(actualTypeArgument[i]); } typeMap.put(typeParameter[i], actualTypeArgument[i]); } } /** * Only works when the option * <pre> * --add-opens java.base/jdk.internal.loader=ALL-UNNAMED * </pre> * * is added to the runtime, because the idiots defining Java 9 could not * get it into their tiny brain that there are legitimate reasons to * want to know the jars that build the classpath - despite their * horror of a module system. */ static public List<URL> findClassloaderURLs_JAVA11_ONLYWITHOPTION(Class<?> root) { ClassLoader cl = root.getClassLoader(); List<URL> res = new ArrayList<>(); collectUrls(res, cl); for(URL re : res) { System.out.println(re.toString()); } return res; } static private void collectUrls(List<URL> res, ClassLoader cl) { try { Field ucp = cl.getClass().getDeclaredField("ucp"); // Fuck the morons that fucked this up ucp.setAccessible(true); Object path = ucp.get(cl); // Also hidden. Fuck them again. Field listField = path.getClass().getDeclaredField("path"); listField.setAccessible(true); List<URL> list = (List<URL>) listField.get(path); res.addAll(list); } catch(Exception x) { x.printStackTrace(); } ClassLoader parent = cl.getParent(); if(parent == null || parent == cl) return; collectUrls(res, parent); } }
// MIASReader.java package loci.formats.in; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.Vector; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.formats.CoreMetadata; import loci.formats.FilePattern; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.in.MinimalTiffReader; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; import loci.formats.tiff.IFD; import loci.formats.tiff.TiffParser; public class MIASReader extends FormatReader { // -- Fields -- /** TIFF files - indexed by well and file. */ private String[][] tiffs; /** Delegate readers. */ private MinimalTiffReader[][] readers; /** Path to file containing analysis results for all plates. */ private String resultFile = null; private Vector<AnalysisFile> analysisFiles; private int[] wellNumber; private int tileRows, tileCols; private int tileWidth, tileHeight; private int wellColumns; private int[] bpp; private String templateFile; /** Cached tile buffer to avoid re-allocations when reading tiles. */ private byte[] cachedTileBuffer; // -- Constructor -- /** Constructs a new MIAS reader. */ public MIASReader() { super("MIAS", new String[] {"tif", "tiff"}); suffixSufficient = false; domains = new String[] {FormatTools.HCS_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return false; } /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String filename, boolean open) { if (!open) return super.isThisType(filename, open); // no file system access Location baseFile = new Location(filename).getAbsoluteFile(); Location wellDir = baseFile.getParentFile(); Location experiment = null; try { experiment = wellDir.getParentFile().getParentFile(); } catch (NullPointerException e) { } if (experiment == null) return false; String wellName = wellDir.getName(); boolean validName = wellName.startsWith("Well") || wellName.equals("results") || (wellName.length() == 1 && wellName.replaceAll("\\d", "").length() == 0); return validName && super.isThisType(filename, open); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; Object s = ifd.getIFDValue(IFD.SOFTWARE); if (s == null) return false; String software = null; if (s instanceof String[]) software = ((String[]) s)[0]; else software = s.toString(); return software.startsWith("eaZYX") || software.startsWith("SCIL_Image") || software.startsWith("IDL"); } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (readers == null || readers[0][0].getCurrentFile() == null) { return null; } return readers[0][0].get8BitLookupTable(); } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (readers == null || readers[0][0].getCurrentFile() == null) { return null; } return readers[0][0].get16BitLookupTable(); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (tileRows == 1 && tileCols == 1) { readers[getSeries()][no].setId(tiffs[getSeries()][no]); readers[getSeries()][no].openBytes(0, buf, x, y, w, h); return buf; } int outputRowLen = w * bpp[getSeries()]; Region image = new Region(x, y, w, h); int outputRow = 0, outputCol = 0; Region intersection = null; byte[] tileBuf = null; for (int row=0; row<tileRows; row++) { for (int col=0; col<tileCols; col++) { Region tile = new Region(col * tileWidth, row * tileHeight, tileWidth, tileHeight); if (!tile.intersects(image)) continue; intersection = tile.intersection(image); int tileIndex = (no * tileRows + row) * tileCols + col; tileBuf = getTile(getSeries(), no, row, col, intersection); int rowLen = tileBuf.length / intersection.height; // copy tile into output image int outputOffset = outputRow * outputRowLen + outputCol; for (int trow=0; trow<intersection.height; trow++) { System.arraycopy(tileBuf, trow * rowLen, buf, outputOffset, rowLen); outputOffset += outputRowLen; } outputCol += rowLen; } if (intersection != null) { outputRow += intersection.height; outputCol = 0; } } return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); Vector<String> files = new Vector<String>(); if (!noPixels) { files.addAll(Arrays.asList(tiffs[getSeries()])); } for (AnalysisFile file : analysisFiles) { if (file.plate <= 0 && (file.well == getSeries() || file.well < 0 || wellNumber[getSeries()] == file.well)) { files.add(file.filename); } } if (templateFile != null) files.add(templateFile); return files.toArray(new String[files.size()]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (readers != null) { for (MinimalTiffReader[] images : readers) { for (MinimalTiffReader r : images) { if (r != null) r.close(fileOnly); } } } if (!fileOnly) { readers = null; tiffs = null; tileRows = tileCols = 0; resultFile = null; analysisFiles = null; wellNumber = null; tileWidth = tileHeight = 0; wellColumns = 0; bpp = null; cachedTileBuffer = null; templateFile = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("MIASReader.initFile(" + id + ")"); super.initFile(id); analysisFiles = new Vector<AnalysisFile>(); // MIAS is a high content screening format which supports multiple plates, // wells and fields. // Most of the metadata comes from the directory hierarchy, as very little // metadata is present in the actual files. // The directory hierarchy is either: // <experiment name> top level experiment directory // Batchresults analysis results for experiment // <plate number>_<plate barcode> one directory for each plate // results analysis results for plate // Well<xxxx> one directory for each well // mode<x>_z<xxx>_t<xxx>_im<x>_<x>.tif // <experiment name> top level experiment directory // <plate number> plate directory (3 digits) // <well number> well directory (4 digits) // <channel number> channel directory (1 digit) // <tile row>_<tile col>_<Z>_<T>.tif // Each TIFF file contains a single grayscale plane. The "mode" block // refers to the channel number; the "z" and "t" blocks refer to the // Z section and timepoint, respectively. The "im<x>_<x>" block gives // the row and column coordinates of the image within a mosaic. // We are initially given one of these TIFF files; from there, we need // to find the top level experiment directory and work our way down to // determine how many plates and wells are present. status("Building list of TIFF files"); Location baseFile = new Location(id).getAbsoluteFile(); Location plate = baseFile.getParentFile().getParentFile(); String plateName = plate.getName(); if (!(plateName.length() == 3 || (plateName.length() > 3 && plateName.replaceAll("\\d", "").startsWith("-")))) { plate = plate.getParentFile(); plateName = plate.getName(); } int plateNumber = Integer.parseInt(plateName.substring(0, 3)); Location experiment = plate.getParentFile(); String[] directories = experiment.list(true); Arrays.sort(directories); for (String dir : directories) { Location f = new Location(experiment, dir); if (dir.equals("Batchresults")) { String[] results = f.list(true); for (String result : results) { Location file = new Location(f, result); if (result.startsWith("NEO_Results")) { resultFile = file.getAbsolutePath(); AnalysisFile af = new AnalysisFile(); af.filename = resultFile; analysisFiles.add(af); } else if (result.startsWith("NEO_PlateOutput_")) { int plateIndex = Integer.parseInt(result.substring(16, 19)); if (plateIndex == plateNumber) { AnalysisFile af = new AnalysisFile(); af.filename = file.getAbsolutePath(); af.plate = 0; analysisFiles.add(af); } } } } } String[] list = plate.list(true); Arrays.sort(list); Vector<String> wellDirectories = new Vector<String>(); for (String dir : list) { Location f = new Location(plate, dir); if (f.getName().startsWith("Well") || f.getName().length() == 4) { // directory name is valid, but we need to make sure that the // directory contains a TIFF or a subdirectory String[] wellList = f.list(true); if (wellList != null) { boolean validWell = false; for (String potentialTIFF : wellList) { if (potentialTIFF.toLowerCase().endsWith(".tif") || new Location(f, potentialTIFF).isDirectory()) { validWell = true; break; } } if (validWell) wellDirectories.add(f.getAbsolutePath()); } } else if (f.getName().equals("results")) { String[] resultsList = f.list(true); for (String result : resultsList) { if (!result.endsWith(".sav") && !result.endsWith(".dsv")) { Location r = new Location(f, result); AnalysisFile af = new AnalysisFile(); af.filename = r.getAbsolutePath(); af.plate = 0; if (result.toLowerCase().startsWith("well")) { af.well = Integer.parseInt(result.substring(4, 8)) - 1; } analysisFiles.add(af); } } } else if (f.getName().equals("Nugenesistemplate.txt")) { templateFile = f.getAbsolutePath(); } } int nWells = wellDirectories.size(); debug("Found " + nWells + " wells."); readers = new MinimalTiffReader[nWells][]; tiffs = new String[nWells][]; int[] zCount = new int[nWells]; int[] cCount = new int[nWells]; int[] tCount = new int[nWells]; String[] order = new String[nWells]; wellNumber = new int[nWells]; String[] wells = wellDirectories.toArray(new String[nWells]); Arrays.sort(wells); for (int j=0; j<nWells; j++) { Location well = new Location(wells[j]); String wellName = well.getName().replaceAll("Well", ""); wellNumber[j] = Integer.parseInt(wellName) - 1; String[] tiffFiles = well.list(true); Vector<String> tmpFiles = new Vector<String>(); for (String tiff : tiffFiles) { String name = tiff.toLowerCase(); if (name.endsWith(".tif") || name.endsWith(".tiff")) { tmpFiles.add(new Location(well, tiff).getAbsolutePath()); } } if (tmpFiles.size() == 0) { debug("No TIFFs in well directory " + wells[j]); // no TIFFs in the well directory, so there are probably channel // directories which contain the TIFFs for (String dir : tiffFiles) { Location file = new Location(well, dir); if (dir.length() == 1 && file.isDirectory()) { cCount[j]++; String[] tiffs = file.list(true); for (String tiff : tiffs) { String name = tiff.toLowerCase(); if (name.endsWith(".tif") || name.endsWith(".tiff")) { tmpFiles.add(new Location(file, tiff).getAbsolutePath()); } } } } } tiffFiles = tmpFiles.toArray(new String[0]); Location firstTiff = new Location(tiffFiles[0]); FilePattern fp = new FilePattern( firstTiff.getName(), firstTiff.getParentFile().getAbsolutePath()); String[] blocks = fp.getPrefixes(); BigInteger[] firstNumber = fp.getFirst(); BigInteger[] lastNumber = fp.getLast(); BigInteger[] step = fp.getStep(); order[j] = "XY"; for (int block=blocks.length - 1; block>=0; block blocks[block] = blocks[block].toLowerCase(); blocks[block] = blocks[block].substring(blocks[block].lastIndexOf("_") + 1); BigInteger tmp = lastNumber[block].subtract(firstNumber[block]); tmp = tmp.add(BigInteger.ONE).divide(step[block]); int count = tmp.intValue(); if (blocks[block].equals("z")) { zCount[j] = count; order[j] += "Z"; } else if (blocks[block].equals("t")) { tCount[j] = count; order[j] += "T"; } else if (blocks[block].equals("mode")) { cCount[j] = count; order[j] += "C"; } else if (blocks[block].equals("im")) tileRows = count; else if (blocks[block].equals("")) tileCols = count; else if (blocks[block].replaceAll("\\d", "").length() == 0) { if (block == 3) tileRows = count; else if (block == 2) tileCols = count; else if (block == 1) { zCount[j] = count; order[j] += "Z"; } else if (block == 0) { tCount[j] = count; order[j] += "T"; } } else { throw new FormatException("Unsupported block '" + blocks[block]); } } Arrays.sort(tiffFiles); tiffs[j] = tiffFiles; debug("Well " + j + " has " + tiffFiles.length + " files."); readers[j] = new MinimalTiffReader[tiffFiles.length]; for (int k=0; k<tiffFiles.length; k++) { readers[j][k] = new MinimalTiffReader(); } } // Populate core metadata status("Populating core metadata"); int nSeries = tiffs.length; core = new CoreMetadata[nSeries]; bpp = new int[nSeries]; if (readers.length == 0) { throw new FormatException("No wells were found."); } // assume that all wells have the same width, height, and pixel type readers[0][0].setId(tiffs[0][0]); tileWidth = readers[0][0].getSizeX(); tileHeight = readers[0][0].getSizeY(); if (tileCols == 0) tileCols = 1; if (tileRows == 0) tileRows = 1; for (int i=0; i<core.length; i++) { core[i] = new CoreMetadata(); core[i].sizeZ = zCount[i]; core[i].sizeC = cCount[i]; core[i].sizeT = tCount[i]; if (core[i].sizeZ == 0) core[i].sizeZ = 1; if (core[i].sizeC == 0) core[i].sizeC = 1; if (core[i].sizeT == 0) core[i].sizeT = 1; core[i].sizeX = tileWidth * tileCols; core[i].sizeY = tileHeight * tileRows; core[i].pixelType = readers[0][0].getPixelType(); core[i].sizeC *= readers[0][0].getSizeC(); core[i].rgb = readers[0][0].isRGB(); core[i].littleEndian = readers[0][0].isLittleEndian(); core[i].interleaved = readers[0][0].isInterleaved(); core[i].indexed = readers[0][0].isIndexed(); core[i].falseColor = readers[0][0].isFalseColor(); core[i].dimensionOrder = order[i]; if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } core[i].imageCount = core[i].sizeZ * core[i].sizeT * cCount[i]; if (core[i].imageCount == 0) { core[i].imageCount = 1; } bpp[i] = FormatTools.getBytesPerPixel(core[i].pixelType); } // Populate metadata hashtable status("Populating metadata hashtable"); if (resultFile != null && isMetadataCollected()) { String[] cols = null; Vector<String> rows = new Vector<String>(); boolean doKeyValue = true; int nStarLines = 0; String analysisResults = DataTools.readFile(resultFile); String[] lines = analysisResults.split("\n"); for (String line : lines) { line = line.trim(); if (line.length() == 0) continue; if (line.startsWith("******") && line.endsWith("******")) nStarLines++; if (doKeyValue) { String[] n = line.split("\t"); if (n[0].endsWith(":")) n[0] = n[0].substring(0, n[0].length() - 1); if (n.length >= 2) addGlobalMeta(n[0], n[1]); } else { if (cols == null) cols = line.split("\t"); else rows.add(line); } if (nStarLines == 2) doKeyValue = false; } for (String row : rows) { String[] d = row.split("\t"); for (int col=3; col<cols.length; col++) { addGlobalMeta("Plate " + d[0] + ", Well " + d[2] + " " + cols[col], d[col]); if (cols[col].equals("AreaCode")) { String wellID = d[col].replaceAll("\\D", ""); wellColumns = Integer.parseInt(wellID); } } } } // Populate MetadataStore if (isMetadataCollected()) { status("Populating MetadataStore"); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this, true); store.setExperimentID("Experiment:" + experiment.getName(), 0); store.setExperimentType("Other", 0); // populate SPW metadata store.setPlateColumnNamingConvention("1", 0); store.setPlateRowNamingConvention("A", 0); parseTemplateFile(store); plateName = plateName.substring(plateName.indexOf("-") + 1); store.setPlateName(plateName, 0); store.setPlateExternalIdentifier(plateName, 0); // HACK: if we don't have the analysis file, we don't how many // rows/columns are in the plate // assume that a 96 well plate is 8x12, and a 384 well plate is 16x24 if (wellColumns == 0) { if (nWells == 96) { wellColumns = 12; } else if (nWells == 384) { wellColumns = 24; } else { warn("Could not determine the plate dimensions."); wellColumns = 24; } } for (int well=0; well<nWells; well++) { int wellIndex = wellNumber[well]; int row = wellIndex / wellColumns; int wellCol = (wellIndex % wellColumns) + 1; store.setWellRow(new Integer(row), 0, well); store.setWellColumn(new Integer(wellCol - 1), 0, well); String imageID = MetadataTools.createLSID("Image", well); store.setWellSampleImageRef(imageID, 0, well, 0); store.setWellSampleIndex(new Integer(well), 0, well, 0); // populate Image/Pixels metadata store.setImageExperimentRef("Experiment:" + experiment.getName(), well); char wellRow = (char) ('A' + row); store.setImageID(imageID, well); store.setImageName("Well " + wellRow + wellCol, well); String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); store.setImageInstrumentRef(instrumentID, well); MetadataTools.setDefaultCreationDate(store, id, well); } // populate image-level ROIs String[] colors = new String[getSizeC()]; int nextROI = 0; for (AnalysisFile af : analysisFiles) { String file = af.filename; String name = new Location(file).getName(); if (!name.startsWith("Well")) continue; int[] position = getPositionFromFile(file); int well = position[0]; if (name.endsWith("detail.txt")) { String data = DataTools.readFile(file); String[] lines = data.split("\n"); int start = 0; while (start < lines.length && !lines[start].startsWith("Label")) { start++; } if (start >= lines.length) continue; String[] columns = lines[start].split("\t"); List<String> columnNames = Arrays.asList(columns); for (int j=start+1; j<lines.length; j++) { populateROI(columnNames, lines[j].split("\t"), well, nextROI++, position[1], position[2], store); } } else if (name.endsWith("AllModesOverlay.tif")) { // original color for each channel is stored in // results/Well<nnnn>_mode<n>_z<nnn>_t<nnn>_AllModesOverlay.tif if (colors[position[3]] != null) continue; try { colors[position[3]] = getChannelColorFromFile(file); } catch (IOException e) { } if (colors[position[3]] == null) continue; for (int s=0; s<getSeriesCount(); s++) { store.setChannelComponentColorDomain( colors[position[3]], s, position[3], 0); } if (position[3] == 0) { nextROI += parseMasks(store, well, nextROI, file); } } else if (name.endsWith("overlay.tif")) { nextROI += parseMasks(store, well, nextROI, file); } } } } // -- Helper methods -- /** * Get the color associated with the given file's channel. * The file must be one of the * Well<nnnn>_mode<n>_z<nnn>_t<nnn>_AllModesOverlay.tif * files in <experiment>/<plate>/results/ */ private String getChannelColorFromFile(String file) throws FormatException, IOException { RandomAccessInputStream s = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(s); IFD ifd = tp.getFirstIFD(); s.close(); int[] colorMap = ifd.getIFDIntArray(IFD.COLOR_MAP, false); if (colorMap == null) return null; int nEntries = colorMap.length / 3; int max = Integer.MIN_VALUE; int maxIndex = -1; for (int c=0; c<3; c++) { int v = (colorMap[c * nEntries] >> 8) & 0xff; if (v > max) { max = v; maxIndex = c; } else if (v == max) { return "gray"; } } switch (maxIndex) { case 0: return "R"; case 1: return "G"; case 2: return "B"; } return null; } /** * Returns an array of length 5 that contains the well, time point, * Z and channel indices corresponding to the given analysis file. */ private int[] getPositionFromFile(String file) { int[] position = new int[4]; file = file.substring(file.lastIndexOf(File.separator) + 1); String wellIndex = file.substring(4, file.indexOf("_")); position[0] = Integer.parseInt(wellIndex) - 1; int tIndex = file.indexOf("_t") + 2; String t = file.substring(tIndex, file.indexOf("_", tIndex)); position[1] = Integer.parseInt(t); int zIndex = file.indexOf("_z") + 2; String zValue = file.substring(zIndex, file.indexOf("_", zIndex)); position[2] = Integer.parseInt(zValue); int cIndex = file.indexOf("mode") + 4; String cValue = file.substring(cIndex, file.indexOf("_", cIndex)); position[3] = Integer.parseInt(cValue) - 1; return position; } private void populateROI(List<String> columns, String[] data, int series, int roi, int time, int z, MetadataStore store) { float cx = Float.parseFloat(data[columns.indexOf("Col")]); float cy = Float.parseFloat(data[columns.indexOf("Row")]); Integer tv = new Integer(time); Integer zv = new Integer(z); store.setROIT0(tv, series, roi); store.setROIT1(tv, series, roi); store.setROIZ0(zv, series, roi); store.setROIZ1(zv, series, roi); store.setShapeText(data[columns.indexOf("Label")], series, roi, 0); store.setShapeTheT(tv, series, roi, 0); store.setShapeTheZ(zv, series, roi, 0); store.setCircleCx(data[columns.indexOf("Col")], series, roi, 0); store.setCircleCy(data[columns.indexOf("Row")], series, roi, 0); float diam = Float.parseFloat(data[columns.indexOf("Cell Diam.")]); String radius = String.valueOf(diam / 2); store.setCircleR(radius, series, roi, 0); // NB: other attributes are "Nucleus Area", "Cell Type", and // "Mean Nucleus Intens." } private byte[] getTile(int well, int no, int row, int col, Region intersection) throws FormatException, IOException { intersection.x %= tileWidth; intersection.y %= tileHeight; int tileIndex = (no * tileRows + row) * tileCols + col; readers[well][tileIndex].setId(tiffs[well][tileIndex]); int bpp = FormatTools.getBytesPerPixel(getPixelType()); int ch = getRGBChannelCount(); int bufferSize = intersection.width * intersection.height * ch * bpp; if (cachedTileBuffer == null || cachedTileBuffer.length != bufferSize) { cachedTileBuffer = new byte[bufferSize]; } byte[] buf = readers[well][tileIndex].openBytes(0, cachedTileBuffer, intersection.x, intersection.y, intersection.width, intersection.height); return buf; } /** Parse metadata from the Nugenesistemplate.txt file. */ private void parseTemplateFile(MetadataStore store) throws IOException { if (templateFile == null) return; Float physicalSizeX = null, physicalSizeY = null, exposure = null; Vector<String> channelNames = new Vector<String>(); String date = null; String data = DataTools.readFile(templateFile); String[] lines = data.split("\r\n"); for (String line : lines) { int eq = line.indexOf("="); if (eq != -1) { String key = line.substring(0, eq); String value = line.substring(eq + 1); if (key.equals("Barcode")) { store.setPlateExternalIdentifier(value, 0); } else if (key.equals("Carrier")) { store.setPlateName(value, 0); } else if (key.equals("Pixel_X")) { physicalSizeX = new Float(value); } else if (key.equals("Pixel_Y")) { physicalSizeY = new Float(value); } else if (key.equals("Objective_ID")) { store.setObjectiveModel(value, 0, 0); } else if (key.equals("Magnification")) { int mag = (int) Float.parseFloat(value); store.setObjectiveNominalMagnification(new Integer(mag), 0, 0); } else if (key.startsWith("Mode_")) { channelNames.add(value); } else if (key.equals("Date")) { date = value; } else if (key.equals("Time")) { date += " " + value; } else if (key.equals("Exposure")) { exposure = new Float(value); } } } for (int well=0; well<tiffs.length; well++) { if (physicalSizeX != null) { store.setDimensionsPhysicalSizeX(physicalSizeX, well, 0); } if (physicalSizeY != null) { store.setDimensionsPhysicalSizeY(physicalSizeY, well, 0); } for (int c=0; c<channelNames.size(); c++) { if (c < getEffectiveSizeC()) { store.setLogicalChannelName(channelNames.get(c), well, c); } } date = DateTools.formatDate(date, "dd/MM/yyyy HH:mm:ss"); store.setImageCreationDate(date, well); for (int i=0; i<getImageCount(); i++) { store.setPlaneTimingExposureTime(exposure, well, 0, i); } } } /** * Parse Mask ROIs from the given TIFF and place them in the given * MetadataStore. * @return the number of masks parsed */ private int parseMasks(MetadataStore store, int series, int roi, String overlayTiff) throws FormatException, IOException { MinimalTiffReader r = new MinimalTiffReader(); r.setId(overlayTiff); byte[] plane = r.openBytes(0); byte[][] planes = null; if (r.isIndexed()) { planes = ImageTools.indexedToRGB(r.get8BitLookupTable(), plane); } else { planes = new byte[r.getRGBChannelCount()][]; int bpp = FormatTools.getBytesPerPixel(r.getPixelType()); for (int c=0; c<planes.length; c++) { planes[c] = ImageTools.splitChannels( plane, c, planes.length, bpp, false, r.isInterleaved()); } } for (int i=0; i<planes[0].length; i++) { boolean channelsEqual = true; for (int c=1; c<planes.length; c++) { if (planes[c][i] != planes[0][i]) { channelsEqual = false; break; } } if (channelsEqual) { for (int c=0; c<planes.length; c++) { planes[c][i] = 0; } } } String pixelType = FormatTools.getPixelTypeString(r.getPixelType()); int nMasks = 0; for (int i=0; i<planes.length; i++) { // threshold the pixel data boolean validMask = false; for (int p=0; p<planes[i].length; p++) { if (planes[i][p] != 0) { validMask = true; planes[i][p] = (byte) 1; } } if (validMask) { store.setMaskX("0", series, roi + i, 0); store.setMaskY("0", series, roi + i, 0); store.setMaskWidth(String.valueOf(r.getSizeX()), series, roi + i, 0); store.setMaskHeight(String.valueOf(r.getSizeY()), series, roi + i, 0); store.setMaskPixelsBigEndian( new Boolean(!r.isLittleEndian()), series, roi + i, 0); store.setMaskPixelsSizeX(new Integer(r.getSizeX()), series, roi + i, 0); store.setMaskPixelsSizeY(new Integer(r.getSizeY()), series, roi + i, 0); store.setMaskPixelsExtendedPixelType("bit", series, roi + i, 0); store.setMaskPixelsBinData(planes[i], series, roi + i, 0); nMasks++; } } r.close(); planes = null; return nMasks; } // -- Helper class -- class AnalysisFile { public String filename; public int plate = -1, well = -1; } }
// Colorizer.java package loci.plugins.in; import ij.CompositeImage; import ij.ImagePlus; import ij.measure.Calibration; import ij.process.ColorProcessor; import ij.process.ImageProcessor; import ij.process.LUT; import java.awt.Color; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.io.IOException; import java.util.Arrays; import java.util.List; import loci.formats.ChannelFiller; import loci.formats.DimensionSwapper; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.ImageReader; import loci.formats.MinMaxCalculator; import loci.plugins.BF; import loci.plugins.util.ImageProcessorReader; import loci.plugins.util.VirtualImagePlus; public class Colorizer { // -- Fields -- private ImportProcess process; // -- Constructor -- public Colorizer(ImportProcess process) { this.process = process; } // -- Colorizer methods -- public List<ImagePlus> applyColors(List<ImagePlus> imps) { final ImporterOptions options = process.getOptions(); final ImageProcessorReader reader = process.getReader(); final DimensionSwapper dimSwapper = process.getDimensionSwapper(); final ChannelFiller channelFiller = process.getChannelFiller(); final ImageReader imageReader = process.getImageReader(); for (int i=0; i<imps.size(); i++) { ImagePlus imp = imps.get(i); final int series = (Integer) imp.getProperty(ImagePlusReader.PROP_SERIES); reader.setSeries(series); // get LUT for each channel final String stackOrder = dimSwapper.getDimensionOrder(); final int zSize = imp.getNSlices(); final int cSize = imp.getNChannels(); final int tSize = imp.getNFrames(); final int stackSize = imp.getStackSize(); final LUT[] channelLUTs = new LUT[cSize]; boolean hasChannelLUT = false; for (int c=0; c<cSize; c++) { final int index = FormatTools.getIndex(stackOrder, zSize, cSize, tSize, stackSize, 0, c, 0); channelLUTs[c] = (LUT) imp.getProperty(ImagePlusReader.PROP_LUT + index); if (channelLUTs[c] != null) hasChannelLUT = true; } // compute color mode and LUTs to use int mode = -1; LUT[] luts; if (options.isColorModeDefault()) { // NB: Default color mode behavior depends on the situation. final boolean isRGB = reader.isRGB() || imageReader.isRGB(); if (isRGB || channelFiller.isFilled()) { // NB: The original data had more than one channel per plane // (e.g., RGB image planes), so we use the composite display mode. mode = CompositeImage.COMPOSITE; luts = makeLUTs(channelLUTs, true); // preserve original LUTs } else if (hasChannelLUT) { // NB: The original data had only one channel per plane, // but had at least one lookup table defined. We use the color // display mode, with missing LUTs as grayscale. mode = CompositeImage.COLOR; luts = makeLUTs(channelLUTs, false); // preserve original LUTs } else { // NB: The original data had only one channel per plane, // and had no lookup tables defined, so we use the grayscale mode. mode = CompositeImage.GRAYSCALE; luts = null; } } else if (options.isColorModeComposite()) { mode = CompositeImage.COMPOSITE; luts = makeLUTs(channelLUTs, true); // preserve existing channel LUTs } else if (options.isColorModeColorized()) { mode = CompositeImage.COLOR; luts = makeLUTs(channelLUTs, true); // preserve existing channel LUTs } else if (options.isColorModeGrayscale()) { mode = CompositeImage.GRAYSCALE; luts = null; // use default (grayscale) channel LUTs } else if (options.isColorModeCustom()) { mode = CompositeImage.COLOR; luts = makeLUTs(series); // override any existing channel LUTs } else { throw new IllegalStateException("Invalid color mode: " + options.getColorMode()); } // apply color mode and LUTs final boolean doComposite = !options.isViewStandard() && mode != -1 && cSize > 1 && cSize <= 7; if (doComposite) { final ImagePlus toClose = imp; CompositeImage compImage = new CompositeImage(imp, mode) { public void close() { super.close(); toClose.close(); } }; if (luts != null) compImage.setLuts(luts); imps.set(i, compImage); imp = compImage; } else { // NB: Cannot use CompositeImage for some reason. if (luts != null && luts.length > 0 && luts[0] != null) { if (imp instanceof VirtualImagePlus) { ((VirtualImagePlus) imp).setLUTs(luts); } else if (cSize == 1) imp.getProcessor().setColorModel(luts[0]); } if (mode != -1 && cSize > 7) { // NB: Cannot use CompositeImage with more than seven channels. BF.warn(options.isQuiet(), "Data has too many channels for " + options.getColorMode() + " color mode"); } } applyDisplayRanges(imp, series); } return imps; } // -- Helper methods -- private void applyDisplayRanges(ImagePlus imp, int series) { if (imp instanceof VirtualImagePlus) { // virtual stacks handle their own display ranges return; } final ImporterOptions options = process.getOptions(); final ImageProcessorReader reader = process.getReader(); final int pixelType = reader.getPixelType(); final boolean autoscale = options.isAutoscale() || FormatTools.isFloatingPoint(pixelType); // always autoscale float data final int cSize = imp.getNChannels(); final double[] cMin = new double[cSize]; final double[] cMax = new double[cSize]; Arrays.fill(cMin, Double.NaN); Arrays.fill(cMax, Double.NaN); if (autoscale) { // extract display ranges for autoscaling final MinMaxCalculator minMaxCalc = process.getMinMaxCalculator(); final int cBegin = process.getCBegin(series); final int cStep = process.getCStep(series); for (int c=0; c<cSize; c++) { final int cIndex = cBegin + c * cStep; Double cMinVal = null, cMaxVal = null; try { cMinVal = minMaxCalc.getChannelGlobalMinimum(cIndex); cMaxVal = minMaxCalc.getChannelGlobalMaximum(cIndex); } catch (FormatException exc) { } catch (IOException exc) { } if (cMinVal != null) cMin[c] = cMinVal; if (cMaxVal != null) cMax[c] = cMaxVal; } } // for calibrated data, the offset from zero final double zeroOffset = getZeroOffset(imp); // fill in default display ranges as appropriate final double min, max; if (FormatTools.isFloatingPoint(pixelType)) { // no defined min and max values for floating point data min = max = Double.NaN; } else { final int bitDepth = reader.getBitsPerPixel(); final double halfPow = Math.pow(2, bitDepth - 1); final double fullPow = 2 * halfPow; final boolean signed = FormatTools.isSigned(pixelType); if (signed) { // signed data is centered at 0 min = -halfPow; max = halfPow - 1; } else { // unsigned data begins at 0 min = 0; max = fullPow - 1; } for (int c=0; c<cSize; c++) { if (Double.isNaN(cMin[c])) cMin[c] = min; if (Double.isNaN(cMax[c])) cMax[c] = max; } } // apply display ranges if (imp instanceof CompositeImage) { // apply channel display ranges final CompositeImage compImage = (CompositeImage) imp; for (int c=0; c<cSize; c++) { LUT lut = compImage.getChannelLut(c + 1); // NB: Uncalibrate values before assigning to LUT min/max. lut.min = cMin[c] - zeroOffset; lut.max = cMax[c] - zeroOffset; } } else { // compute global display range from channel display ranges double globalMin = Double.POSITIVE_INFINITY; double globalMax = Double.NEGATIVE_INFINITY; for (int c=0; c<cSize; c++) { if (cMin[c] < globalMin) globalMin = cMin[c]; if (cMax[c] > globalMax) globalMax = cMax[c]; } // NB: Uncalibrate values before assigning to display range min/max. globalMin -= zeroOffset; globalMax -= zeroOffset; // apply global display range ImageProcessor proc = imp.getProcessor(); if (proc instanceof ColorProcessor) { // NB: Should never occur. ;-) final ColorProcessor colorProc = (ColorProcessor) proc; colorProc.setMinAndMax(globalMin, globalMax, 3); } else { ColorModel model = proc.getColorModel(); proc.setMinAndMax(globalMin, globalMax); proc.setColorModel(model); imp.setDisplayRange(globalMin, globalMax); } } } private LUT[] makeLUTs(ColorModel[] cm, boolean colorize) { final ImporterOptions options = process.getOptions(); final LUT[] luts = new LUT[cm.length]; for (int c=0; c<luts.length; c++) { if (cm[c] instanceof LUT) luts[c] = (LUT) cm[c]; else if (cm[c] instanceof IndexColorModel) { luts[c] = new LUT((IndexColorModel) cm[c], 0, 255); } else { Color color = colorize ? options.getDefaultCustomColor(c) : Color.white; luts[c] = makeLUT(color); } } return luts; } private LUT[] makeLUTs(int series) { final ImageProcessorReader reader = process.getReader(); reader.setSeries(series); LUT[] luts = new LUT[reader.getSizeC()]; for (int c=0; c<luts.length; c++) luts[c] = makeLUT(series, c); return luts; } private LUT makeLUT(int series, int channel) { final ImporterOptions options = process.getOptions(); Color color = options.getCustomColor(series, channel); if (color == null) color = options.getDefaultCustomColor(channel); return makeLUT(color); } private LUT makeLUT(Color color) { final int red = color.getRed(); final int green = color.getGreen(); final int blue = color.getBlue(); final int lutLength = 256; final int lutDivisor = lutLength - 1; byte[] r = new byte[lutLength]; byte[] g = new byte[lutLength]; byte[] b = new byte[lutLength]; for (int i=0; i<lutLength; i++) { r[i] = (byte) (i * red / lutDivisor); g[i] = (byte) (i * green / lutDivisor); b[i] = (byte) (i * blue / lutDivisor); } LUT lut = new LUT(r, g, b); return lut; } private static double getZeroOffset(ImagePlus imp) { final Calibration cal = imp.getCalibration(); if (cal.getFunction() != Calibration.STRAIGHT_LINE) return 0; final double[] coeffs = cal.getCoefficients(); if (coeffs == null || coeffs.length == 0) return 0; return coeffs[0]; } }
package ome.scifio; import java.io.File; import java.io.IOException; import net.imglib2.meta.Axes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ome.scifio.FormatException; import ome.scifio.io.RandomAccessInputStream; import ome.scifio.util.FormatTools; import ome.scifio.util.SCIFIOMetadataTools; /** * Abstract superclass of all SCIFIO {@link ome.scifio.Reader} implementations. * * @see ome.scifio.Reader * @see ome.scifio.HasFormat * @see ome.scifio.Metadata * @see ome.scifio.Plane * * @author Mark Hiner */ public abstract class AbstractReader<M extends TypedMetadata, P extends DataPlane<?>> extends AbstractGroupable implements TypedReader<M, P> { // -- Constants -- protected static final Logger LOGGER = LoggerFactory.getLogger(Reader.class); // -- Fields -- /** Metadata for the current image source. */ protected M metadata; /** Whether or not to normalize float data. */ protected boolean normalizeData; /** List of domains in which this format is used. */ protected String[] domains = new String[0]; /** Name of current file. */ protected String currentId; /** Whether this format supports multi-file datasets. */ protected boolean hasCompanionFiles = false; private Class<P> planeClass; // -- Constructors -- /** Constructs a reader and stores a reference to its plane type */ public AbstractReader(Class<P> planeClass) { this.planeClass = planeClass; } // -- Reader API Methods -- //TODO Merge common Reader and Writer API methods /* * @see ome.scifio.Reader#openPlane(int, int) */ public P openPlane(final int imageIndex, final int planeNumber) throws FormatException, IOException { return openPlane(imageIndex, planeNumber, 0, 0, metadata.getAxisLength(imageIndex, Axes.X), metadata.getAxisLength(imageIndex, Axes.Y)); } /* * @see ome.scifio.Reader#openPlane(int, int, int, int, int, int) */ public P openPlane(final int imageIndex, final int planeIndex, final int x, final int y, final int w, final int h) throws FormatException, IOException { P plane = null; try { plane = createPlane(x, y, w, h); } catch (IllegalArgumentException e) { throw new FormatException("Image plane too large. Only 2GB of data can " + "be extracted at one time. You can workaround the problem by opening " + "the plane in tiles; for further details, see: " + "http: "i-see-an-outofmemory-or-negativearraysize-error-message-when-" + "attempting-to-open-an-svs-or-jpeg-2000-file.-what-does-this-mean", e); } return openPlane(imageIndex, planeIndex, plane, x, y, w, h); } /* * @see ome.scifio.Reader#openPlane(int, int, ome.scifio.Plane) */ public P openPlane(int imageIndex, int planeIndex, Plane plane) throws FormatException, IOException { return openPlane(imageIndex, planeIndex, this.<P>castToTypedPlane(plane)); } /* * @see ome.scifio.Reader#openPlane(int, int, ome.scifio.Plane, int, int, int, int) */ public P openPlane(int imageIndex, int planeIndex, Plane plane, int x, int y, int w, int h) throws FormatException, IOException { return openPlane(imageIndex, planeIndex, this.<P>castToTypedPlane(plane), x, y, w, h); } /* * @see ome.scifio.Reader#getCurrentFile() */ public String getCurrentFile() { return getStream() == null ? null : getStream().getFileName(); } /* * @see ome.scifio.Reader#getDomains() */ public String[] getDomains() { return domains; } /* * @see ome.scifio.Reader#getStream() */ public RandomAccessInputStream getStream() { return metadata == null ? null : metadata.getSource(); } /* * @see ome.scifio.Reader#getUnderlyingReaders() */ public Reader[] getUnderlyingReaders() { // TODO Auto-generated method stub return null; } /* * @see ome.scifio.Reader#getOptimalTileWidth(int) */ public int getOptimalTileWidth(final int imageIndex) { return metadata.getAxisLength(imageIndex, Axes.X); } /* * @see ome.scifio.Reader#getOptimalTileHeight(int) */ public int getOptimalTileHeight(final int imageIndex) { final int bpp = FormatTools.getBytesPerPixel(metadata.getPixelType(imageIndex)); final int width = metadata.getAxisLength(imageIndex, Axes.X); final int rgbcCount = metadata.getRGBChannelCount(imageIndex); final int maxHeight = (1024 * 1024) / (width * rgbcCount * bpp); return Math.min(maxHeight, metadata.getAxisLength(imageIndex, Axes.Y)); } /* * @see ome.scifio.Reader#setMetadata(ome.scifio.Metadata) */ public void setMetadata(ome.scifio.Metadata meta) throws IOException { setMetadata(SCIFIOMetadataTools.<M>castMeta(meta)); } /* * @see ome.scifio.Reader#getMetadata() */ public M getMetadata() { return metadata; } /* * @see ome.scifio.Reader#setNormalized(boolean) */ public void setNormalized(final boolean normalize) { normalizeData = normalize; } /* * @see ome.scifio.Reader#isNormalized() */ public boolean isNormalized() { return normalizeData; } /* * @see ome.scifio.Reader#hasCompanionFiles() */ public boolean hasCompanionFiles() { return hasCompanionFiles; } /* * @see ome.scifio.Reader#setSource(java.lang.String) */ public void setSource(final String fileName) throws IOException { if (getStream() != null && getStream().getFileName() != null && getStream().getFileName().equals(fileName)) { getStream().seek(0); return; } else { close(); setSource(new RandomAccessInputStream(getContext(), fileName)); } } /* * @see ome.scifio.Reader#setSource(java.io.File) */ public void setSource(final File file) throws IOException { setSource(file.getName()); } /* * @see ome.scifio.Reader#setSource(ome.scifio.io.RandomAccessInputStream) */ public void setSource(final RandomAccessInputStream stream) throws IOException { if (metadata != null && getStream() != stream) close(); if (metadata == null) { currentId = stream.getFileName(); try { @SuppressWarnings("unchecked") final M meta = (M) getFormat().createParser().parse(stream); setMetadata(meta); } catch (final FormatException e) { throw new IOException(e); } } } /* * @see ome.scifio.Reader#readPlane(ome.scifio.io.RandomAccessInputStream, int, int, int, int, int, ome.scifio.Plane) */ public Plane readPlane(RandomAccessInputStream s, int imageIndex, int x, int y, int w, int h, Plane plane) throws IOException { return readPlane(s, imageIndex, x, y, w, h, this.<P>castToTypedPlane(plane)); } /* * @see ome.scifio.Reader#readPlane(ome.scifio.io.RandomAccessInputStream, int, int, int, int, int, int, ome.scifio.Plane) */ public Plane readPlane(RandomAccessInputStream s, int imageIndex, int x, int y, int w, int h, int scanlinePad, Plane plane) throws IOException { return readPlane(s, imageIndex, x, y, w, h, scanlinePad, this.<P>castToTypedPlane(plane)); } /* * @see ome.scifio.Reader#getPlaneCount(int) */ public int getPlaneCount(final int imageIndex) { return metadata.getPlaneCount(imageIndex); } /* * @see ome.scifio.Reader#getImageCount() */ public int getImageCount() { return metadata.getImageCount(); } /* * @see ome.scifio.Reader#castToTypedPlane(ome.scifio.Plane) */ public <T extends Plane> T castToTypedPlane(Plane plane) { if(!planeClass.isAssignableFrom(plane.getClass())) { throw new IllegalArgumentException("Incompatible plane types. " + "Attempted to cast: " + plane.getClass() + " to: " + planeClass); } @SuppressWarnings("unchecked") T p = (T)plane; return p; } // -- TypedReader API -- /* * @see ome.scifio.TypedReader#openPlane(int, int, ome.scifio.DataPlane) */ public P openPlane(final int imageIndex, final int planeIndex, final P plane) throws FormatException, IOException { return openPlane( imageIndex, planeIndex, plane, 0, 0, metadata.getAxisLength(imageIndex, Axes.X), metadata.getAxisLength(imageIndex, Axes.Y)); } /* * @see ome.scifio.TypedReader#setMetadata(ome.scifio.TypedMetadata) */ public void setMetadata(final M meta) throws IOException { if (metadata != null && metadata != meta) { close(); } if (metadata == null) metadata = meta; } /* * @see ome.scifio.TypedReader#readPlane(ome.scifio.io.RandomAccessInputStream, int, int, int, int, int, ome.scifio.DataPlane) */ public P readPlane(final RandomAccessInputStream s, final int imageIndex, final int x, final int y, final int w, final int h, final P plane) throws IOException { return readPlane(s, imageIndex, x, y, w, h, 0, plane); } /* * @see ome.scifio.TypedReader#readPlane(ome.scifio.io.RandomAccessInputStream, int, int, int, int, int, int, ome.scifio.DataPlane) */ public P readPlane(final RandomAccessInputStream s, final int imageIndex, final int x, final int y, final int w, final int h, final int scanlinePad, final P plane) throws IOException { final int c = metadata.getRGBChannelCount(imageIndex); final int bpp = FormatTools.getBytesPerPixel(metadata.getPixelType(imageIndex)); byte[] bytes = plane.getBytes(); if (x == 0 && y == 0 && w == metadata.getAxisLength(imageIndex, Axes.X) && h == metadata.getAxisLength(imageIndex, Axes.Y) && scanlinePad == 0) { s.read(bytes); } else if (x == 0 && w == metadata.getAxisLength(imageIndex, Axes.X) && scanlinePad == 0) { if (metadata.isInterleaved(imageIndex)) { s.skipBytes(y * w * bpp * c); s.read(bytes, 0, h * w * bpp * c); } else { final int rowLen = w * bpp; for (int channel = 0; channel < c; channel++) { s.skipBytes(y * rowLen); s.read(bytes, channel * h * rowLen, h * rowLen); if (channel < c - 1) { // no need to skip bytes after reading final channel s.skipBytes((metadata.getAxisLength(imageIndex, Axes.Y) - y - h) * rowLen); } } } } else { final int scanlineWidth = metadata.getAxisLength(imageIndex, Axes.X) + scanlinePad; if (metadata.isInterleaved(imageIndex)) { s.skipBytes(y * scanlineWidth * bpp * c); for (int row = 0; row < h; row++) { s.skipBytes(x * bpp * c); s.read(bytes, row * w * bpp * c, w * bpp * c); if (row < h - 1) { // no need to skip bytes after reading final row s.skipBytes(bpp * c * (scanlineWidth - w - x)); } } } else { for (int channel = 0; channel < c; channel++) { s.skipBytes(y * scanlineWidth * bpp); for (int row = 0; row < h; row++) { s.skipBytes(x * bpp); s.read(bytes, channel * w * h * bpp + row * w * bpp, w * bpp); if (row < h - 1 || channel < c - 1) { // no need to skip bytes after reading final row of final channel s.skipBytes(bpp * (scanlineWidth - w - x)); } } if (channel < c - 1) { // no need to skip bytes after reading final channel s.skipBytes(scanlineWidth * bpp * (metadata.getAxisLength(imageIndex, Axes.Y) - y - h)); } } } } return plane; } /* * @see ome.scifio.TypedReader#getPlaneClass() */ public Class<P> getPlaneClass() { return planeClass; } // -- HasSource Format API -- /* * @see ome.scifio.Reader#close(boolean) */ public void close(final boolean fileOnly) throws IOException { if (metadata != null) metadata.close(fileOnly); if (!fileOnly) { metadata = null; currentId = null; } } }
package org.pdxfinder.commands; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.neo4j.ogm.json.JSONArray; import org.neo4j.ogm.json.JSONObject; import org.neo4j.ogm.session.Session; import org.pdxfinder.dao.*; import org.pdxfinder.utilities.LoaderUtils; import org.pdxfinder.utilities.Standardizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.stream.Stream; /** * Load data from JAX. */ @Component @Order(value = 0) public class LoadJAXData implements CommandLineRunner { private final static Logger log = LoggerFactory.getLogger(LoadJAXData.class); private final static String JAX_DATASOURCE_ABBREVIATION = "JAX"; private final static String JAX_DATASOURCE_NAME = "The Jackson Laboratory"; private final static String JAX_DATASOURCE_DESCRIPTION = "The Jackson Laboratory PDX mouse models."; private final static String NSG_BS_NAME = "NOD scid gamma"; private final static String NSG_BS_SYMBOL = "NOD.Cg-Prkdc<scid> Il2rg<tm1Wjl>/SzJ"; private final static String NSG_BS_DESC = ""; private final static String NSG_BS_URL = "http://jax.org/strain/005557"; private final static String HISTOLOGY_NOTE = "Pathologist assessment of patient tumor and pdx model tumor histology slides."; private final static String NOT_SPECIFIED = Standardizer.NOT_SPECIFIED; // for now all samples are of tumor tissue private final static Boolean NORMAL_TISSUE_FALSE = false; private HostStrain nsgBS; private ExternalDataSource jaxDS; private Options options; private CommandLineParser parser; private CommandLine cmd; private HelpFormatter formatter; private LoaderUtils loaderUtils; private Session session; @Value("${jaxpdx.file}") private String file; @Value("${jaxpdx.url}") private String urlStr; @Value("${jaxpdx.variation.url}") private String variationURL; @Value("${jaxpdx.histology.url}") private String histologyURL; @Value("${jaxpdx.variation.max}") private int maxVariations; @Value("${jaxpdx.ref.assembly}") private String refAssembly; HashMap<String, String> passageMap = null; HashMap<String, Image> histologyMap = null; @PostConstruct public void init() { formatter = new HelpFormatter(); } public LoadJAXData(LoaderUtils loaderUtils) { this.loaderUtils = loaderUtils; } @Override public void run(String... args) throws Exception { OptionParser parser = new OptionParser(); parser.allowsUnrecognizedOptions(); parser.accepts("loadJAX", "Load JAX PDX data"); parser.accepts("loadALL", "Load all, including JAX PDX data"); OptionSet options = parser.parse(args); if (options.has("loadJAX") || options.has("loadALL")) { log.info("Loading JAX PDX data."); if (urlStr != null) { log.info("Loading from URL " + urlStr); parseJSON(parseURL(urlStr)); } else if (file != null) { log.info("Loading from file " + file); parseJSON(parseFile(file)); } else { log.error("No jaxpdx.file or jaxpdx.url provided in properties"); } } } //JSON Fields {"Model ID","Gender","Age","Race","Ethnicity","Specimen Site","Primary Site","Initial Diagnosis","Clinical Diagnosis", // "Tumor Type","Grades","Tumor Stage","Markers","Sample Type","Strain","Mouse Sex","Engraftment Site"}; private void parseJSON(String json) { jaxDS = loaderUtils.getExternalDataSource(JAX_DATASOURCE_ABBREVIATION, JAX_DATASOURCE_NAME, JAX_DATASOURCE_DESCRIPTION); nsgBS = loaderUtils.getHostStrain(NSG_BS_NAME, NSG_BS_SYMBOL, NSG_BS_URL, NSG_BS_DESC); try { JSONObject job = new JSONObject(json); JSONArray jarray = job.getJSONArray("pdxInfo"); for (int i = 0; i < jarray.length(); i++) { JSONObject j = jarray.getJSONObject(i); createGraphObjects(j); } } catch (Exception e) { log.error("Error getting JAX PDX models", e); } } @Transactional void createGraphObjects(JSONObject j) throws Exception { String id = j.getString("Model ID"); histologyMap = getHistologyImageMap(id); // the preference is for clinical diagnosis but if not available use initial diagnosis String diagnosis = j.getString("Clinical Diagnosis"); if (diagnosis.trim().length() == 0 || "Not specified".equals(diagnosis)) { diagnosis = j.getString("Initial Diagnosis"); } // if the diagnosis is still unknown don't load it if(diagnosis.toLowerCase().contains("unknown") || diagnosis.toLowerCase().contains("not specified")){ System.out.println("Skipping model "+id+" with diagnosis:"+diagnosis); return; } String classification = j.getString("Tumor Stage") + "/" + j.getString("Grades"); String age = Standardizer.getAge(j.getString("Age")); String gender = Standardizer.getGender(j.getString("Gender")); PatientSnapshot pSnap = loaderUtils.getPatientSnapshot(j.getString("Patient ID"), gender, j.getString("Race"), j.getString("Ethnicity"), age, jaxDS); String tumorType = Standardizer.getTumorType(j.getString("Tumor Type")); Sample sample = loaderUtils.getSample(j.getString("Model ID"), tumorType, diagnosis, j.getString("Primary Site"), j.getString("Specimen Site"), j.getString("Sample Type"), classification, NORMAL_TISSUE_FALSE, JAX_DATASOURCE_ABBREVIATION); if (histologyMap.containsKey("Patient")) { Histology histology = new Histology(); Image image = histologyMap.get("Patient"); histology.addImage(image); sample.addHistology(histology); } // TODO: When the QA information is available, replace this with actual data from the feed String qaPassages = null; QualityAssurance qa = new QualityAssurance("Histology", HISTOLOGY_NOTE, ValidationTechniques.VALIDATION, qaPassages); loaderUtils.saveQualityAssurance(qa); pSnap.addSample(sample); loaderUtils.savePatientSnapshot(pSnap); ModelCreation mc = loaderUtils.createModelCreation(id, jaxDS.getAbbreviation(), sample, qa); mc.addRelatedSample(sample); String backgroundStrain = j.getString("Strain"); // JAX feed does not supply implantation type String implantationType = "Subcutaneous"; String implantationSite = j.getString("Engraftment Site"); loadVariationData(mc, backgroundStrain, implantationSite, implantationType); } /* Use the modelID in the modelCreation object to get model specific variation data This is a set of makers with marker association details Since we are creating samples here attach any histology images to the sample based on passage # */ private void loadVariationData(ModelCreation modelCreation,String backgroundStrain,String implantationSite,String implantationType) { if (maxVariations == 0) { return; } try { passageMap = new HashMap<>(); HashMap<String, HashMap<String, Set<MarkerAssociation>>> sampleMap = new HashMap<>(); HashMap<String, Set<MarkerAssociation>> markerMap = new HashMap<>(); JSONObject job = new JSONObject(parseURL(this.variationURL + modelCreation.getSourcePdxId())); JSONArray jarray = job.getJSONArray("variation"); String sample = null; String symbol, id, technology, aaChange, chromosome, seqPosition, refAllele, consequence, rsVariants, readDepth, alleleFrequency, altAllele = null; log.info(jarray.length() + " gene variants for model " + modelCreation.getSourcePdxId()); // configure the maximum variations to load in properties file // loading them all will take a while (hour?) int stop = jarray.length(); if (maxVariations > 0 && maxVariations < jarray.length()) { stop = maxVariations; } for (int i = 0; i < stop;) { JSONObject j = jarray.getJSONObject(i); sample = j.getString("sample"); symbol = j.getString("gene symbol"); id = j.getString("gene id"); aaChange = j.getString("amino acid change"); technology = j.getString("platform"); chromosome = j.getString("chromosome"); seqPosition = j.getString("seq position"); refAllele = j.getString("ref allele"); consequence = j.getString("consequence"); rsVariants = j.getString("rs variants"); readDepth = j.getString("read depth"); alleleFrequency = j.getString("allele frequency"); altAllele = j.getString("alt allele"); passageMap.put(sample, j.getString("passage num")); // since there are 8 fields assume (incorrectly?) all MAs are unique // create a new one rather than look for exisitng one MarkerAssociation ma = new MarkerAssociation(); ma.setAminoAcidChange(aaChange); ma.setConsequence(consequence); ma.setAlleleFrequency(alleleFrequency); ma.setChromosome(chromosome); ma.setReadDepth(readDepth); ma.setRefAllele(refAllele); ma.setAltAllele(altAllele); ma.setRefAssembly(refAssembly); ma.setRsVariants(rsVariants); ma.setSeqPosition(seqPosition); ma.setReadDepth(readDepth); Marker marker = loaderUtils.getMarker(symbol); marker.setEntrezId(id); ma.setMarker(marker); Platform platform = loaderUtils.getPlatform(technology, this.jaxDS); platform.setExternalDataSource(jaxDS); //loaderUtils.savePlatform(platform); //loaderUtils.createPlatformAssociation(platform, marker); markerMap = sampleMap.get(sample); if (markerMap == null) { markerMap = new HashMap<>(); } // make a map of markerAssociation collections keyed to technology if (markerMap.containsKey(technology)) { markerMap.get(technology).add(ma); } else { HashSet<MarkerAssociation> set = new HashSet<>(); set.add(ma); markerMap.put(technology, set); } sampleMap.put(sample, markerMap); i++; if (i % 100 == 0) { System.out.println("loaded " + i + " markers"); } } System.out.println("loaded " + stop + " markers for " + modelCreation.getSourcePdxId()); for (String sampleKey : sampleMap.keySet()) { String passage = getPassage(sampleKey); markerMap = sampleMap.get(sampleKey); HashSet<MolecularCharacterization> mcs = new HashSet<>(); for (String tech : markerMap.keySet()) { MolecularCharacterization mc = new MolecularCharacterization(); mc.setPlatform(loaderUtils.getPlatform(tech, this.jaxDS)); mc.setMarkerAssociations(markerMap.get(tech)); mcs.add(mc); } //PdxPassage pdxPassage = new PdxPassage(modelCreation, passage); Specimen specimen = loaderUtils.getSpecimen(modelCreation, sampleKey, this.jaxDS.getAbbreviation(), passage); Sample specSample = new Sample(); specSample.setSourceSampleId(sampleKey); specimen.setSample(specSample); specSample.setMolecularCharacterizations(mcs); //specimen.setPdxPassage(pdxPassage); if (histologyMap.containsKey(passage)) { Histology histology = new Histology(); Image image = histologyMap.get(passage); histology.addImage(image); specSample.addHistology(histology); } if(backgroundStrain != null){ HostStrain bs = new HostStrain(backgroundStrain); specimen.setHostStrain(bs); } if(implantationSite != null){ ImplantationSite is = new ImplantationSite(implantationSite); specimen.setImplantationSite(is); } if(implantationType != null){ ImplantationType it = new ImplantationType(implantationType); specimen.setImplantationType(it); } loaderUtils.saveSpecimen(specimen); modelCreation.addSpecimen(specimen); modelCreation.addRelatedSample(specSample); System.out.println("saved passage " + passage + " for model " + modelCreation.getSourcePdxId() + " from sample " + sampleKey); } loaderUtils.saveModelCreation(modelCreation); } catch (Exception e) { log.error("", e); } } private String getPassage(String sample) { String p = "0"; try { p = passageMap.get(sample).replaceAll("P", ""); } catch (Exception e) { log.info("Unable to determine passage from sample name " + sample + ". Assuming 0"); } return p; } /* For a given model return a map of passage # or "Patient" -> histology image URL */ private HashMap<String, Image> getHistologyImageMap(String id) { HashMap<String, Image> map = new HashMap<>(); try { JSONObject job = new JSONObject(parseURL(this.histologyURL + id)); JSONArray jarray = job.getJSONObject("pdxHistology").getJSONArray("Graphics"); String comment = job.getJSONObject("pdxHistology").getString("Comment"); for (int i = 0; i < jarray.length(); i++) { job = jarray.getJSONObject(i); String desc = job.getString("Description"); // comments apply to all of a models histology but histologies are passage specific // so I guess attach the comment to all image descriptions if (comment != null && comment.trim().length() > 0) { String sep = ""; if (desc != null && desc.trim().length() > 0) { sep = " : "; } desc = comment + sep + desc; } String url = job.getString("URL"); Image img = new Image(); img.setDescription(desc); img.setUrl(url); if (desc.startsWith("Patient") || desc.startsWith("Primary")) { map.put("Patient", img); } else { String[] parts = desc.split(" "); if (parts[0].startsWith("P")) { try { String passage = new Integer(parts[0].replace("P", "")).toString(); map.put(passage, img); } catch (Exception e) { log.info("Can't extract passage from description " + desc); } } } } } catch (Exception e) { log.error("Error getting histology for model " + id, e); } return map; } private String parseURL(String urlStr) { StringBuilder sb = new StringBuilder(); try { URL url = new URL(urlStr); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); } catch (Exception e) { log.error("Unable to read from URL " + urlStr, e); } return sb.toString(); } private String parseFile(String path) { StringBuilder sb = new StringBuilder(); try { Stream<String> stream = Files.lines(Paths.get(path)); Iterator itr = stream.iterator(); while (itr.hasNext()) { sb.append(itr.next()); } } catch (Exception e) { log.error("Failed to load file " + path, e); } return sb.toString(); } }
package org.intermine.api.profile; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.lang.StringUtils; import org.intermine.api.config.ClassKeyHelper; import org.intermine.api.search.Scope; import org.intermine.api.search.SearchRepository; import org.intermine.api.search.WebSearchable; import org.intermine.api.tag.TagTypes; import org.intermine.api.template.ApiTemplate; import org.intermine.api.tracker.TrackerDelegate; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; /** * Class to represent a user of the webapp * * @author Mark Woodbridge * @author Thomas Riley */ public class Profile { protected ProfileManager manager; protected String username; protected Integer userId; protected String password; protected Map<String, SavedQuery> savedQueries = new TreeMap<String, SavedQuery>(); protected Map<String, InterMineBag> savedBags = Collections.synchronizedMap(new TreeMap<String, InterMineBag>()); protected Map<String, ApiTemplate> savedTemplates = new TreeMap<String, ApiTemplate>(); protected Map<String, InterMineBag> savedInvalidBags = new TreeMap<String, InterMineBag>(); protected Map queryHistory = new ListOrderedMap(); protected boolean savingDisabled; private final SearchRepository searchRepository; private String token; /** * True if this account is purely local. False if it was created * in reference to another authenticator, such as an OpenID provider. */ private final boolean isLocal; /** * Construct a Profile * @param manager the manager for this profile * @param username the username for this profile * @param userId the id of this user * @param password the password for this profile * @param savedQueries the saved queries for this profile * @param savedBags the saved bags for this profile * @param savedTemplates the saved templates for this profile * @param token The token to use as an API key */ public Profile(ProfileManager manager, String username, Integer userId, String password, Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags, Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal) { this.manager = manager; this.username = username; this.userId = userId; this.password = password; this.isLocal = isLocal; if (savedQueries != null) { this.savedQueries.putAll(savedQueries); } if (savedBags != null) { this.savedBags.putAll(savedBags); } if (savedTemplates != null) { this.savedTemplates.putAll(savedTemplates); } searchRepository = new SearchRepository(this, Scope.USER); this.token = token; } /** * Construct a Profile * @param manager the manager for this profile * @param username the username for this profile * @param userId the id of this user * @param password the password for this profile * @param savedQueries the saved queries for this profile * @param savedBags the saved bags for this profile * @param savedInvalidBags the saved bags which type doesn't match with the model * @param savedTemplates the saved templates for this profile * @param token The token to use as an API key */ public Profile(ProfileManager manager, String username, Integer userId, String password, Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags, Map<String, InterMineBag> savedInvalidBags, Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal) { this(manager, username, userId, password, savedQueries, savedBags, savedTemplates, token, isLocal); this.savedInvalidBags = savedInvalidBags; } /** * Construct a profile without an API key * @param manager the manager for this profile * @param username the username for this profile * @param userId the id of this user * @param password the password for this profile * @param savedQueries the saved queries for this profile * @param savedBags the saved bags for this profile * @param savedTemplates the saved templates for this profile */ public Profile(ProfileManager manager, String username, Integer userId, String password, Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags, Map<String, ApiTemplate> savedTemplates, boolean isLocal) { this(manager, username, userId, password, savedQueries, savedBags, savedTemplates, null, isLocal); } /** * Return the ProfileManager that was passed to the constructor. * @return the ProfileManager */ public ProfileManager getProfileManager() { return manager; } /** * Get the value of username * @return the value of username */ public String getUsername() { return username; } /** * Return a first part of the username before the "@" sign (used in metabolicMine) * @author radek * * @return String */ public String getName() { int atPos = username.indexOf("@"); if (atPos > 0) { return username.substring(0, atPos); } else { return username; } } /** * Return true if and only if the user is logged is (and the Profile will be written to the * userprofile). * @return Return true if logged in */ public boolean isLoggedIn() { return getUsername() != null; } /** * Return true if and only if the user logged is superuser * @return Return true if superuser */ public boolean isSuperuser() { if (username != null && manager.getSuperuser().equals(username)) { return true; } return false; } /** * Get the value of userId * @return an Integer */ public Integer getUserId() { return userId; } /** * Set the userId * * @param userId an Integer */ public void setUserId(Integer userId) { this.userId = userId; } /** * Get the value of password * @return the value of password */ public String getPassword() { return password; } /** * Disable saving until enableSaving() is called. This is called before many templates or * queries need to be saved or deleted because each call to ProfileManager.saveProfile() is * slow. */ public void disableSaving() { savingDisabled = true; } /** * Re-enable saving when saveTemplate(), deleteQuery() etc. are called. Also calls * ProfileManager.saveProfile() to write this Profile to the database and rebuilds the * template description index. */ public void enableSaving() { savingDisabled = false; if (manager != null) { manager.saveProfile(this); } reindex(TagTypes.TEMPLATE); reindex(TagTypes.BAG); } /** * Get the users saved templates * @return saved templates */ public synchronized Map<String, ApiTemplate> getSavedTemplates() { return Collections.unmodifiableMap(savedTemplates); } /** * Save a template * @param name the template name * @param template the template */ public void saveTemplate(String name, ApiTemplate template) { savedTemplates.put(name, template); if (manager != null && !savingDisabled) { manager.saveProfile(this); reindex(TagTypes.TEMPLATE); } } /** * get a template * @param name the template * @return template */ public ApiTemplate getTemplate(String name) { return savedTemplates.get(name); } /** * Delete a template and its tags, rename the template tracks adding the prefix "deleted_" * to the previous name. If trackerDelegate is null, the template tracks are not renamed * @param name the template name * @param trackerDelegate used to rename the template tracks. */ public void deleteTemplate(String name, TrackerDelegate trackerDelegate, boolean deleteTracks) { savedTemplates.remove(name); if (manager != null) { if (!savingDisabled) { manager.saveProfile(this); reindex(TagTypes.TEMPLATE); } } TagManager tagManager = getTagManager(); tagManager.deleteObjectTags(name, TagTypes.TEMPLATE, username); if (trackerDelegate != null && deleteTracks) { trackerDelegate.updateTemplateName(name, "deleted_" + name); } } /** * Get the value of savedQueries * @return the value of savedQueries */ public Map<String, SavedQuery> getSavedQueries() { return Collections.unmodifiableMap(savedQueries); } /** * Save a query * @param name the query name * @param query the query */ public void saveQuery(String name, SavedQuery query) { savedQueries.put(name, query); if (manager != null && !savingDisabled) { manager.saveProfile(this); } } /** * Delete a query * @param name the query name */ public void deleteQuery(String name) { savedQueries.remove(name); if (manager != null && !savingDisabled) { manager.saveProfile(this); } } /** * Get the session query history. * @return map from query name to SavedQuery */ public Map<String, SavedQuery> getHistory() { return Collections.unmodifiableMap(queryHistory); } /** * Save a query to the query history. * @param query the SavedQuery to save to the history */ public void saveHistory(SavedQuery query) { queryHistory.put(query.getName(), query); } /** * Remove an item from the query history. * @param name the of the SavedQuery from the history */ public void deleteHistory(String name) { queryHistory.remove(name); } /** * Rename an item in the history. * @param oldName the name of the old item * @param newName the new name */ public void renameHistory(String oldName, String newName) { Map<String, SavedQuery> newMap = new ListOrderedMap(); Iterator<String> iter = queryHistory.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); SavedQuery sq = (SavedQuery) queryHistory.get(name); if (name.equals(oldName)) { sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery()); } newMap.put(sq.getName(), sq); } queryHistory = newMap; } /** * Get the value of savedBags * @return the value of savedBags */ public synchronized Map<String, InterMineBag> getSavedBags() { return Collections.unmodifiableMap(savedBags); } /** * Get the saved bags in a map of "status key" -> map of lists * @return */ public Map<String, Map<String, InterMineBag>> getSavedBagsByStatus() { Map<String, Map<String, InterMineBag>> result = new LinkedHashMap<String, Map<String, InterMineBag>>(); // maintain order on the JSP page result.put("NOT_CURRENT", new HashMap<String, InterMineBag>()); result.put("TO_UPGRADE", new HashMap<String, InterMineBag>()); result.put("CURRENT", new HashMap<String, InterMineBag>()); for (InterMineBag bag : savedBags.values()) { String state = bag.getState(); // XXX: this can go pear shaped if new states are introduced Map<String, InterMineBag> stateMap = result.get(state); stateMap.put(bag.getName(), bag); } return result; } /** * Get the value of savedBags current * @return the value of savedBags */ public Map<String, InterMineBag> getCurrentSavedBags() { Map<String, InterMineBag> clone = new HashMap<String, InterMineBag>(); clone.putAll(savedBags); for (InterMineBag bag : savedBags.values()) { if (!bag.isCurrent()) { clone.remove(bag.getName()); } } return clone; } /** * Stores a new bag in the profile. Note that bags are always present in the user profile * database, so this just adds the bag to the in-memory list of this profile. * * @param name the name of the bag * @param bag the InterMineBag object */ public void saveBag(String name, InterMineBag bag) { if (StringUtils.isBlank(name)) { throw new RuntimeException("No name specified for the list to save."); } savedBags.put(name, bag); reindex(TagTypes.BAG); } /** * Create a bag and save it to the userprofile database. * * @param name the bag name * @param type the bag type * @param description the bag description * @param classKeys the classKeys used to obtain the primary identifier field * @return the new bag * @throws ObjectStoreException if something goes wrong */ public InterMineBag createBag(String name, String type, String description, Map<String, List<FieldDescriptor>> classKeys) throws ObjectStoreException { ObjectStore os = manager.getProductionObjectStore(); ObjectStoreWriter uosw = manager.getProfileObjectStoreWriter(); List<String> keyFielNames = ClassKeyHelper.getKeyFieldNames( classKeys, type); InterMineBag bag = new InterMineBag(name, type, description, new Date(), BagState.CURRENT, os, userId, uosw, keyFielNames); savedBags.put(name, bag); reindex(TagTypes.BAG); return bag; } /** * Delete a bag from the user account, if user is logged in also deletes from the userprofile * database. * If there is no such bag associated with the account, no action is performed. * @param name the bag name * @throws ObjectStoreException if problems deleting bag */ public void deleteBag(String name) throws ObjectStoreException { if (!savedBags.containsKey(name) && !savedInvalidBags.containsKey(name)) { throw new BagDoesNotExistException(name + " not found"); } InterMineBag bagToDelete; if (savedBags.containsKey(name)) { bagToDelete = savedBags.get(name); savedBags.remove(name); } else { bagToDelete = savedInvalidBags.get(name); savedInvalidBags.remove(name); } if (isLoggedIn()) { bagToDelete.delete(); } TagManager tagManager = getTagManager(); tagManager.deleteObjectTags(name, TagTypes.BAG, username); reindex(TagTypes.BAG); } /** * Update the type of bag. * If there is no such bag associated with the account, no action is performed. * @param name the bag name * @param newType the type to set * @throws ObjectStoreException if problems deleting bag */ public void updateBagType(String name, String newType) throws ObjectStoreException { if (!savedBags.containsKey(name) && !savedInvalidBags.containsKey(name)) { throw new BagDoesNotExistException(name + " not found"); } InterMineBag bagToUpdate; if (savedBags.containsKey(name)) { bagToUpdate = savedBags.get(name); } else { bagToUpdate = savedInvalidBags.get(name); } if (isLoggedIn()) { bagToUpdate.setType(newType); } } /** * Rename an existing bag, throw exceptions when bag doesn't exist of if new name already * exists. Moves tags from old bag to new bag. * @param oldName the bag to rename * @param newName new name for the bag * @throws ObjectStoreException if problems storing */ public void renameBag(String oldName, String newName) throws ObjectStoreException { if (!savedBags.containsKey(oldName)) { throw new BagDoesNotExistException("Attempting to rename " + oldName); } if (savedBags.containsKey(newName)) { throw new ProfileAlreadyExistsException("Attempting to rename a bag to a new name that" + " already exists: " + newName); } InterMineBag bag = savedBags.get(oldName); savedBags.remove(oldName); bag.setName(newName); saveBag(newName, bag); moveTagsToNewObject(oldName, newName, TagTypes.BAG); } /** * Update an existing template, throw exceptions when template doesn't exist. * Moves tags from old template to new template. * @param oldName the template to rename * @param template the new template * @throws ObjectStoreException if problems storing */ public void updateTemplate(String oldName, ApiTemplate template) throws ObjectStoreException { if (!savedTemplates.containsKey(oldName)) { throw new IllegalArgumentException("Attempting to rename a template that doesn't" + " exist: " + oldName); } savedTemplates.remove(oldName); saveTemplate(template.getName(), template); if (!oldName.equals(template.getName())) { moveTagsToNewObject(oldName, template.getName(), TagTypes.TEMPLATE); } } private void moveTagsToNewObject(String oldTaggedObj, String newTaggedObj, String type) { TagManager tagManager = getTagManager(); List<Tag> tags = tagManager.getTags(null, oldTaggedObj, type, username); for (Tag tag : tags) { try { tagManager.addTag(tag.getTagName(), newTaggedObj, type, this); } catch (TagManager.TagNameException e) { throw new IllegalStateException("Existing tag is illegal: " + tag.getTagName(), e); } catch (TagManager.TagNamePermissionException e) { throw new IllegalStateException("Object tagged with " + tag.getTagName(), e); } tagManager.deleteTag(tag); } } private TagManager getTagManager() { return new TagManagerFactory(manager).getTagManager(); } /** * Create a map from category name to a list of templates contained * within that category. */ private void reindex(String type) { // We also take this opportunity to index the user's template queries, bags, etc. searchRepository.addWebSearchables(type); } /** * Return a WebSearchable Map for the given type. * @param type the type (from TagTypes) * @return the Map */ public Map<String, ? extends WebSearchable> getWebSearchablesByType(String type) { if (type.equals(TagTypes.TEMPLATE)) { return savedTemplates; } if (type.equals(TagTypes.BAG)) { return getSavedBags(); } throw new RuntimeException("unknown type: " + type); } /** * Get the SearchRepository for this Profile. * @return the SearchRepository for the user */ public SearchRepository getSearchRepository() { return searchRepository; } /** * @return the user's API key token. */ public String getApiKey() { return token; } /** * Set the API token for this user, and save it in * the backing db. * @param token */ public void setApiKey(String token) { this.token = token; if (manager != null && !savingDisabled) { manager.saveProfile(this); } } /** * Returns true if this is a local account, and not, for * example, an OpenID account. * @return Whether or not this is a local account. */ public boolean isLocal() { return this.isLocal; } }
package org.intermine.web.logic; /** * Container for ServletContext and Session attribute names used by the webapp * * @author Kim Rutherford * @author Thomas Riley */ public final class Constants { private Constants() { // Hidden constructor. } /** * ServletContext attribute used to store web.properties */ public static final String WEB_PROPERTIES = "WEB_PROPERTIES"; /** * Attribute used to store origin information about properties in * the context of this web application. */ public static final String PROPERTIES_ORIGINS = "PROPERTIES_ORIGINS"; /** * ServletContext attribute, List of category names. */ public static final String CATEGORIES = "CATEGORIES"; /** * ServletContext attribute, autocompletion. */ public static final String AUTO_COMPLETER = "AUTO_COMPLETER"; /** * ServletContext attribute, Map from unqualified type name to list of subclass names. */ public static final String SUBCLASSES = "SUBCLASSES"; /** * Session attribute, name of tab selected on MyMine page. */ public static final String MYMINE_PAGE = "MYMINE_PAGE"; // serializes /** * ServletContext attribute used to store the WebConfig object for the Model. */ public static final String WEBCONFIG = "WEBCONFIG"; /** * Session attribute used to store the user's Profile */ public static final String PROFILE = "PROFILE"; // serialized as 'username' /** * Session attribute used to store the current query */ public static final String QUERY = "QUERY"; /** * Session attribute used to store the status new template */ public static final String NEW_TEMPLATE = "NEW_TEMPLATE"; /** * Session attribute used to store the status editing template */ public static final String EDITING_TEMPLATE = "EDITING_TEMPLATE"; /** * Session attribute used to store the previous template name */ public static final String PREV_TEMPLATE_NAME = "PREV_TEMPLATE_NAME"; /** * Servlet context attribute - map from aspect set name to Aspect object. */ public static final String ASPECTS = "ASPECTS"; /** * Session attribute equals Boolean.TRUE when logged in user is superuser. */ public static final String IS_SUPERUSER = "IS_SUPERUSER"; /** * Session attribute that temporarily holds a Vector of messages that will be displayed by the * errorMessages.jsp on the next page viewed by the user and then removed (allows message * after redirect). */ public static final String MESSAGES = "MESSAGES"; /** * Session attribute that temporarily holds a Vector of errors that will be displayed by the * errorMessages.jsp on the next page viewed by the user and then removed (allows errors * after redirect). */ public static final String ERRORS = "ERRORS"; /** * Session attribute that temporarily holds messages from the Portal */ public static final String PORTAL_MSG = "PORTAL_MSG"; /** * Session attribute that holds message when a lookup constraint has been used */ public static final String LOOKUP_MSG = "LOOKUP_MSG"; /** * The name of the property to look up to find the maximum size of an inline table. */ public static final String INLINE_TABLE_SIZE = "inline.table.size"; /** * Session attribut containing the default operator name, either 'and' or 'or'. */ public static final String DEFAULT_OPERATOR = "DEFAULT_OPERATOR"; /** * Period of time to wait for client to poll a running query before cancelling the query. */ public static final int QUERY_TIMEOUT_SECONDS = 20; /** * Refresh period specified on query poll page. */ public static final int POLL_REFRESH_SECONDS = 2; /** * The session attribute that holds the ReportObjectCache object for the session. */ public static final String REPORT_OBJECT_CACHE = "REPORT_OBJECT_CACHE"; /** * Session attribute that holds cache of table identifiers to PagedTable objects. */ public static final String TABLE_MAP = "TABLE_MAP"; /** * Session attribute. A Map from query id to QueryMonitor. */ public static final String RUNNING_QUERIES = "RUNNING_QUERIES"; /** * Servlet attribute. Map from MultiKey(experiment, gene) id to temp file name. */ public static final String GRAPH_CACHE = "GRAPH_CACHE"; /** * Servlet attribute. Map from class name to Set of leaf class descriptors. */ public static final String LEAF_DESCRIPTORS_MAP = "LEAF_DESCRIPTORS_MAP"; /** * Servlet attribute. The global webapp cache - a InterMineCache object. */ public static final String GLOBAL_CACHE = "GLOBAL_CACHE"; /** * Maximum size a bag should have if the user is not logged in (to save memory) */ public static final int MAX_NOT_LOGGED_BAG_SIZE = 500; /** * Servlet attribute. Contains the SearchRepository for global/public WebSearchable objects. */ public static final String GLOBAL_SEARCH_REPOSITORY = "GLOBAL_SEARCH_REPOSITORY"; /** * Default size of table implemented by PagedTable. */ public static final int DEFAULT_TABLE_SIZE = 25; /** * Session attribute used to store the size of table with results. */ public static final String RESULTS_TABLE_SIZE = "RESULTS_TABLE_SIZE"; /** * Session attribute used to store WebState object. */ public static final String WEB_STATE = "WEB_STATE"; /** * Current version of the InterMine WebService. * This constant must changed every time the API changes, either by addition * or deletion of features. */ public static final int WEB_SERVICE_VERSION = 12; /** * Key for a Map from class name to Boolean.TRUE for all classes in the model that do not have * any class keys. */ public static final String KEYLESS_CLASSES_MAP = "KEYLESS_CLASSES_MAP"; /** * Key for the InterMine API object */ public static final String INTERMINE_API = "INTERMINE_API"; /** Key for the initialiser error **/ public static final String INITIALISER_KEY_ERROR = "INITIALISER_KEY_ERROR"; /** * key for the map saved in the session containing the status of saved bags */ public static final String SAVED_BAG_STATUS = "SAVED_BAG_STATUS"; /** Key for the upgrading bag on the session **/ public static final String UPGRADING_BAG = "UPGRADING"; /** The replay-attack prevention nonces **/ public static final String NONCES = "NONCES"; /** The display name of the current user **/ public static final String USERNAME = "USERNAME"; /** The name of the current open-id provider **/ public static final String PROVIDER = "PROVIDER"; /** * The key for the open-id providers located in the servlet context. */ public static final String OPENID_PROVIDERS = "OPENID_PROVIDERS"; /* The names of various user preferences known to the web application */ /** The preference set if the user does not like lots of emails */ public static final String NO_SPAM = "do_not_spam"; /** The preference set if the user does not want to be found */ public static final String HIDDEN = "hidden"; }
package bisq.core.dao.node.full; import bisq.core.app.BisqEnvironment; import bisq.core.dao.DaoOptionKeys; import bisq.core.dao.state.model.blockchain.PubKeyScript; import bisq.core.dao.state.model.blockchain.TxInput; import bisq.core.user.Preferences; import bisq.common.UserThread; import bisq.common.handlers.ResultHandler; import bisq.common.util.Utilities; import org.bitcoinj.core.Utils; import com.neemre.btcdcli4j.core.BitcoindException; import com.neemre.btcdcli4j.core.CommunicationException; import com.neemre.btcdcli4j.core.client.BtcdClient; import com.neemre.btcdcli4j.core.client.BtcdClientImpl; import com.neemre.btcdcli4j.core.domain.RawTransaction; import com.neemre.btcdcli4j.core.domain.enums.ScriptTypes; import com.neemre.btcdcli4j.daemon.BtcdDaemon; import com.neemre.btcdcli4j.daemon.BtcdDaemonImpl; import com.neemre.btcdcli4j.daemon.event.BlockListener; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import com.google.inject.Inject; import javax.inject.Named; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import java.util.List; import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; /** * Request blockchain data via RPC from Bitcoin Core for a FullNode. * Runs in a custom thread. * See the rpc.md file in the doc directory for more info about the setup. */ @Slf4j public class RpcService { private final String rpcUser; private final String rpcPassword; private final String rpcPort; private final String rpcBlockPort; private final boolean dumpBlockchainData; private BtcdClient client; private BtcdDaemon daemon; // We could use multiple threads but then we need to support ordering of results in a queue // Keep that for optimization after measuring performance differences private final ListeningExecutorService executor = Utilities.getSingleThreadExecutor("RpcService"); // Constructor @SuppressWarnings("WeakerAccess") @Inject public RpcService(Preferences preferences, @Named(DaoOptionKeys.RPC_PORT) String rpcPort, @Named(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT) String rpcBlockPort, @Named(DaoOptionKeys.DUMP_BLOCKCHAIN_DATA) boolean dumpBlockchainData) { this.rpcUser = preferences.getRpcUser(); this.rpcPassword = preferences.getRpcPw(); // mainnet is 8332, testnet 18332, regtest 18443 boolean isPortSet = rpcPort != null && !rpcPort.isEmpty(); boolean isMainnet = BisqEnvironment.getBaseCurrencyNetwork().isMainnet(); boolean isTestnet = BisqEnvironment.getBaseCurrencyNetwork().isTestnet(); this.rpcPort = isPortSet ? rpcPort : isMainnet ? "8332" : isTestnet ? "18332" : "18443"; // regtest this.rpcBlockPort = rpcBlockPort != null && !rpcBlockPort.isEmpty() ? rpcBlockPort : "5125"; this.dumpBlockchainData = dumpBlockchainData; } // API void setup(ResultHandler resultHandler, Consumer<Throwable> errorHandler) { ListenableFuture<Void> future = executor.submit(() -> { try { long startTs = System.currentTimeMillis(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); CloseableHttpClient httpProvider = HttpClients.custom().setConnectionManager(cm).build(); Properties nodeConfig = new Properties(); nodeConfig.setProperty("node.bitcoind.rpc.protocol", "http"); nodeConfig.setProperty("node.bitcoind.rpc.host", "127.0.0.1"); nodeConfig.setProperty("node.bitcoind.rpc.auth_scheme", "Basic"); nodeConfig.setProperty("node.bitcoind.rpc.user", rpcUser); nodeConfig.setProperty("node.bitcoind.rpc.password", rpcPassword); nodeConfig.setProperty("node.bitcoind.rpc.port", rpcPort); nodeConfig.setProperty("node.bitcoind.notification.block.port", rpcBlockPort); // todo(chirhonul): we are not using the alert or wallet functionality currently, so we may want to // disable this in the com.neemre.btcdcli4j library entirely, if possible. nodeConfig.setProperty("node.bitcoind.notification.alert.port", String.valueOf(bisq.network.p2p.Utils.findFreeSystemPort())); nodeConfig.setProperty("node.bitcoind.notification.wallet.port", String.valueOf(bisq.network.p2p.Utils.findFreeSystemPort())); nodeConfig.setProperty("node.bitcoind.http.auth_scheme", "Basic"); BtcdClientImpl client = new BtcdClientImpl(httpProvider, nodeConfig); daemon = new BtcdDaemonImpl(client); log.info("Setup took {} ms", System.currentTimeMillis() - startTs); this.client = client; } catch (BitcoindException | CommunicationException e) { if (e instanceof CommunicationException) log.error("Probably Bitcoin core is not running or the rpc port is not set correctly. rpcPort=" + rpcPort); log.error(e.toString()); e.printStackTrace(); log.error(e.getCause() != null ? e.getCause().toString() : "e.getCause()=null"); throw new RpcException(e.getMessage(), e); } catch (Throwable e) { log.error(e.toString()); e.printStackTrace(); throw new RpcException(e.toString(), e); } return null; }); Futures.addCallback(future, new FutureCallback<Void>() { public void onSuccess(Void ignore) { UserThread.execute(resultHandler::handleResult); } public void onFailure(@NotNull Throwable throwable) { UserThread.execute(() -> errorHandler.accept(throwable)); } }); } void addNewBtcBlockHandler(Consumer<RawBlock> btcBlockHandler, Consumer<Throwable> errorHandler) { daemon.addBlockListener(new BlockListener() { @Override public void blockDetected(com.neemre.btcdcli4j.core.domain.RawBlock rawBtcBlock) { if (rawBtcBlock.getHeight() == null || rawBtcBlock.getHeight() == 0) { log.warn("We received a RawBlock with no data. blockHash={}", rawBtcBlock.getHash()); return; } try { log.info("New block received: height={}, id={}", rawBtcBlock.getHeight(), rawBtcBlock.getHash()); List<RawTx> txList = rawBtcBlock.getTx().stream() .map(e -> getTxFromRawTransaction(e, rawBtcBlock)) .collect(Collectors.toList()); UserThread.execute(() -> { btcBlockHandler.accept(new RawBlock(rawBtcBlock.getHeight(), rawBtcBlock.getTime() * 1000, // rawBtcBlock.getTime() is in sec but we want ms rawBtcBlock.getHash(), rawBtcBlock.getPreviousBlockHash(), ImmutableList.copyOf(txList))); }); } catch (Throwable t) { errorHandler.accept(t); } } }); } void requestChainHeadHeight(Consumer<Integer> resultHandler, Consumer<Throwable> errorHandler) { ListenableFuture<Integer> future = executor.submit(client::getBlockCount); Futures.addCallback(future, new FutureCallback<>() { public void onSuccess(Integer chainHeight) { UserThread.execute(() -> resultHandler.accept(chainHeight)); } public void onFailure(@NotNull Throwable throwable) { UserThread.execute(() -> errorHandler.accept(throwable)); } }); } void requestBtcBlock(int blockHeight, Consumer<RawBlock> resultHandler, Consumer<Throwable> errorHandler) { ListenableFuture<RawBlock> future = executor.submit(() -> { long startTs = System.currentTimeMillis(); String blockHash = client.getBlockHash(blockHeight); com.neemre.btcdcli4j.core.domain.RawBlock rawBtcBlock = client.getBlock(blockHash, 2); List<RawTx> txList = rawBtcBlock.getTx().stream() .map(e -> getTxFromRawTransaction(e, rawBtcBlock)) .collect(Collectors.toList()); log.debug("requestBtcBlock with all txs took {} ms at blockHeight {}; txList.size={}", System.currentTimeMillis() - startTs, blockHeight, txList.size()); return new RawBlock(rawBtcBlock.getHeight(), rawBtcBlock.getTime() * 1000, // rawBtcBlock.getTime() is in sec but we want ms rawBtcBlock.getHash(), rawBtcBlock.getPreviousBlockHash(), ImmutableList.copyOf(txList)); }); Futures.addCallback(future, new FutureCallback<>() { @Override public void onSuccess(RawBlock block) { UserThread.execute(() -> resultHandler.accept(block)); } @Override public void onFailure(@NotNull Throwable throwable) { log.error("Error at requestBtcBlock: blockHeight={}", blockHeight); UserThread.execute(() -> errorHandler.accept(throwable)); } }); } // Private private RawTx getTxFromRawTransaction(RawTransaction rawBtcTx, com.neemre.btcdcli4j.core.domain.RawBlock rawBtcBlock) { String txId = rawBtcTx.getTxId(); long blockTime = rawBtcBlock.getTime() * 1000; // We convert block time from sec to ms int blockHeight = rawBtcBlock.getHeight(); String blockHash = rawBtcBlock.getHash(); final List<TxInput> txInputs = rawBtcTx.getVIn() .stream() .filter(rawInput -> rawInput != null && rawInput.getVOut() != null && rawInput.getTxId() != null) .map(rawInput -> { // We don't support segWit inputs yet as well as no pay to pubkey txs... String[] split = rawInput.getScriptSig().getAsm().split("\\[ALL\\] "); String pubKeyAsHex; if (split.length == 2) { pubKeyAsHex = rawInput.getScriptSig().getAsm().split("\\[ALL\\] ")[1]; } else { // If we receive a pay to pubkey tx the pubKey is not included as // it is in the output already. // Bitcoin Core creates payToPubKey tx when spending mined coins (regtest)... pubKeyAsHex = null; log.debug("pubKeyAsHex is not set as we received a not supported sigScript " + "(segWit or payToPubKey tx). txId={}, asm={}", rawBtcTx.getTxId(), rawInput.getScriptSig().getAsm()); } return new TxInput(rawInput.getTxId(), rawInput.getVOut(), pubKeyAsHex); }) .collect(Collectors.toList()); final List<RawTxOutput> txOutputs = rawBtcTx.getVOut() .stream() .filter(e -> e != null && e.getN() != null && e.getValue() != null && e.getScriptPubKey() != null) .map(rawBtcTxOutput -> { byte[] opReturnData = null; com.neemre.btcdcli4j.core.domain.PubKeyScript scriptPubKey = rawBtcTxOutput.getScriptPubKey(); if (ScriptTypes.NULL_DATA.equals(scriptPubKey.getType()) && scriptPubKey.getAsm() != null) { String[] chunks = scriptPubKey.getAsm().split(" "); // We get on testnet a lot of "OP_RETURN 0" data, so we filter those away if (chunks.length == 2 && "OP_RETURN".equals(chunks[0]) && !"0".equals(chunks[1])) { try { opReturnData = Utils.HEX.decode(chunks[1]); } catch (Throwable t) { log.warn("Error at Utils.HEX.decode(chunks[1]): " + t.toString() + " / chunks[1]=" + chunks[1] + "\nWe get sometimes exceptions with opReturn data, seems BitcoinJ " + "cannot handle all " + "existing OP_RETURN data, but we ignore them anyway as the OP_RETURN " + "data used for DAO transactions are all valid in BitcoinJ"); } } } // We don't support raw MS which are the only case where scriptPubKey.getAddresses()>1 String address = scriptPubKey.getAddresses() != null && scriptPubKey.getAddresses().size() == 1 ? scriptPubKey.getAddresses().get(0) : null; PubKeyScript pubKeyScript = dumpBlockchainData ? new PubKeyScript(scriptPubKey) : null; return new RawTxOutput(rawBtcTxOutput.getN(), rawBtcTxOutput.getValue().movePointRight(8).longValue(), rawBtcTx.getTxId(), pubKeyScript, address, opReturnData, blockHeight); } ) .collect(Collectors.toList()); return new RawTx(txId, blockHeight, blockHash, blockTime, ImmutableList.copyOf(txInputs), ImmutableList.copyOf(txOutputs)); } }
package hudson.model; import hudson.ExtensionPoint; import hudson.triggers.SCMTrigger; import hudson.triggers.TimerTrigger; import java.util.Set; import java.io.IOException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint { /** * Human-readable ID of this monitor, which needs to be unique within the system. * * <p> * This ID is used to remember persisted setting for this monitor, * so the ID should remain consistent beyond the Hudson JVM lifespan. */ public final String id; protected AdministrativeMonitor(String id) { this.id = id; } protected AdministrativeMonitor() { this.id = this.getClass().getName(); } /** * Returns the URL of this monitor, relative to the context path, like "administrativeMonitor/foobar". */ public String getUrl() { return "administrativeMonitor/"+id; } public String getDisplayName() { return id; } public final String getSearchUrl() { return getUrl(); } /** * Mark this monitor as disabled, to prevent this from showing up in the UI. */ public void disable(boolean value) throws IOException { Hudson hudson = Hudson.getInstance(); Set<String> set = hudson.disabledAdministrativeMonitors; if(value) set.add(id); else set.remove(id); hudson.save(); } /** * Returns true if this monitor {@link #disable(boolean) isn't disabled} earlier. * * <p> * This flag implements the ability for the admin to say "no thank you" to the monitor that * he wants to ignore. */ public boolean isEnabled() { return !Hudson.getInstance().disabledAdministrativeMonitors.contains(id); } /** * Returns true if this monitor is activated and * wants to produce a warning message. * * <p> * This method is called from the HTML rendering thread, * so it should run efficiently. */ public abstract boolean isActivated(); /** * URL binding to disable this monitor. */ public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); disable(true); rsp.sendRedirect2(req.getContextPath()+"/manage"); } }
package org.mwg.core.task; import org.mwg.Node; import org.mwg.plugin.AbstractNode; import org.mwg.plugin.AbstractTaskAction; import org.mwg.plugin.NodeState; import org.mwg.plugin.NodeStateCallback; import org.mwg.task.TaskContext; import org.mwg.task.TaskResult; class ActionProperties extends AbstractTaskAction { private final byte _filter; ActionProperties(byte filterType) { super(); this._filter = filterType; } @Override public void eval(TaskContext context) { final TaskResult previous = context.result(); final TaskResult result = context.newResult(); for (int i = 0; i < previous.size(); i++) { if (previous.get(i) instanceof AbstractNode) { final Node n = (Node) previous.get(i); final NodeState nState = context.graph().resolver().resolveState(n); nState.each(new NodeStateCallback() { @Override public void on(long attributeKey, byte elemType, Object elem) { if (_filter == -1 || elemType == _filter) { String retrieved = context.graph().resolver().hashToString(attributeKey); if (retrieved != null) { result.add(retrieved); } else { result.add(attributeKey); } } } }); n.free(); } } previous.clear(); context.continueWith(result); } }
// PickerTool.java package imagej.core.tools; import imagej.ext.display.event.input.KyPressedEvent; import imagej.ext.display.event.input.KyReleasedEvent; import imagej.ext.display.event.input.MsClickedEvent; import imagej.ext.plugin.Plugin; import imagej.ext.tool.AbstractTool; import imagej.ext.tool.Tool; import imagej.options.OptionsService; import imagej.options.plugins.OptionsColors; import imagej.util.ColorRGB; /** * Sets foreground and background values when tool is active and mouse clicked * over an image. * * @author Barry DeZonia */ @Plugin( type = Tool.class, name = "Picker", description = "Picker Tool (sets foreground/background colors/values)", iconPath = "/icons/tools/picker.png", priority = PickerTool.PRIORITY) public class PickerTool extends AbstractTool { // -- constants -- public static final int PRIORITY = -299; // -- instance variables -- private final PixelHelper helper = new PixelHelper(); private boolean altKeyDown = false; // -- Tool methods -- @Override public void onMouseClick(final MsClickedEvent evt) { if (!helper.recordEvent(evt)) { evt.consume(); return; } final OptionsColors options = getOptions(); final double value = helper.getValue(); final ColorRGB color = helper.getColor(); // background case? if (altKeyDown) { if (helper.isPureRGBCase()) { options.setBgColor(color); colorMessage("BG", color); } else { options.setBgGray(value); grayMessage("BG", value); } } else { // foreground case if (helper.isPureRGBCase()) { options.setFgColor(color); colorMessage("FG", color); } else { options.setFgGray(value); grayMessage("FG", value); } } options.save(); evt.consume(); } @Override public void onKeyDown(final KyPressedEvent evt) { altKeyDown = evt.getModifiers().isAltDown() || evt.getModifiers().isAltGrDown(); evt.consume(); } @Override public void onKeyUp(final KyReleasedEvent evt) { altKeyDown = evt.getModifiers().isAltDown() || evt.getModifiers().isAltGrDown(); evt.consume(); } @Override public String getDescription() { OptionsColors opts = getOptions(); StringBuilder sb = new StringBuilder(); sb.append("Picker FG: "); ColorRGB fgColor = opts.getFgColor(); ColorRGB bgColor = opts.getBgColor(); double fgValue = opts.getFgGray(); double bgValue = opts.getBgGray(); sb.append(String.format("(%.3f) (%d,%d,%d)", fgValue, fgColor.getRed(), fgColor.getGreen(), fgColor.getBlue())); sb.append(" BG: "); sb.append(String.format("(%.3f) (%d,%d,%d)", bgValue, bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue())); return sb.toString(); } // -- private interface -- private void colorMessage(final String label, final ColorRGB color) { final String message = String.format("%s color = (%d,%d,%d)", label, color.getRed(), color .getGreen(), color.getBlue()); helper.updateStatus(message); } private void grayMessage(final String label, final double value) { String message; if (helper.isIntegerCase()) message = String.format("%s gray value = %d", label, (long) value); else message = String.format("%s gray value = %f", label, value); helper.updateStatus(message); } private OptionsColors getOptions() { final OptionsService service = getContext().getService(OptionsService.class); return service.getOptions(OptionsColors.class); } }
package com.esotericsoftware.kryonet.rmi; import static com.esotericsoftware.minlog.Log.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import com.esotericsoftware.kryo.CustomSerialization; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.SerializationException; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.serialize.ArraySerializer; import com.esotericsoftware.kryo.serialize.FieldSerializer; import com.esotericsoftware.kryo.serialize.IntSerializer; import com.esotericsoftware.kryo.util.IntHashMap; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.EndPoint; import com.esotericsoftware.kryonet.FrameworkMessage; import com.esotericsoftware.kryonet.Listener; /** * Allows methods on registered objects to be invoked remotely over TCP. It costs at least 3 bytes more to use remote method * invocation than just sending the parameters. If the method has a return value, there is an additional cost of 1 byte. * @author Nathan Sweet <misc@n4te.com> */ public class ObjectSpace { static private final Object instancesLock = new Object(); static ObjectSpace[] instances = new ObjectSpace[0]; static private final HashMap<Class, Method[]> methodCache = new HashMap(); final IntHashMap idToObject = new IntHashMap(); Connection[] connections = {}; final Object connectionsLock = new Object(); private final Listener invokeListener = new Listener() { public void received (Connection connection, Object object) { if (!(object instanceof InvokeMethod)) return; if (connections != null) { int i = 0, n = connections.length; for (; i < n; i++) if (connection == connections[i]) break; if (i == n) return; // The InvokeMethod message is not for a connection in this ObjectSpace. } InvokeMethod invokeMethod = (InvokeMethod)object; Object target = idToObject.get(invokeMethod.objectID); if (target == null) { if (WARN) warn("kryonet", "Ignoring remote invocation request for unknown object ID: " + invokeMethod.objectID); return; } invoke(connection, target, invokeMethod); } public void disconnected (Connection connection) { removeConnection(connection); } }; /** * Creates an ObjectSpace with no connections. */ public ObjectSpace () { synchronized (instancesLock) { ObjectSpace[] instances = ObjectSpace.instances; ObjectSpace[] newInstances = new ObjectSpace[instances.length + 1]; newInstances[0] = this; System.arraycopy(instances, 0, newInstances, 1, instances.length); ObjectSpace.instances = newInstances; } } /** * Creates an ObjectSpace with the specified connection. More connections can be {@link #addConnection(Connection) added}. */ public ObjectSpace (Connection connection) { this(); addConnection(connection); } /** * Registers an object to allow the remote end of the ObjectSpace's connections to access it using the specified ID. * <p> * If a connection is added to multiple ObjectSpaces, the same object ID should not be used in more than one of those * ObjectSpaces. * @see #getRemoteObject(Connection, int, Class...) */ public void register (int objectID, Object object) { if (object == null) throw new IllegalArgumentException("object cannot be null."); idToObject.put(objectID, object); if (TRACE) trace("kryonet", "Object registered with ObjectSpace as " + objectID + ": " + object); } /** * Causes this ObjectSpace to stop listening to the connections for method invocation messages. */ public void close () { Connection[] connections = this.connections; for (int i = 0; i < connections.length; i++) connections[i].removeListener(invokeListener); synchronized (instancesLock) { ArrayList<Connection> temp = new ArrayList(Arrays.asList(instances)); temp.remove(this); instances = temp.toArray(new ObjectSpace[temp.size()]); } if (TRACE) trace("kryonet", "Closed ObjectSpace."); } /** * Allows the remote end of the specified connection to access objects registered in this ObjectSpace. */ public void addConnection (Connection connection) { if (connection == null) throw new IllegalArgumentException("connection cannot be null."); synchronized (connectionsLock) { Connection[] newConnections = new Connection[connections.length + 1]; newConnections[0] = connection; System.arraycopy(connections, 0, newConnections, 1, connections.length); connections = newConnections; } connection.addListener(invokeListener); if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection); } /** * Removes the specified connection, it will no longer be able to access objects registered in this ObjectSpace. */ public void removeConnection (Connection connection) { if (connection == null) throw new IllegalArgumentException("connection cannot be null."); connection.removeListener(invokeListener); synchronized (connectionsLock) { ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections)); temp.remove(connection); connections = temp.toArray(new Connection[temp.size()]); } if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection); } /** * Invokes the method on the object and, if necessary, sends the result back to the connection that made the invocation * request. This method is invoked on the update thread of the {@link EndPoint} for this ObjectSpace and can be overridden to * perform invocations on a different thread. * @param connection The remote side of this connection requested the invocation. */ protected void invoke (Connection connection, Object target, InvokeMethod invokeMethod) { if (DEBUG) { String argString = ""; if (invokeMethod.args != null) { argString = Arrays.deepToString(invokeMethod.args); argString = argString.substring(1, argString.length() - 1); } debug("kryonet", connection + " received: " + target.getClass().getSimpleName() + "#" + invokeMethod.method.getName() + "(" + argString + ")"); } Object result; Method method = invokeMethod.method; try { result = method.invoke(target, invokeMethod.args); } catch (Exception ex) { throw new RuntimeException("Error invoking method: " + method.getDeclaringClass().getName() + "." + method.getName(), ex); } byte responseID = invokeMethod.responseID; if (method.getReturnType() == void.class || responseID == 0) return; InvokeMethodResult invokeMethodResult = new InvokeMethodResult(); invokeMethodResult.objectID = invokeMethod.objectID; invokeMethodResult.responseID = responseID; invokeMethodResult.result = result; int length = connection.sendTCP(invokeMethodResult); if (DEBUG) debug("kryonet", connection + " sent: " + result + " (" + length + ")"); } /** * Identical to {@link #getRemoteObject(Connection, int, Class...)} except returns the object as the specified interface type. * The returned object still implements {@link RemoteObject}. */ static public <T> T getRemoteObject (final Connection connection, int objectID, Class<T> iface) { return (T)getRemoteObject(connection, objectID, new Class[] {iface}); } /** * Returns a proxy object that implements the specified interfaces. Methods invoked on the proxy object will be invoked * remotely on the object with the specified ID in the ObjectSpace for the specified connection. * <p> * Methods that return a value will throw {@link TimeoutException} if the response is not received with the * {@link RemoteObject#setResponseTimeout(int) response timeout}. * <p> * If {@link RemoteObject#setNonBlocking(boolean, boolean) non-blocking} is false (the default), then methods that return a * value must not be called from the update thread for the connection. An exception will be thrown if this occurs. Methods with * a void return value can be called on the update thread. * <p> * If a proxy returned from this method is part of an object graph sent over the network, the object graph on the receiving * side will have the proxy object replaced with the registered object. * @see RemoteObject */ static public RemoteObject getRemoteObject (Connection connection, int objectID, Class... ifaces) { if (connection == null) throw new IllegalArgumentException("connection cannot be null."); if (ifaces == null) throw new IllegalArgumentException("ifaces cannot be null."); Class[] temp = new Class[ifaces.length + 1]; temp[0] = RemoteObject.class; System.arraycopy(ifaces, 0, temp, 1, ifaces.length); return (RemoteObject)Proxy.newProxyInstance(ObjectSpace.class.getClassLoader(), temp, new RemoteInvocationHandler( connection, objectID)); } /** * Handles network communication when methods are invoked on a proxy. */ static private class RemoteInvocationHandler implements InvocationHandler { private final Connection connection; final int objectID; private int timeoutMillis = 3000; private boolean nonBlocking, ignoreResponses; private Byte lastResponseID; final ArrayList<InvokeMethodResult> responseQueue = new ArrayList(); private byte nextResponseID = 1; private Listener responseListener; public RemoteInvocationHandler (Connection connection, final int objectID) { super(); this.connection = connection; this.objectID = objectID; responseListener = new Listener() { public void received (Connection connection, Object object) { if (!(object instanceof InvokeMethodResult)) return; InvokeMethodResult invokeMethodResult = (InvokeMethodResult)object; if (invokeMethodResult.objectID != objectID) return; synchronized (responseQueue) { responseQueue.add(invokeMethodResult); responseQueue.notifyAll(); } } public void disconnected (Connection connection) { close(); } }; connection.addListener(responseListener); } public Object invoke (Object proxy, Method method, Object[] args) { if (method.getDeclaringClass() == RemoteObject.class) { String name = method.getName(); if (name.equals("close")) { close(); return null; } else if (name.equals("setResponseTimeout")) { timeoutMillis = (Integer)args[0]; return null; } else if (name.equals("setNonBlocking")) { nonBlocking = (Boolean)args[0]; ignoreResponses = (Boolean)args[1]; return null; } else if (name.equals("waitForLastResponse")) { if (lastResponseID == null) throw new IllegalStateException("There is no last response to wait for."); return waitForResponse(lastResponseID); } else if (name.equals("getLastResponseID")) { if (lastResponseID == null) throw new IllegalStateException("There is no last response ID."); return lastResponseID; } else if (name.equals("waitForResponse")) { if (ignoreResponses) throw new IllegalStateException("This RemoteObject is configured to ignore all responses."); return waitForResponse((Byte)args[0]); } } InvokeMethod invokeMethod = new InvokeMethod(); invokeMethod.objectID = objectID; invokeMethod.method = method; invokeMethod.args = args; boolean hasReturnValue = method.getReturnType() != void.class; if (hasReturnValue && !ignoreResponses) { byte responseID = nextResponseID++; if (nextResponseID == 0) nextResponseID++; // Zero means don't send back a response. invokeMethod.responseID = responseID; } int length = connection.sendTCP(invokeMethod); if (DEBUG) { String argString = ""; if (args != null) { argString = Arrays.deepToString(args); argString = argString.substring(1, argString.length() - 1); } debug("kryonet", connection + " sent: " + method.getDeclaringClass().getSimpleName() + "#" + method.getName() + "(" + argString + ") (" + length + ")"); } if (!hasReturnValue) return null; if (nonBlocking) { if (!ignoreResponses) lastResponseID = invokeMethod.responseID; Class returnType = method.getReturnType(); if (returnType.isPrimitive()) { if (returnType == int.class) return 0; if (returnType == boolean.class) return Boolean.FALSE; if (returnType == float.class) return 0f; if (returnType == char.class) return (char)0; if (returnType == long.class) return 0l; if (returnType == short.class) return (short)0; if (returnType == byte.class) return (byte)0; if (returnType == double.class) return 0d; } return null; } try { return waitForResponse(invokeMethod.responseID); } catch (TimeoutException ex) { throw new TimeoutException("Response timed out: " + method.getDeclaringClass().getName() + "." + method.getName()); } } private Object waitForResponse (int responseID) { if (connection.getEndPoint().getUpdateThread() == Thread.currentThread()) throw new IllegalStateException("Cannot wait for an RMI response on the connection's update thread."); long endTime = System.currentTimeMillis() + timeoutMillis; synchronized (responseQueue) { while (true) { int remaining = (int)(endTime - System.currentTimeMillis()); for (int i = responseQueue.size() - 1; i >= 0; i++) { InvokeMethodResult invokeMethodResult = responseQueue.get(i); if (invokeMethodResult.responseID == responseID) { responseQueue.remove(invokeMethodResult); lastResponseID = null; return invokeMethodResult.result; } } if (remaining <= 0) throw new TimeoutException("Response timed out."); try { responseQueue.wait(remaining); } catch (InterruptedException ignored) { } } } } void close () { connection.removeListener(responseListener); } } /** * Internal message to invoke methods remotely. */ static public class InvokeMethod implements FrameworkMessage, CustomSerialization { public int objectID; public Method method; public Object[] args; public byte responseID; public void writeObjectData (Kryo kryo, ByteBuffer buffer) { IntSerializer.put(buffer, objectID, true); int methodClassID = kryo.getRegisteredClass(method.getDeclaringClass()).getID(); IntSerializer.put(buffer, methodClassID, true); Method[] methods = getMethods(method.getDeclaringClass()); for (int i = 0, n = methods.length; i < n; i++) { if (methods[i].equals(method)) { buffer.put((byte)i); break; } } int argCount = method.getParameterTypes().length; if (argCount > 0) { ArraySerializer serializer = new ArraySerializer(kryo); serializer.setLength(argCount); serializer.writeObjectData(buffer, args); } if (method.getReturnType() != void.class) buffer.put(responseID); } public void readObjectData (Kryo kryo, ByteBuffer buffer) { objectID = IntSerializer.get(buffer, true); int methodClassID = IntSerializer.get(buffer, true); Class methodClass = kryo.getRegisteredClass(methodClassID).getType(); byte methodIndex = buffer.get(); try { method = getMethods(methodClass)[methodIndex]; } catch (IndexOutOfBoundsException ex) { throw new SerializationException("Invalid method index " + methodIndex + " for class: " + methodClass.getName()); } int argCount = method.getParameterTypes().length; if (argCount > 0) { ArraySerializer serializer = new ArraySerializer(kryo); serializer.setLength(argCount); args = serializer.readObjectData(buffer, Object[].class); } if (method.getReturnType() != void.class) responseID = buffer.get(); } } /** * Internal message to return the result of a remotely invoked method. */ static public class InvokeMethodResult implements FrameworkMessage { public int objectID; public byte responseID; public Object result; } static Method[] getMethods (Class type) { Method[] cachedMethods = methodCache.get(type); if (cachedMethods != null) return cachedMethods; ArrayList<Method> allMethods = new ArrayList(); Class nextClass = type; while (nextClass != null && nextClass != Object.class) { Collections.addAll(allMethods, nextClass.getDeclaredMethods()); nextClass = nextClass.getSuperclass(); } PriorityQueue<Method> methods = new PriorityQueue(Math.max(1, allMethods.size()), new Comparator<Method>() { public int compare (Method o1, Method o2) { // Methods are sorted so they can be represented as an index. int diff = o1.getName().compareTo(o2.getName()); if (diff != 0) return diff; Class[] argTypes1 = o1.getParameterTypes(); Class[] argTypes2 = o2.getParameterTypes(); if (argTypes1.length > argTypes2.length) return 1; if (argTypes1.length < argTypes2.length) return -1; for (int i = 0; i < argTypes1.length; i++) { diff = argTypes1[i].getName().compareTo(argTypes2[i].getName()); if (diff != 0) return diff; } throw new RuntimeException("Two methods with same signature!"); // Impossible. } }); for (int i = 0, n = allMethods.size(); i < n; i++) { Method method = allMethods.get(i); int modifiers = method.getModifiers(); if (Modifier.isStatic(modifiers)) continue; if (Modifier.isPrivate(modifiers)) continue; if (method.isSynthetic()) continue; methods.add(method); } int n = methods.size(); cachedMethods = new Method[n]; for (int i = 0; i < n; i++) cachedMethods[i] = methods.poll(); methodCache.put(type, cachedMethods); return cachedMethods; } /** * Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs to. */ static Object getRegisteredObject (Connection connection, int objectID) { ObjectSpace[] instances = ObjectSpace.instances; for (int i = 0, n = instances.length; i < n; i++) { ObjectSpace objectSpace = instances[i]; // Check if the connection is in this ObjectSpace. Connection[] connections = objectSpace.connections; for (int j = 0; j < connections.length; j++) { if (connections[j] != connection) continue; // Find an object with the objectID. Object object = objectSpace.idToObject.get(objectID); if (object != null) return object; } } return null; } /** * Registers the classes needed to use ObjectSpaces. This should be called before any connections are opened. * @see EndPoint#getKryo() * @see Kryo#register(Class, Serializer) */ static public void registerClasses (Kryo kryo) { kryo.register(Object[].class); kryo.register(InvokeMethod.class); FieldSerializer serializer = (FieldSerializer)kryo.register(InvokeMethodResult.class).getSerializer(); serializer.getField("objectID").setClass(int.class, new IntSerializer(true)); kryo.register(InvocationHandler.class, new Serializer() { public void writeObjectData (ByteBuffer buffer, Object object) { RemoteInvocationHandler handler = (RemoteInvocationHandler)Proxy.getInvocationHandler(object); IntSerializer.put(buffer, handler.objectID, true); } public <T> T readObjectData (ByteBuffer buffer, Class<T> type) { int objectID = IntSerializer.get(buffer, true); Connection connection = (Connection)Kryo.getContext().get("connection"); Object object = getRegisteredObject(connection, objectID); if (WARN && object == null) warn("kryonet", "Unknown object ID " + objectID + " for connection: " + connection); return (T)object; } }); } }
package org.lenskit.cli.util; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import net.sourceforge.argparse4j.inf.ArgumentGroup; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup; import net.sourceforge.argparse4j.inf.Namespace; import org.lenskit.LenskitConfiguration; import org.lenskit.data.dao.DataAccessException; import org.lenskit.data.dao.DataAccessObject; import org.lenskit.data.dao.file.DelimitedColumnEntityFormat; import org.lenskit.data.dao.file.StaticDataSource; import org.lenskit.data.dao.file.TextEntitySource; import org.lenskit.data.entities.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; public class InputData { private static final Logger logger = LoggerFactory.getLogger(InputData.class); private final Namespace options; private final ScriptEnvironment environment; public InputData(ScriptEnvironment env, Namespace opts) { environment = env; options = opts; } @Nullable public StaticDataSource getSource() { File sourceFile = options.get("data_source"); if (sourceFile != null) { ClassLoader cl = null; if (environment != null) { cl = environment.getClassLoader(); } return loadDataSource(sourceFile, cl); } StaticDataSource source = new StaticDataSource(); TextEntitySource entities = new TextEntitySource(); DelimitedColumnEntityFormat format = new DelimitedColumnEntityFormat(); format.setEntityType(CommonTypes.RATING); format.addColumns(CommonAttributes.USER_ID, CommonAttributes.ITEM_ID, CommonAttributes.RATING, CommonAttributes.TIMESTAMP); String type = options.get("event_type"); if (type != null) { EntityType etype = EntityType.forName(type); format.setEntityType(etype); EntityDefaults defaults = EntityDefaults.lookup(etype); if (defaults == null) { logger.warn("no defaults found for entity type {}", type); } else { format.clearColumns(); for (TypedName<?> col: defaults.getDefaultColumns()) { format.addColumn(col); } } } Integer header = options.get("header_lines"); if (header != null) { format.setHeaderLines(header); } File ratingFile = options.get("csv_file"); if (ratingFile != null) { format.setDelimiter(","); entities.setFile(ratingFile.toPath()); } ratingFile = options.get("tsv_file"); if (ratingFile != null) { format.setDelimiter("\t"); entities.setFile(ratingFile.toPath()); } ratingFile = options.get("ratings_file"); if (ratingFile == null) { ratingFile = options.get("events_file"); } if (ratingFile != null) { String delim = options.getString("delimiter"); format.setDelimiter(delim); entities.setFile(ratingFile.toPath()); } if (entities.getURL() == null) { // we found no configuration return null; } entities.setFormat(format); source.addSource(entities); File nameFile = options.get("item_names"); if (nameFile != null) { TextEntitySource itemSource = new TextEntitySource(); DelimitedColumnEntityFormat itemFormat = new DelimitedColumnEntityFormat(); itemFormat.setDelimiter(","); itemFormat.setEntityType(CommonTypes.ITEM); itemFormat.addColumns(CommonAttributes.ENTITY_ID, CommonAttributes.NAME); itemSource.setFormat(itemFormat); itemSource.setFile(nameFile.toPath()); source.addSource(itemSource); } return source; } private StaticDataSource loadDataSource(File sourceFile, ClassLoader loader) { JsonNode node; JsonFactory factory = new YAMLFactory(); ObjectMapper mapper = new ObjectMapper(factory); try { node = mapper.readTree(sourceFile); StaticDataSource provider = StaticDataSource.fromJSON(node, sourceFile.toURI()); return provider; } catch (IOException e) { logger.error("error loading " + sourceFile, e); throw new DataAccessException("error loading " + sourceFile, e); } } /** * Get the data access object from the input data. * @return The data access object. */ @Nullable public DataAccessObject getDAO() { StaticDataSource source = getSource(); return source != null ? source.get() : null; } @Nonnull public LenskitConfiguration getConfiguration() { StaticDataSource src = getSource(); LenskitConfiguration config = new LenskitConfiguration(); if (src != null) { config.bind(DataAccessObject.class).toProvider(src); } return config; } @Override public String toString() { StaticDataSource src = getSource(); return (src == null) ? "null" : src.toString(); } public static void configureArguments(ArgumentParser parser) { configureArguments(parser, false); } public static void configureArguments(ArgumentParser parser, boolean required) { MutuallyExclusiveGroup group = parser.addMutuallyExclusiveGroup("input data") .description("Specify the input data for the command.") .required(required); ArgumentGroup options = parser.addArgumentGroup("input options") .description("Additional options for input data."); group.addArgument("--csv-file") .type(File.class) .metavar("FILE") .help("read from comma-separated FILE"); group.addArgument("--tsv-file") .type(File.class) .metavar("FILE") .help("read from tab-separated FILE"); group.addArgument("--ratings-file") .type(File.class) .metavar("FILE") .help("read from delimited text FILE"); group.addArgument("--entities-file") .type(File.class) .metavar("FILE") .help("read from delimited text FILE"); options.addArgument("-d", "--delimiter") .setDefault(",") .metavar("DELIM") .help("input file is delimited by DELIM"); options.addArgument("-H", "--header-lines") .type(Integer.class) .setDefault(0) .metavar("N") .help("skip N header lines at top of input file"); options.addArgument("-t", "--input-entity-type", "--event-type") .setDefault("rating") .metavar("TYPE") .help("read entitites of type TYPE from input file"); options.addArgument("--item-names") .type(File.class) .metavar("FILE") .help("Read item names from CSV file FILE"); group.addArgument("--data-source") .type(File.class) .metavar("FILE") .help("read a data source specification from FILE"); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class MainRobot extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotShoot.initialize(); RobotActuators.initialize(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { runCompressor(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { //runCompressor(); RobotShoot.update(); RobotShoot.testShooter(); } /** * This function is called periodically during test mode */ public void testPeriodic() { } private void runCompressor() { if (!RobotSensors.pressureSwitch.get()) { RobotActuators.compressor.set(Relay.Value.kOn); } else { RobotActuators.compressor.set(Relay.Value.kOff); } } }
package com.parc.ccn.network.daemons.repo; import java.io.PrintStream; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import com.parc.ccn.Library; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.query.Interest; import com.parc.ccn.data.util.DataUtils; import com.parc.ccn.library.CCNNameEnumerator; import com.parc.ccn.library.profiles.VersioningProfile; import com.parc.ccn.network.daemons.repo.Repository.NameEnumerationResponse; public class ContentTree { /** * ContentFileRef * @author jthornto, rbraynar, rasmusse * */ public class ContentFileRef { int id; long offset; } public interface ContentGetter { public ContentObject get(ContentFileRef ref); } /** * TreeNode is the data structure representing one * node of a tree which may have children and/or content. * Every child has a distinct name (it's component) but * there may be multiple content objects ending with the * same component (i.e. having same content digest at end * but presumably different publisher etc. that is not * visible in this tree) * @author jthornto * */ public class TreeNode { byte[] component; // name of this node in the tree, null for root only // oneChild is special case when there is only // a single child (to save obj overhead). // either oneChild or children should be null TreeNode oneChild; SortedSet<TreeNode> children; // oneContent is special case when there is only // a single content object here (to save obj overhead). // either oneContent or content should be null ContentFileRef oneContent; List<ContentFileRef> content; long timestamp; boolean interestFlag = false; public boolean compEquals(byte[] other) { return DataUtils.compare(other, this.component) == 0; } public TreeNode getChild(byte[] component) { if (null != oneChild) { if (oneChild.compEquals(component)) { return oneChild; } } else if (null != children) { TreeNode testNode = new TreeNode(); testNode.component = component; SortedSet<TreeNode> tailSet = children.tailSet(testNode); if (tailSet.size() > 0) { if (tailSet.first().compEquals(component)) return tailSet.first(); } } return null; } public String toString(){ String s = ""; if(component==null) s = "root"; else{ s = ContentName.componentPrintURI(component); } if(oneChild!=null){ //there is only one child s+= " oneChild: "+ContentName.componentPrintURI(component); } else if(children!=null){ s+= " children: "; for(TreeNode t: children){ //append each child to string s+=" "+ContentName.componentPrintURI(t.component); //s+=new String(t.component)+" "; } } else s+=" oneChild and children were null"; return s; } } public class TreeNodeComparator implements Comparator<TreeNode> { public int compare(TreeNode o1, TreeNode o2) { return DataUtils.compare(o1.component, o2.component); } } protected TreeNode root; public ContentTree() { root = new TreeNode(); root.component = null; // Only the root has a null value } /** * Insert entry for the given ContentObject. * @param content * @param ref * @param ts * @param getter * @return - true if content is not exact duplicate of existing content. */ public boolean insert(ContentObject content, ContentFileRef ref, long ts, ContentGetter getter, NameEnumerationResponse ner) { final ContentName name = new ContentName(content.name(), content.contentDigest()); Library.logger().fine("inserting content: "+name.toString()); TreeNode node = root; // starting point assert(null != root); boolean added = false; for (byte[] component : name.components()) { synchronized(node) { //Library.logger().finest("getting node for component: "+new String(component)); TreeNode child = node.getChild(component); if (null == child) { Library.logger().finest("child was null: adding here"); // add it added = true; child = new TreeNode(); child.component = component; if (null == node.oneChild && null == node.children) { // This is first and only child of current node node.oneChild = child; } else if (null == node.oneChild) { // Multiple children already, just add this one to current node node.children.add(child); } else { // Second child in current node, need to switch to list node.children = new TreeSet<TreeNode>(new TreeNodeComparator()); node.children.add(node.oneChild); node.children.add(child); node.oneChild = null; } node.timestamp = ts; } if(node.interestFlag && (ner==null || ner.prefix==null)){ //we have added something to this node and someone was interested //we need to get the child names and the prefix to send back Library.logger().info("we added at least one child, need to send a name enumeration response"); ContentName prefix = name.cut(component); prefix = new ContentName(prefix, CCNNameEnumerator.NEMARKER); //prefix = VersioningProfile.addVersion(prefix, new Timestamp(node.timestamp)); Library.logger().info("prefix for NEResponse: "+prefix); ArrayList<ContentName> names = new ArrayList<ContentName>(); //the parent has children we need to return ContentName c = new ContentName(); if(node.oneChild!=null){ names.add(new ContentName(c, node.oneChild.component)); } else{ if(node.children!=null){ for(TreeNode ch:node.children) names.add(new ContentName(c, ch.component)); } } ner.setPrefix(prefix); ner.setNameList(names); ner.setTimestamp(new Timestamp(node.timestamp)); Library.logger().info("resetting interestFlag to false"); node.interestFlag = false; } //Library.logger().finest("child was not null: moving down the tree"); node = child; } } // Check for duplicate content if (!added) { if (null != node.oneContent) { ContentObject prev = getter.get(node.oneContent); if (null != prev && content.equals(prev)) return false; } else if (null != node.content) { for (ContentFileRef oldRef : node.content) { ContentObject prev = getter.get(oldRef); if (null != prev && content.equals(prev)) return false; } } } // At conclusion of this loop, node must be holding the last node for this name // so we insert the ref there if (null == node.oneContent && null == node.content) { // This is first and only content at this leaf node.oneContent = ref; } else if (null == node.oneContent) { // Multiple content already at this node, add this one node.content.add(ref); } else { // Second content at current node, need to switch to list node.content = new ArrayList<ContentFileRef>(); node.content.add(node.oneContent); node.content.add(ref); node.oneContent = null; } Library.logger().fine("Inserted: " + content.name()); return true; } protected TreeNode lookupNode(ContentName name, int count) { TreeNode node = root; // starting point assert(null != root); if (count < 1) { return node; } for (byte[] component : name.components()) { synchronized(node) { TreeNode child = node.getChild(component); if (null == child) { // Mismatch, no child for the given component so nothing under this name return null; } node = child; count if (count < 1) { break; } } } return node; } /** * Return the content objects with exactly the given name * @param name * @param count * @return */ protected final List<ContentFileRef> lookup(ContentName name) { TreeNode node = lookupNode(name, name.count()); if (null != node) { if (null != node.oneContent) { ArrayList<ContentFileRef> result = new ArrayList<ContentFileRef>(); result.add(node.oneContent); return result; } else { return node.content; } } else { return null; } } public void dumpNamesTree(PrintStream output, int maxNodeLen) { assert(null != root); assert(null != output); output.println("Dumping tree of names of indexed content at " + new Date().toString()); if (maxNodeLen > 0) { output.println("Node names truncated to max " + maxNodeLen + " characters"); } dumpRecurse(output, root, "", maxNodeLen); } // Note: this is not thread-safe against everything else going on. protected void dumpRecurse(PrintStream output, TreeNode node, String indent, int maxNodeLen) { String myname = null; if (null == node.component) { // Special case of root myname = "/"; } else { myname = ContentName.componentPrintURI(node.component); if (maxNodeLen > 0 && myname.length() > (maxNodeLen - 3)) { myname = "<" + myname.substring(0,maxNodeLen-4) + "...>"; } } int mylen = myname.length(); output.print(myname); if (null != node.oneChild) { output.print(" dumpRecurse(output, node.oneChild, String.format("%s%" + mylen + "s ", indent, ""), maxNodeLen); } else if (null != node.children) { int count = 1; int last = node.children.size(); for (TreeNode child : node.children) { if (1 == count) { // First child output.print("-+-"); dumpRecurse(output, child, String.format("%s%" + mylen + "s | ", indent, ""), maxNodeLen); } else if (last == count) { // Last child output.println(); output.printf("%s%" + mylen + "s +-", indent, ""); dumpRecurse(output, child, String.format("%s%" + mylen + "s ", indent, ""), maxNodeLen); } else { // Interior child delimiter output.println(); output.printf("%s%" + mylen + "s |-", indent, ""); dumpRecurse(output, child, String.format("%s%" + mylen + "s | ", indent, ""), maxNodeLen); } count++; } } } /** * * @param interest the interest to match * @param matchlen total number of components required in final answer or -1 if not specified * @param node the node rooting a subtree to search * @param nodeName the full name of this node from the root up to and its component * @param depth the length of name of node including its component (number of components) * @param getter a handler to pull actual ContentObjects for final match testing. * @return */ protected final ContentObject leftSearch(Interest interest, int matchlen, TreeNode node, ContentName nodeName, int depth, boolean anyOK, ContentGetter getter) { if ( (nodeName.count() >= 0) && (matchlen == -1 || matchlen == depth)) { if (null != node.oneContent || null != node.content) { // Since the name INCLUDES digest component and the Interest.matches() convention for name // matching is that the name DOES NOT include digest component (conforming to the convention // for ContentObject.name() that the digest is not present) we must REMOVE the content // digest first or this test will not always be correct ContentName digestFreeName = new ContentName(nodeName.count()-1, nodeName.components()); Interest publisherFreeInterest = interest.clone(); publisherFreeInterest.publisherID(null); if (publisherFreeInterest.matches(digestFreeName, null)) { List<ContentFileRef> content = null; synchronized(node) { if (null != node.oneContent) { content = new ArrayList<ContentFileRef>(); content.add(node.oneContent); } else { assert(null != node.content); content = new ArrayList<ContentFileRef>(node.content); } } for (ContentFileRef ref : content) { ContentObject cand = getter.get(ref); if (interest.matches(cand)) { return cand; } } } } } // Now search children if applicable and if any if (matchlen != -1 && matchlen <= depth || (node.children==null && node.oneChild==null)) { // Any child would make the total name longer than requested so no point in // checking children return null; } SortedSet<TreeNode> children = null; synchronized(node) { if (null != node.oneChild) { children = new TreeSet<TreeNode>(); // Don't bother with comparator, will only hold one element children.add(node.oneChild); } else { children = new TreeSet<TreeNode>(new TreeNodeComparator()); children.addAll(node.children); } } if (null != children) { byte[] interestComp = interest.name().component(depth); for (TreeNode child : children) { int comp = DataUtils.compare(child.component, interestComp); //if (null == interestComp || DataUtils.compare(child.component, interestComp) >= 0) { if (anyOK || comp >= 0) { ContentObject result = null; result = leftSearch(interest, matchlen, child, new ContentName(nodeName, child.component), depth+1, comp > 0, getter); if (null != result) { return result; } } } } // No match found return null; } protected void getSubtreeNodes(TreeNode node, List<TreeNode> result, Integer components) { result.add(node); if (components != null) { components if (components == 0) return; } synchronized(node) { if (null != node.oneChild) { getSubtreeNodes(node.oneChild, result, components); } else if (null != node.children) { for (TreeNode child : node.children) { getSubtreeNodes(child, result, components); } } } } protected final ContentObject rightSearch(Interest interest, int matchlen, TreeNode node, ContentName nodeName, int depth, ContentGetter getter) { // A shortcut compared to leftSearch() for moment, just accumulate all options in forward order // and then go through them in reverse direction and do full test // ToDo This is very inefficient for all but the most optimal case where the last thing in the // subtree happens to be a perfect match ArrayList<TreeNode> options = new ArrayList<TreeNode>(); Integer totalComponents = null; if (interest.minSuffixComponents() != null) totalComponents = interest.name().count() + interest.minSuffixComponents(); getSubtreeNodes(node, options, totalComponents); for (int i = options.size()-1; i >= 0 ; i TreeNode candidate = options.get(i); if (null != candidate.oneContent || null != candidate.content) { List<ContentFileRef> content = null; synchronized(candidate) { if (null != candidate.oneContent) { content = new ArrayList<ContentFileRef>(); content.add(candidate.oneContent); } else { assert(null != node.content); content = new ArrayList<ContentFileRef>(candidate.content); } } for (ContentFileRef ref : content) { ContentObject cand = getter.get(ref); if (cand!=null && interest.matches(cand)) { return cand; } } } } return null; } public final NameEnumerationResponse getNamesWithPrefix(Interest interest, ContentGetter getter) { ArrayList<ContentName> names = new ArrayList<ContentName>(); //first chop off NE marker ContentName prefix = interest.name().cut(CCNNameEnumerator.NEMARKER); Library.logger().fine("checking for content names under: "+prefix); TreeNode parent = lookupNode(prefix, prefix.count()); if (parent!=null) { //check if we should respond... if (interest.matches(VersioningProfile.addVersion(new ContentName(prefix, CCNNameEnumerator.NEMARKER), new Timestamp(parent.timestamp)), null)) { Library.logger().info("the new version is a match with the interest! we should respond"); } else { Library.logger().info("the new version doesn't match, no response needed"); parent.interestFlag = true; return null; } //the parent has children we need to return ContentName c = new ContentName(); if (parent.oneChild!=null) { names.add(new ContentName(c, parent.oneChild.component)); } else { if (parent.children!=null) { for (TreeNode ch:parent.children) names.add(new ContentName(c, ch.component)); } } if (names.size()>0) Library.logger().finer("sending back "+names.size()+" names in the enumeration response"); parent.interestFlag = false; return new NameEnumerationResponse(interest.name(), names, new Timestamp(parent.timestamp)); } return null; } public final ContentObject get(Interest interest, ContentGetter getter) { Integer addl = interest.maxSuffixComponents(); int ncc = interest.name().count(); if (null != addl && addl.intValue() == 0) { // Query is for exact match to full name with digest, no additional components List<ContentFileRef> found = lookup(interest.name()); if (found!=null) { for (ContentFileRef ref : found) { ContentObject cand = getter.get(ref); if (null != cand) { if (interest.matches(cand)) { return cand; } } } } } else { //TreeNode prefixRoot = lookupNode(interest.name(), interest.nameComponentCount()); TreeNode prefixRoot = lookupNode(interest.name(), ncc); if (prefixRoot == null) { //Library.logger().info("For: " + interest.name() + " the prefix root is null... returning null"); return null; } if (null != interest.orderPreference() && (interest.orderPreference() & (Interest.ORDER_PREFERENCE_RIGHT | Interest.ORDER_PREFERENCE_ORDER_NAME)) == (Interest.ORDER_PREFERENCE_RIGHT | Interest.ORDER_PREFERENCE_ORDER_NAME)) { // Traverse to find latest match return rightSearch(interest, (null == addl) ? -1 : addl + ncc, prefixRoot, new ContentName(ncc, interest.name().components()), ncc, getter); } else{ return leftSearch(interest, (null == addl) ? -1 : addl + ncc, prefixRoot, new ContentName(ncc, interest.name().components()), ncc, null == interest.orderPreference() || (interest.orderPreference() & (Interest.ORDER_PREFERENCE_RIGHT | Interest.ORDER_PREFERENCE_ORDER_NAME)) != (Interest.ORDER_PREFERENCE_RIGHT | Interest.ORDER_PREFERENCE_ORDER_NAME), getter); } /** original version // Now we need to iterate over content at or below this node to find best match //if ((interest.orderPreference() & (Interest.ORDER_PREFERENCE_LEFT | Interest.ORDER_PREFERENCE_ORDER_NAME)) // == (Interest.ORDER_PREFERENCE_LEFT | Interest.ORDER_PREFERENCE_ORDER_NAME)) { if ((null!=interest.orderPreference()) && ((interest.orderPreference() & (Interest.ORDER_PREFERENCE_LEFT | Interest.ORDER_PREFERENCE_ORDER_NAME)) == (Interest.ORDER_PREFERENCE_LEFT | Interest.ORDER_PREFERENCE_ORDER_NAME))) { // Traverse to find earliest match //leftSearch(interest, (null == addl) ? -1 : addl + interest.nameComponentCount(), //prefixRoot, new ContentName(interest.nameComponentCount(), interest.name().components()), //interest.nameComponentCount(), getter); System.out.println("going to do leftSearch for earliest. Interest: "+interest.toString()); return leftSearch(interest, (null == addl) ? -1 : addl + ncc, prefixRoot, new ContentName(ncc, interest.name().components()), ncc, getter); } else { // Traverse to find latest match //rightSearch(interest, (null == addl) ? -1 : addl + interest.nameComponentCount(), // prefixRoot, new ContentName(interest.nameComponentCount(), interest.name().components()), // interest.nameComponentCount(), getter); System.out.println("going to do rightSearch for latest. Interest: "+interest.name().toString()); return rightSearch(interest, (null == addl) ? -1 : addl + ncc, prefixRoot, new ContentName(ncc, interest.name().components()), ncc, getter); } **/ } return null; } }
package josuezelaya_lab3; import java.awt.Color; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Scanner; import javax.swing.JOptionPane; public class JosueZelaya_Lab3 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); ArrayList<Carro> carros = new ArrayList(); ArrayList<Personas> personas = new ArrayList(); String opcion = " "; while (!opcion.equals("e")) { opcion = JOptionPane.showInputDialog("Menu\n" + "a- Agregar\n" + "b- Modificar\n" + "c- Eliminar\n" + "d- Ventas\n" + "e- Salir!\n"); if (opcion.equalsIgnoreCase("a")) { String opcion2 = " "; while (!opcion2.equals("c")) { opcion2 = JOptionPane.showInputDialog("\n" + "Que Desea Agregar?\n" + "a. Carros\n" + "b. Personas\n" + "c. Salir\n"); if (opcion2.equalsIgnoreCase("a")) {//carros String opcion3 = " "; while (!opcion3.equals("e")) { opcion3 = JOptionPane.showInputDialog("Que Modelo desea?\n" + "a.Maybach\n" + "b.Morgan Aero 8\n" + "c.Fisker Automotive\n" + "d.Tramontana\n" + "e.Salir\n"); if (opcion3.equalsIgnoreCase("a")) { int llantas_respuesto = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de llantas de respuestos[1 o 2]: ")); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (velocidad_maxima >= 155 && velocidad_maxima <= 160 && km_galon >= 50 && km_galon <= 55 && precio_venta >= 400000 && precio_venta <= 600000) { carros.add(new Maybach(llantas_respuesto, serie, fecha, color, marca_llantas, polarizado, velocidad_maxima, km_galon, precio_venta)); } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } if (opcion3.equalsIgnoreCase("b")) { String convertible = JOptionPane.showInputDialog("Ingrese si es convertible o no[si,no]: "); String cabina = JOptionPane.showInputDialog("Ingrese si es cabina unica o doble: "); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (velocidad_maxima >= 140 && velocidad_maxima <= 145 && km_galon >= 35 && km_galon <= 40 && precio_venta >= 500000 && precio_venta <= 700000) { carros.add(new Morgan_Aero8(convertible, cabina, serie, fecha, color, marca_llantas, polarizado, velocidad_maxima, km_galon, precio_venta)); } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } if (opcion3.equalsIgnoreCase("c")) { String tipo = JOptionPane.showInputDialog("Ingrese si es camioneta o turismo: "); String convertible = JOptionPane.showInputDialog("Ingrese si es convertible o no lo es[si,,no]: "); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (velocidad_maxima >= 160 && velocidad_maxima <= 165 && km_galon >= 55 && km_galon <= 60 && precio_venta >= 450000 && precio_venta <= 650000) { carros.add(new Fisker_Automotive(tipo, convertible, serie, fecha, color, marca_llantas, polarizado, velocidad_maxima, km_galon, precio_venta)); } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } if (opcion3.equalsIgnoreCase("d")) { double peso = Double.parseDouble(JOptionPane.showInputDialog("Ingrese peso: ")); double transmision = Double.parseDouble(JOptionPane.showInputDialog("Ingrese transmision de 6 a 7 velocidades: ")); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (peso >= 1276 && peso <= 1376 && velocidad_maxima >= 175 && velocidad_maxima <= 180 && km_galon >= 50 && km_galon <= 55 && precio_venta >= 800000 && precio_venta <= 1000000) { carros.add(new Tramontana(peso, transmision, serie, fecha, color, marca_llantas, polarizado, velocidad_maxima, km_galon, precio_venta)); } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } } } if (opcion2.equals("b")) {//personas String opcion4 = " "; while (!opcion.equalsIgnoreCase("c")) { opcion4 = JOptionPane.showInputDialog("Que tipo de persona desea Agregar:? \n" + "a. Empleados\n" + "b. Clientes\n" + "c. Salir!\n"); if (opcion4.equalsIgnoreCase("a")) { String nombre = JOptionPane.showInputDialog("Ingrese Nombre: "); double id = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su ID: ")); double edad = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su edad: ")); double altura = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su altura: ")); double peso = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su peso: ")); int horas = Integer.parseInt(JOptionPane.showInputDialog("Ingrese sus horas trabajadas: ")); personas.add(new Empleados(horas, new Clientes(), nombre, id, edad, altura, peso)); // Empleados nuevo_empleado=new Empleados(horas,new Clientes(),nombre,id,edad,altura,peso); } if (opcion4.equalsIgnoreCase("b")) { String nombre = JOptionPane.showInputDialog("Ingrese Nombre: "); double id = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su ID: ")); double edad = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su edad: ")); double altura = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su altura: ")); double peso = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su peso: ")); int dinero = Integer.parseInt(JOptionPane.showInputDialog("Ingrese su dinero que lleva: ")); personas.add(new Clientes(dinero, nombre, id, edad, altura, peso)); // Clientes nuevo_cliente=new Clientes(dinero,nombre,id,edad,altura,peso); } } } } } if (opcion.equalsIgnoreCase("b")) { String opcion2 = " "; while (!opcion2.equals("c")) { opcion2 = JOptionPane.showInputDialog("\n" + "Que Desea Modificar?\n" + "a. Carros\n" + "b. Personas\n" + "c. Salir\n"); if (opcion2.equalsIgnoreCase("a")) {//carros String opcion3 = " "; while (!opcion3.equals("e")) { opcion3 = JOptionPane.showInputDialog("Que Modelo desea?\n" + "a.Maybach\n" + "b.Morgan Aero 8\n" + "c.Fisker Automotive\n" + "d.Tramontana\n" + "e.Salir\n"); if (opcion3.equalsIgnoreCase("a")) { int posicion = Integer.parseInt(JOptionPane.showInputDialog("Ingrese posicion a modificar: ")); int llantas_respuesto = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de llantas de respuestos[1 o 2]: ")); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (velocidad_maxima >= 155 && velocidad_maxima <= 160 && km_galon >= 50 && km_galon <= 55 && precio_venta >= 400000 && precio_venta <= 600000) { if (carros.get(posicion) instanceof Maybach) { ((Maybach) carros.get(posicion)).setLlantas_respuesto(llantas_respuesto); ((Maybach) carros.get(posicion)).setSerie(serie); ((Maybach) carros.get(posicion)).setFecha(fecha); ((Maybach) carros.get(posicion)).setColor(color); ((Maybach) carros.get(posicion)).setMarca_llantas(marca_llantas); ((Maybach) carros.get(posicion)).setPolarizado(polarizado); ((Maybach) carros.get(posicion)).setVelocidad_max(velocidad_maxima); ((Maybach) carros.get(posicion)).setKm_galon(km_galon); ((Maybach) carros.get(posicion)).setPrecio_venta(precio_venta); } } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } if (opcion3.equalsIgnoreCase("b")) { int posicion = Integer.parseInt(JOptionPane.showInputDialog("Ingrese posicion a modificar: ")); String convertible = JOptionPane.showInputDialog("Ingrese si es convertible o no[si,no]: "); String cabina = JOptionPane.showInputDialog("Ingrese si es cabina unica o doble: "); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (velocidad_maxima >= 140 && velocidad_maxima <= 145 && km_galon >= 35 && km_galon <= 40 && precio_venta >= 500000 && precio_venta <= 700000) { if (carros.get(posicion) instanceof Morgan_Aero8) { ((Morgan_Aero8) carros.get(posicion)).setConvertible(convertible); ((Morgan_Aero8) carros.get(posicion)).setCabina(cabina); ((Morgan_Aero8) carros.get(posicion)).setSerie(serie); ((Morgan_Aero8) carros.get(posicion)).setFecha(fecha); ((Morgan_Aero8) carros.get(posicion)).setColor(color); ((Morgan_Aero8) carros.get(posicion)).setMarca_llantas(marca_llantas); ((Morgan_Aero8) carros.get(posicion)).setPolarizado(polarizado); ((Morgan_Aero8) carros.get(posicion)).setVelocidad_max(velocidad_maxima); ((Morgan_Aero8) carros.get(posicion)).setKm_galon(km_galon); ((Morgan_Aero8) carros.get(posicion)).setPrecio_venta(precio_venta); } } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } if (opcion3.equalsIgnoreCase("c")) { int posicion = Integer.parseInt(JOptionPane.showInputDialog("Ingrese posicion a modificar: ")); String tipo = JOptionPane.showInputDialog("Ingrese si es camioneta o turismo: "); String convertible = JOptionPane.showInputDialog("Ingrese si es convertible o no lo es[si,,no]: "); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (velocidad_maxima >= 160 && velocidad_maxima <= 165 && km_galon >= 55 && km_galon <= 60 && precio_venta >= 450000 && precio_venta <= 650000) { if (carros.get(posicion) instanceof Fisker_Automotive) { ((Fisker_Automotive) carros.get(posicion)).setTipo(tipo); ((Fisker_Automotive) carros.get(posicion)).setConvertible(convertible); ((Fisker_Automotive) carros.get(posicion)).setSerie(serie); ((Fisker_Automotive) carros.get(posicion)).setFecha(fecha); ((Fisker_Automotive) carros.get(posicion)).setColor(color); ((Fisker_Automotive) carros.get(posicion)).setMarca_llantas(marca_llantas); ((Fisker_Automotive) carros.get(posicion)).setPolarizado(polarizado); ((Fisker_Automotive) carros.get(posicion)).setVelocidad_max(velocidad_maxima); ((Fisker_Automotive) carros.get(posicion)).setKm_galon(km_galon); ((Fisker_Automotive) carros.get(posicion)).setPrecio_venta(precio_venta); } } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } if (opcion3.equalsIgnoreCase("d")) { int posicion = Integer.parseInt(JOptionPane.showInputDialog("Ingrese posicion a modificar: ")); double peso = Double.parseDouble(JOptionPane.showInputDialog("Ingrese peso: ")); double transmision = Double.parseDouble(JOptionPane.showInputDialog("Ingrese transmision de 6 a 7 velocidades: ")); int serie = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de Serie: ")); Date fecha = new Date(); Color color = Color.BLUE; String marca_llantas = JOptionPane.showInputDialog("Ingrese Marca de llantas: "); String polarizado = JOptionPane.showInputDialog("Ingrese Si tiene o no polarizado[Si,No]: "); double velocidad_maxima = Double.parseDouble(JOptionPane.showInputDialog("Ingrese velocidad maxima(km/hr): ")); double km_galon = Double.parseDouble(JOptionPane.showInputDialog("Ingrese kilometros por galon(km/gal): ")); double precio_venta = Double.parseDouble(JOptionPane.showInputDialog("Ingrese precio de venta: ")); if (peso >= 1276 && peso <= 1376 && velocidad_maxima >= 175 && velocidad_maxima <= 180 && km_galon >= 50 && km_galon <= 55 && precio_venta >= 800000 && precio_venta <= 1000000) { if (carros.get(posicion) instanceof Tramontana) { ((Tramontana) carros.get(posicion)).setPeso(peso); ((Tramontana) carros.get(posicion)).setTransmision(transmision); ((Tramontana) carros.get(posicion)).setSerie(serie); ((Tramontana) carros.get(posicion)).setFecha(fecha); ((Tramontana) carros.get(posicion)).setColor(color); ((Tramontana) carros.get(posicion)).setMarca_llantas(marca_llantas); ((Tramontana) carros.get(posicion)).setPolarizado(polarizado); ((Tramontana) carros.get(posicion)).setVelocidad_max(velocidad_maxima); ((Tramontana) carros.get(posicion)).setKm_galon(km_galon); ((Tramontana) carros.get(posicion)).setPrecio_venta(precio_venta); } } else { JOptionPane.showMessageDialog(null, "No cumple algunos requisitos"); } } } } if (opcion2.equalsIgnoreCase("b")) {//personas String opcion4 = " "; while (!opcion.equalsIgnoreCase("c")) { opcion4 = JOptionPane.showInputDialog("Que tipo de persona desea modificar:? \n" + "a. Empleados\n" + "b. Clientes\n" + "c. Salir!\n"); if (opcion4.equalsIgnoreCase("a")) { int posicion = Integer.parseInt(JOptionPane.showInputDialog("Ingrese posicion a modificar: ")); String nombre = JOptionPane.showInputDialog("Ingrese Nombre: "); double id = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su ID: ")); double edad = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su edad: ")); double altura = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su altura: ")); double peso = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su peso: ")); int horas = Integer.parseInt(JOptionPane.showInputDialog("Ingrese sus horas trabajadas: ")); if (personas.get(posicion) instanceof Empleados) { ((Empleados) personas.get(posicion)).setNombre(nombre); ((Empleados) personas.get(posicion)).setId(id); ((Empleados) personas.get(posicion)).setEdad(edad); ((Empleados) personas.get(posicion)).setAltura(altura); ((Empleados) personas.get(posicion)).setPeso(peso); ((Empleados) personas.get(posicion)).setHora_trabajadas(horas); } } if (opcion4.equalsIgnoreCase("b")) { String nombre = JOptionPane.showInputDialog("Ingrese Nombre: "); double id = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su ID: ")); double edad = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su edad: ")); double altura = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su altura: ")); double peso = Double.parseDouble(JOptionPane.showInputDialog("Ingrese su peso: ")); int dinero = Integer.parseInt(JOptionPane.showInputDialog("Ingrese su dinero que lleva: ")); int posicion = Integer.parseInt(JOptionPane.showInputDialog("Ingrese posicion a modificar: ")); if (personas.get(posicion) instanceof Clientes) { ((Clientes) personas.get(posicion)).setNombre(nombre); ((Clientes) personas.get(posicion)).setId(id); ((Clientes) personas.get(posicion)).setEdad(edad); ((Clientes) personas.get(posicion)).setAltura(altura); ((Clientes) personas.get(posicion)).setPeso(peso); ((Clientes) personas.get(posicion)).setDinero(dinero); } } } } } } } } }
package codeu.chat.util; import java.util.ArrayList; import java.util.List; /** * CommandTokenizer tokenizes the input String and allows for easy use of * methods such as getCommand(), or getNextArg(). Meant to take input from a * command line following format: "Command Arg0 Arg1..." Arguments and commands * can be surrounded by quotes or just spaces. * * @author MatthewKrager * */ final public class CommandTokenizer { /** * String that will be tokenized. Passed Through constructor */ private String source; /** * The index that the tokenizer is currently at. When nextArg() is called, * the argument after the current index will be returned */ private int currentIndex = 0; /** * * @return If there are any args the tokenizer has not yet returned */ public boolean hasNextArg() { int remainingIndices = source.length() - currentIndex; return remainingIndices > 0; } // returns a String starting at currentIndex until the next occurrence of // endingChar. // Does not include endingChar in the String // Leaves currentIndex one character after the end of the returned string. private String nextStringUntil(char endingChar) { String toReturn = ""; while (hasNextArg() && source.charAt(currentIndex) != endingChar) { toReturn += source.charAt(currentIndex); currentIndex++; } currentIndex++; return toReturn; } /** * Returns the argument directly after the currentIndex * * @return the next argument in the source string */ public String getNextArg() { if (!this.hasNextArg()) { return null; } // skip all spaces while (source.charAt(currentIndex) == ' ') { currentIndex++; } // if quotes is first, return string between the two quotes if (source.charAt(currentIndex) == '"') { currentIndex++; return nextStringUntil('"'); } return nextStringUntil(' '); } /** * Leaves currentIndex right before the first argument. Calling getCommand * will reset all calls made to getNextArg() * * @return Returns command (first section of the source String) */ public String getCommand() { currentIndex = 0; return getNextArg(); } /** * Initializes a CommandTokenizer with the given source String. Leaves * currentIndex right before the first argument. * * @param source */ public CommandTokenizer(String source) { // trims the source to rid leading and lagging white space this.source = source.trim(); // runs get Command once so currentIndex is ready to return args // after running getCommand, currentIndex will be ready to tokenize arg0 getCommand(); } /** * * @return all remaining args from the currentIndex to the end of the source * string */ public List<String> getRemainingArgs() { ArrayList<String> args = new ArrayList<String>(); while (hasNextArg()) { args.add(getNextArg()); } return args; } }
package com.android.mms.data; import java.util.ArrayList; import java.util.List; import android.text.TextUtils; import com.android.mms.data.Contact.UpdateListener; public class ContactList extends ArrayList<Contact> { private static final long serialVersionUID = 1L; public static ContactList getByNumbers(Iterable<String> numbers, boolean canBlock) { ContactList list = new ContactList(); for (String number : numbers) { if (!TextUtils.isEmpty(number)) { list.add(Contact.get(number, canBlock)); } } return list; } public static ContactList getByNumbers(String semiSepNumbers, boolean canBlock) { ContactList list = new ContactList(); for (String number : semiSepNumbers.split(";")) { if (!TextUtils.isEmpty(number)) { list.add(Contact.get(number, canBlock)); } } return list; } public static ContactList getByIds(String spaceSepIds, boolean canBlock) { ContactList list = new ContactList(); for (String number : RecipientIdCache.getNumbers(spaceSepIds)) { if (!TextUtils.isEmpty(number)) { list.add(Contact.get(number, canBlock)); } } return list; } public int getPresenceResId() { // We only show presence for single contacts. if (size() != 1) return 0; return get(0).getPresenceResId(); } public void addListeners(UpdateListener l) { for (Contact c : this) { c.addListener(l); } } public void removeListeners(UpdateListener l) { for (Contact c : this) { c.removeListener(l); } } public String formatNames(String separator) { String[] names = new String[size()]; int i = 0; for (Contact c : this) { names[i++] = c.getName(); } return TextUtils.join(separator, names); } public String formatNamesAndNumbers(String separator) { String[] nans = new String[size()]; int i = 0; for (Contact c : this) { nans[i++] = c.getNameAndNumber(); } return TextUtils.join(separator, nans); } public String serialize() { return TextUtils.join(";", getNumbers()); } public boolean containsEmail() { for (Contact c : this) { if (c.isEmail()) { return true; } } return false; } public String[] getNumbers() { List<String> numbers = new ArrayList<String>(); String number; for (Contact c : this) { number = c.getNumber(); // Don't add duplicate numbers. This can happen if a contact name has a comma. // Since we use a comma as a delimiter between contacts, the code will consider // the same recipient has been added twice. The recipients UI still works correctly. // It's easiest to just make sure we only send to the same recipient once. if (!numbers.contains(number)) { numbers.add(number); } } return numbers.toArray(new String[numbers.size()]); } @Override public boolean equals(Object obj) { try { ContactList other = (ContactList)obj; // If they're different sizes, the contact // set is obviously different. if (size() != other.size()) { return false; } // Make sure all the individual contacts are the same. for (Contact c : this) { if (!other.contains(c)) { return false; } } return true; } catch (ClassCastException e) { return false; } } }
package com.aziis98.fractals; import com.aziis98.dare.*; import com.aziis98.dare.SwingWindow.*; import com.aziis98.dare.inputs.*; import com.aziis98.dare.math.*; import com.aziis98.dare.rendering.*; import com.aziis98.dare.system.*; import com.aziis98.dare.util.*; import java.awt.*; import java.awt.event.*; public class FractalsApp extends ApplicationCore { public EList<EList<Vector2f>> iterations = new EList<>(); public int currentIteration = 4; public boolean showShadow = true; @Override public void init() { // Window WindowData.width = 1000; WindowData.height = 800; WindowData.resizable = false; WindowData.title = "Fractals"; // The fractal FractalFunction theFractal = Fractals::fractalKoch; // Initial conditions float focalDist = 300F; EList<Vector2f> initials = new EList<>(); { initials.add( new Vector2f( -focalDist, 0F ).plus( WindowData.getCenter() ) ); initials.add( new Vector2f( +focalDist, 0F ).plus( WindowData.getCenter() ) ); } iterations.add( initials ); EList<Vector2f> iteration, prevIteration; for (int i = 0; i < 7; i++) { System.out.println( " Iteration #" + (i + 1) ); long stTime = Time.milliTime(); iteration = new EList<>(); prevIteration = iterations.getLast(); for (int j = 1; j < prevIteration.size(); j++) { Vector2f a = prevIteration.get( j - 1 ); Vector2f b = prevIteration.get( j ); iteration.addAll( theFractal.iterate( a, b ) ); } iterations.add( iteration ); System.out.println( " Duration: " + (Time.milliTime() - stTime) + "ms" ); } // Keycontrols Keyboard.key( KeyEvent.VK_UP ).addChangeListner( value -> { if ( value && iterations.size() > currentIteration + 1 ) currentIteration++; } ); Keyboard.key( KeyEvent.VK_DOWN ).addChangeListner( value -> { if ( value && currentIteration - 1 >= 0 ) currentIteration } ); Keyboard.key( KeyEvent.VK_S ).addChangeListner( value -> { if ( value ) showShadow ^= true; } ); } @Override public void update() { } public static BasicStroke stroke2 = new BasicStroke( 1.3F, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND ); public static Color outlineColor = new Color( 0xE7E7E7 ); @Override public void render(Graphics2D g) { g.setBackground( Color.WHITE ); g.clearRect( 0, 0, WindowData.width, WindowData.height ); g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); g.setStroke( stroke2 ); if ( showShadow ) { g.setColor( outlineColor ); for (EList<Vector2f> iteration : iterations) { Polyline.drawPolyline( g, iteration ); } } try { g.setColor( Color.BLACK ); Polyline.drawPolyline( g, iterations.get( currentIteration ) ); } catch (Exception e) { g.setColor( Color.RED ); G.drawLine( g, new Vector2f(), WindowData.getDimensions() ); G.drawLine( g, new Vector2f( 0, WindowData.getHeight() ), new Vector2f( WindowData.getWidth(), 0 ) ); } } public interface FractalFunction { EList<Vector2f> iterate(Vector2f a, Vector2f b); } public static void main(String[] args) { launch( new FractalsApp() ); } }
package com.cgutman.adblib; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.Socket; import java.util.HashMap; /** * This class represents an ADB connection. * @author Cameron Gutman */ public class AdbConnection implements Closeable { /** The underlying socket that this class uses to * communicate with the target device. */ private Socket socket; /** The last allocated local stream ID. The ID * chosen for the next stream will be this value + 1. */ private int lastLocalId; /** * The input stream that this class uses to read from * the socket. */ private InputStream inputStream; /** * The output stream that this class uses to read from * the socket. */ OutputStream outputStream; /** * The backend thread that handles responding to ADB packets. */ private Thread connectionThread; /** * Specifies whether a connect has been attempted */ private boolean connectAttempted; /** * Specifies whether a CNXN packet has been received from the peer. */ private boolean connected; /** * Specifies the maximum amount data that can be sent to the remote peer. * This is only valid after connect() returns successfully. */ private int maxData; /** * An initialized ADB crypto object that contains a key pair. */ private AdbCrypto crypto; /** * Specifies whether this connection has already sent a signed token. */ private boolean sentSignature; /** * A hash map of our open streams indexed by local ID. **/ private HashMap<Integer, AdbStream> openStreams; /** * Internal constructor to initialize some internal state */ private AdbConnection() { openStreams = new HashMap<Integer, AdbStream>(); lastLocalId = 0; connectionThread = createConnectionThread(); } /** * Creates a AdbConnection object associated with the socket and * crypto object specified. * @param socket The socket that the connection will use for communcation. * @param crypto The crypto object that stores the key pair for authentication. * @return A new AdbConnection object. * @throws IOException If there is a socket error */ public static AdbConnection create(Socket socket, AdbCrypto crypto) throws IOException { AdbConnection newConn = new AdbConnection(); newConn.crypto = crypto; newConn.socket = socket; newConn.inputStream = socket.getInputStream(); newConn.outputStream = socket.getOutputStream(); /* Disable Nagle because we're sending tiny packets */ socket.setTcpNoDelay(true); return newConn; } /** * Creates a new connection thread. * @return A new connection thread. */ private Thread createConnectionThread() { @SuppressWarnings("resource") final AdbConnection conn = this; return new Thread(new Runnable() { @Override public void run() { while (!connectionThread.isInterrupted()) { try { /* Read and parse a message off the socket's input stream */ AdbProtocol.AdbMessage msg = AdbProtocol.AdbMessage.parseAdbMessage(inputStream); /* Verify magic and checksum */ if (!AdbProtocol.validateMessage(msg)) continue; switch (msg.command) { /* Stream-oriented commands */ case AdbProtocol.CMD_OKAY: case AdbProtocol.CMD_WRTE: case AdbProtocol.CMD_CLSE: /* We must ignore all packets when not connected */ if (!conn.connected) continue; /* Get the stream object corresponding to the packet */ AdbStream waitingStream = openStreams.get(msg.arg1); if (waitingStream == null) continue; synchronized (waitingStream) { if (msg.command == AdbProtocol.CMD_OKAY) { /* We're ready for writes */ waitingStream.updateRemoteId(msg.arg0); waitingStream.readyForWrite(); /* Unwait an open/write */ waitingStream.notify(); } else if (msg.command == AdbProtocol.CMD_WRTE) { /* Got some data from our partner */ waitingStream.addPayload(msg.payload); /* Tell it we're ready for more */ waitingStream.sendReady(); } else if (msg.command == AdbProtocol.CMD_CLSE) { /* He doesn't like us anymore :-( */ conn.openStreams.remove(msg.arg1); /* Notify readers and writers */ waitingStream.notifyClose(); } } break; case AdbProtocol.CMD_AUTH: byte[] packet; if (msg.arg0 == AdbProtocol.AUTH_TYPE_TOKEN) { /* This is an authentication challenge */ if (conn.sentSignature) { /* We've already tried our signature, so send our public key */ packet = AdbProtocol.generateAuth(AdbProtocol.AUTH_TYPE_RSA_PUBLIC, conn.crypto.getAdbPublicKeyPayload()); } else { /* We'll sign the token */ packet = AdbProtocol.generateAuth(AdbProtocol.AUTH_TYPE_SIGNATURE, conn.crypto.signAdbTokenPayload(msg.payload)); conn.sentSignature = true; } /* Write the AUTH reply */ conn.outputStream.write(packet); conn.outputStream.flush(); } break; case AdbProtocol.CMD_CNXN: synchronized (conn) { /* We need to store the max data size */ conn.maxData = msg.arg1; /* Mark us as connected and unwait anyone waiting on the connection */ conn.connected = true; conn.notifyAll(); } break; default: /* Unrecognized packet, just drop it */ break; } } catch (Exception e) { /* The cleanup is taken care of by a combination of this thread * and close() */ break; } } /* This thread takes care of cleaning up pending streams */ cleanupStreams(); conn.notifyAll(); conn.connectAttempted = false; } }); } /** * Gets the max data size that the remote client supports. * A connection must have been attempted before calling this routine. * This routine will block if a connection is in progress. * @return The maximum data size indicated in the connect packet. * @throws InterruptedException If a connection cannot be waited on. * @throws IOException if the connection fails */ public int getMaxData() throws InterruptedException, IOException { if (!connectAttempted) throw new IllegalStateException("connect() must be called first"); synchronized (this) { /* Block if a connection is pending, but not yet complete */ if (!connected) wait(); if (!connected) { throw new IOException("Connection failed"); } } return maxData; } /** * Connects to the remote device. This routine will block until the connection * completes. * @throws IOException If the socket fails while connecting * @throws InterruptedException If we are unable to wait for the connection to finish */ public void connect() throws IOException, InterruptedException { if (connected) throw new IllegalStateException("Already connected"); /* Write the CONNECT packet */ outputStream.write(AdbProtocol.generateConnect()); outputStream.flush(); /* Start the connection thread to respond to the peer */ connectAttempted = true; connectionThread.start(); /* Wait for the connection to go live */ synchronized (this) { if (!connected) wait(); if (!connected) { throw new IOException("Connection failed"); } } } /** * Opens an AdbStream object corresponding to the specified destination. * This routine will block until the connection completes. * @param destination The destination to open on the target * @return AdbStream object corresponding to the specified destination * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8 * @throws IOException If the stream fails while sending the packet * @throws InterruptedException If we are unable to wait for the connection to finish */ public AdbStream open(String destination) throws UnsupportedEncodingException, IOException, InterruptedException { int localId = ++lastLocalId; if (!connectAttempted) throw new IllegalStateException("connect() must be called first"); /* Wait for the connect response */ synchronized (this) { if (!connected) wait(); if (!connected) { throw new IOException("Connection failed"); } } /* Add this stream to this list of half-open streams */ AdbStream stream = new AdbStream(this, localId); openStreams.put(localId, stream); /* Send the open */ outputStream.write(AdbProtocol.generateOpen(localId, destination)); outputStream.flush(); /* Wait for the connection thread to receive the OKAY */ synchronized (stream) { stream.wait(); } /* Check if the open was rejected */ if (stream.isClosed()) throw new ConnectException("Stream open actively rejected by remote peer"); /* We're fully setup now */ return stream; } /** * This function terminates all I/O on streams associated with this ADB connection */ private void cleanupStreams() { /* Close all streams on this connection */ for (AdbStream s : openStreams.values()) { /* We handle exceptions for each close() call to avoid * terminating cleanup for one failed close(). */ try { s.close(); } catch (IOException e) {} } /* No open streams anymore */ openStreams.clear(); } /** This routine closes the Adb connection and underlying socket * @throws IOException if the socket fails to close */ @Override public void close() throws IOException { /* If the connection thread hasn't spawned yet, there's nothing to do */ if (connectionThread == null) return; /* Closing the socket will kick the connection thread */ socket.close(); /* Wait for the connection thread to die */ connectionThread.interrupt(); try { connectionThread.join(); } catch (InterruptedException e) { } } }
package com.dmdirc.actions; import com.dmdirc.Main; import com.dmdirc.Precondition; import com.dmdirc.actions.interfaces.ActionComparison; import com.dmdirc.actions.interfaces.ActionComponent; import com.dmdirc.actions.interfaces.ActionType; import com.dmdirc.actions.wrappers.ActionWrapper; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.actions.wrappers.PerformWrapper; import com.dmdirc.config.ConfigTarget; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.ActionListener; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.updater.components.ActionGroupComponent; import com.dmdirc.util.MapList; import com.dmdirc.util.resourcemanager.ZipResourceManager; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * Manages all actions for the client. * * @author chris */ public final class ActionManager { /** A list of registered action types. */ private final static List<ActionType> actionTypes = new ArrayList<ActionType>(); /** A list of registered action components. */ private final static List<ActionComponent> actionComponents = new ArrayList<ActionComponent>(); /** A list of registered action comparisons. */ private final static List<ActionComparison> actionComparisons = new ArrayList<ActionComparison>(); /** A list of all action wrappers that have registered with us. */ private final static List<ActionWrapper> actionWrappers = new ArrayList<ActionWrapper>(); /** A map linking types and a list of actions that're registered for them. */ private final static MapList<ActionType, Action> actions = new MapList<ActionType, Action>(); /** A map linking groups and a list of actions that're in them. */ private final static Map<String, ActionGroup> groups = new HashMap<String, ActionGroup>(); /** A map of the action type groups to the action types within. */ private final static MapList<String, ActionType> actionTypeGroups = new MapList<String, ActionType>(); /** The listeners that we have registered. */ private final static MapList<ActionType, ActionListener> listeners = new MapList<ActionType, ActionListener>(); /** The identity we're using for action defaults. */ private static Identity defaultsIdentity; /** Indicates whether or not user actions should be killed (not processed). */ private static boolean killSwitch = IdentityManager.getGlobalConfig().getOptionBool("actions", "killswitch", false); /** Creates a new instance of ActionManager. */ private ActionManager() { // Shouldn't be instansiated } /** * Initialises the action manager. */ public static void init() { registerActionTypes(CoreActionType.values()); registerActionComparisons(CoreActionComparison.values()); registerActionComponents(CoreActionComponent.values()); registerWrapper(AliasWrapper.getAliasWrapper()); registerWrapper(PerformWrapper.getPerformWrapper()); // Set up the identity used for our defaults final ConfigTarget target = new ConfigTarget(); final Properties properties = new Properties(); target.setGlobalDefault(); target.setOrder(500000); properties.setProperty("identity.name", "Action defaults"); defaultsIdentity = new Identity(properties, target); // Register a listener for the closing event, so we can save actions addListener(new ActionListener() { /** {@inheritDoc} */ @Override public void processEvent(final ActionType type, final StringBuffer format, final Object... arguments) { saveActions(); } }, CoreActionType.CLIENT_CLOSED); // Make sure we listen for the killswitch IdentityManager.getGlobalConfig().addChangeListener("actions", "killswitch", new ConfigChangeListener() { /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { killSwitch = IdentityManager.getGlobalConfig().getOptionBool( "actions", "killswitch", false); } }); } /** * Saves all actions. */ public static void saveActions() { for (ActionGroup group : groups.values()) { for (Action action : group) { action.save(); } } } /** * Registers the specified default setting for actions. * * @param name The name of the setting to be registered * @param value The default value for the setting */ public static void registerDefault(final String name, final String value) { defaultsIdentity.setOption("actions", name, value); } /** * Registers the specified action wrapper with the manager. * * @param wrapper The wrapper to be registered */ @Precondition({ "The specified wrapper is not null", "The specified wrapper's group name is non-null and not empty" }) public static void registerWrapper(final ActionWrapper wrapper) { assert(wrapper != null); assert(wrapper.getGroupName() != null); assert(!wrapper.getGroupName().isEmpty()); actionWrappers.add(wrapper); } /** * Registers a set of actiontypes with the manager. * * @param types An array of ActionTypes to be registered */ @Precondition("None of the specified ActionTypes are null") public static void registerActionTypes(final ActionType[] types) { for (ActionType type : types) { assert(type != null); actionTypes.add(type); actionTypeGroups.add(type.getType().getGroup(), type); } } /** * Registers a set of action components with the manager. * * @param comps An array of ActionComponents to be registered */ @Precondition("None of the specified ActionComponents are null") public static void registerActionComponents(final ActionComponent[] comps) { for (ActionComponent comp : comps) { assert(comp != null); actionComponents.add(comp); } } /** * Registers a set of action comparisons with the manager. * * @param comps An array of ActionComparisons to be registered */ @Precondition("None of the specified ActionComparisons are null") public static void registerActionComparisons(final ActionComparison[] comps) { for (ActionComparison comp : comps) { assert(comp != null); actionComparisons.add(comp); } } /** * Returns a map of groups to action lists. * * @return a map of groups to action lists */ public static Map<String, ActionGroup> getGroups() { return groups; } /** * Returns a map of type groups to types. * * @return A map of type groups to types */ public static MapList<String, ActionType> getTypeGroups() { return actionTypeGroups; } /** * Loads actions from the user's directory. */ public static void loadActions() { actions.clear(); groups.clear(); for (ActionWrapper wrapper : actionWrappers) { wrapper.clearActions(); } final File dir = new File(getDirectory()); if (!dir.exists()) { try { dir.mkdirs(); dir.createNewFile(); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "I/O error when creating actions directory: " + ex.getMessage()); } } if (dir.listFiles() == null) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load user action files"); } else { for (File file : dir.listFiles()) { if (file.isDirectory()) { loadActions(file); } } } registerComponents(); } /** * Creates new ActionGroupComponents for each action group. */ private static void registerComponents() { for (ActionGroup group : groups.values()) { new ActionGroupComponent(group); } } /** * Retrieves the action wrapper with the specified group name. * * @param name The group name to find * @return An ActionWrapper with the specified group name, or null */ @Precondition("The specified name is non-null and not empty") private static ActionWrapper getWrapper(final String name) { assert(name != null); assert(!name.isEmpty()); for (ActionWrapper wrapper : actionWrappers) { if (name.equals(wrapper.getGroupName())) { return wrapper; } } return null; } /** * Determines whether the specified group name is one used by an action * wrapper. * * @param name The group name to test * @return True if the group is part of a wrapper, false otherwise */ @Precondition("The specified name is non-null and not empty") private static boolean isWrappedGroup(final String name) { assert(name != null); assert(!name.isEmpty()); return getWrapper(name) != null; } /** * Loads action files from a specified group directory. * * @param dir The directory to scan. */ @Precondition("The specified File is not null and represents a directory") private static void loadActions(final File dir) { assert(dir != null); assert(dir.isDirectory()); groups.put(dir.getName(), new ActionGroup(dir.getName())); for (File file : dir.listFiles()) { new Action(dir.getName(), file.getName()); } } /** * Registers an action with the manager. * * @param action The action to be registered */ @Precondition("The specified action is not null") public static void registerAction(final Action action) { assert(action != null); for (ActionType trigger : action.getTriggers()) { actions.add(trigger, action); } if (isWrappedGroup(action.getGroup())) { getWrapper(action.getGroup()).registerAction(action); } else { getGroup(action.getGroup()).add(action); } } /** * Retrieves the action group with the specified name. A new group is * created if it doesn't already exist. * * @param name The name of the group to retrieve * @return The corresponding ActionGroup */ public static ActionGroup getGroup(final String name) { if (!groups.containsKey(name)) { groups.put(name, new ActionGroup(name)); } return groups.get(name); } /** * Unregisters an action with the manager. * * @param action The action to be unregistered */ @Precondition("The specified action is not null") public static void unregisterAction(final Action action) { assert(action != null); actions.removeFromAll(action); getGroup(action.getGroup()).remove(action); } /** * Reregisters the specified action. Should be used when the action's * triggers change. * * @param action The action to be reregistered */ public static void reregisterAction(final Action action) { unregisterAction(action); reregisterAction(action); } /** * Deletes the specified action. * * @param action The action to be deleted */ @Precondition("The specified Action is not null") public static void deleteAction(final Action action) { assert(action != null); unregisterAction(action); action.delete(); } /** * Processes an event of the specified type. * * @param type The type of the event to process * @param format The format of the message that's going to be displayed for * the event. Actions may change this format. * @param arguments The arguments for the event */ @Precondition({ "The specified ActionType is not null", "The specified ActionType has a valid ActionMetaType", "The length of the arguments array equals the arity of the ActionType's ActionMetaType" }) public static void processEvent(final ActionType type, final StringBuffer format, final Object ... arguments) { assert(type != null); assert(type.getType() != null); assert(type.getType().getArity() == arguments.length); if (listeners.containsKey(type)) { for (ActionListener listener : listeners.get(type)) { listener.processEvent(type, format, arguments); } } if (!killSwitch) { triggerActions(type, format, arguments); } } /** * Triggers actions that respond to the specified type. * * @param type The type of the event to process * @param format The format of the message that's going to be displayed for * the event. Actions may change this format.* * @param arguments The arguments for the event */ @Precondition("The specified ActionType is not null") private static void triggerActions(final ActionType type, final StringBuffer format, final Object ... arguments) { assert(type != null); if (actions.containsKey(type)) { for (Action action : actions.get(type)) { action.trigger(format, arguments); } } } /** * Returns the directory that should be used to store actions. * * @return The directory that should be used to store actions */ public static String getDirectory() { return Main.getConfigDir() + "actions" + System.getProperty("file.separator"); } /** * Creates a new group with the specified name. * * @param group The group to be created */ @Precondition({ "The specified group is non-null and not empty", "The specified group is not an existing group" }) public static void makeGroup(final String group) { assert(group != null); assert(!group.isEmpty()); assert(!groups.containsKey(group)); if (new File(getDirectory() + group).mkdir()) { groups.put(group, new ActionGroup(group)); } } /** * Removes the group with the specified name. * * @param group The group to be removed */ @Precondition({ "The specified group is non-null and not empty", "The specified group is an existing group" }) public static void removeGroup(final String group) { assert(group != null); assert(!group.isEmpty()); assert(groups.containsKey(group)); for (Action action : new ArrayList<Action>(groups.get(group))) { unregisterAction(action); } final File dir = new File(getDirectory() + group); for (File file : dir.listFiles()) { if (!file.delete()) { Logger.userError(ErrorLevel.MEDIUM, "Unable to remove file: " + file.getAbsolutePath()); return; } } if (!dir.delete()) { Logger.userError(ErrorLevel.MEDIUM, "Unable to remove directory: " + dir.getAbsolutePath()); return; } groups.remove(group); } /** * Renames the specified group. * * @param oldName The old name of the group * @param newName The new name of the group */ @Precondition({ "The old name is non-null and not empty", "The old name is an existing group", "The new name is non-null and not empty", "The new name is not an existing group", "The old name does not equal the new name" }) public static void renameGroup(final String oldName, final String newName) { assert(oldName != null); assert(!oldName.isEmpty()); assert(newName != null); assert(!newName.isEmpty()); assert(groups.containsKey(oldName)); assert(!groups.containsKey(newName)); assert(!newName.equals(oldName)); makeGroup(newName); for (Action action : groups.get(oldName)) { action.setGroup(newName); getGroup(newName).add(action); } groups.remove(oldName); removeGroup(oldName); } /** * Returns the action comparison specified by the given string, or null if it * doesn't match a valid registered action comparison. * * @param type The name of the action comparison to try and find * @return The actioncomparison with the specified name, or null on failure */ public static ActionType getActionType(final String type) { if (type == null || type.isEmpty()) { return null; } for (ActionType target : actionTypes) { if (((Enum) target).name().equals(type)) { return target; } } return null; } /** * Returns a list of action types that are compatible with the one * specified. * * @param type The type to be checked against * @return A list of compatible action types */ @Precondition("The specified type is not null") public static List<ActionType> getCompatibleTypes(final ActionType type) { assert(type != null); final List<ActionType> res = new ArrayList<ActionType>(); for (ActionType target : actionTypes) { if (!target.equals(type) && target.getType().equals(type.getType())) { res.add(target); } } return res; } /** * Returns a list of action components that are compatible with the * specified class. * * @param target The class to be tested * @return A list of compatible action components */ @Precondition("The specified target is not null") public static List<ActionComponent> getCompatibleComponents(final Class target) { assert(target != null); final List<ActionComponent> res = new ArrayList<ActionComponent>(); for (ActionComponent subject : actionComponents) { if (subject.appliesTo().equals(target)) { res.add(subject); } } return res; } /** * Returns a list of action comparisons that are compatible with the * specified class. * * @param target The class to be tested * @return A list of compatible action comparisons */ @Precondition("The specified target is not null") public static List<ActionComparison> getCompatibleComparisons(final Class target) { assert(target != null); final List<ActionComparison> res = new ArrayList<ActionComparison>(); for (ActionComparison subject : actionComparisons) { if (subject.appliesTo().equals(target)) { res.add(subject); } } return res; } /** * Returns a list of all the action types registered by this manager. * * @return A list of registered action types */ public static List<ActionType> getTypes() { return actionTypes; } /** * Returns a list of all the action types registered by this manager. * * @return A list of registered action comparisons */ public static List<ActionComparison> getComparisons() { return actionComparisons; } /** * Returns the action component specified by the given string, or null if it * doesn't match a valid registered action component. * * @param type The name of the action component to try and find * @return The actioncomponent with the specified name, or null on failure */ @Precondition("The specified type is non-null and not empty") public static ActionComponent getActionComponent(final String type) { assert(type != null); assert(!type.isEmpty()); for (ActionComponent target : actionComponents) { if (((Enum) target).name().equals(type)) { return target; } } return null; } /** * Returns the action type specified by the given string, or null if it * doesn't match a valid registered action type. * * @param type The name of the action type to try and find * @return The actiontype with the specified name, or null on failure */ @Precondition("The specified type is non-null and not empty") public static ActionComparison getActionComparison(final String type) { assert(type != null); assert(!type.isEmpty()); for (ActionComparison target : actionComparisons) { if (((Enum) target).name().equals(type)) { return target; } } return null; } /** * Installs an action pack located at the specified path. * * @param path The full path of the action pack .zip. * @throws IOException If the zip cannot be extracted */ public static void installActionPack(final String path) throws IOException { final ZipResourceManager ziprm = ZipResourceManager.getInstance(path); ziprm.extractResources("", getDirectory()); loadActions(); new File(path).delete(); } /** * Adds a new listener for the specified action type. * * @param types The action types that are to be listened for * @param listener The listener to be added */ public static void addListener(final ActionListener listener, final ActionType ... types) { for (ActionType type : types) { listeners.add(type, listener); } } /** * Removes a listener for the specified action type. * * @param types The action types that were being listened for * @param listener The listener to be removed */ public static void removeListener(final ActionListener listener, final ActionType ... types) { for (ActionType type: types) { listeners.remove(type, listener); } } /** * Removes a listener for all action types. * * @param listener The listener to be removed */ public static void removeListener(final ActionListener listener) { listeners.removeFromAll(listener); } }
package org.opencms.gwt.client.ui; import org.opencms.gwt.client.CmsCoreProvider; import org.opencms.gwt.client.Messages; import org.opencms.gwt.client.rpc.CmsRpcAction; import org.opencms.gwt.client.ui.CmsListItemWidget.Background; import org.opencms.gwt.client.ui.CmsNotification.Type; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle; import org.opencms.gwt.client.ui.input.CmsCheckBox; import org.opencms.gwt.client.ui.input.upload.CmsFileInfo; import org.opencms.gwt.client.ui.input.upload.CmsFileInput; import org.opencms.gwt.client.util.CmsChangeHeightAnimation; import org.opencms.gwt.client.util.CmsDomUtil; import org.opencms.gwt.shared.CmsIconUtil; import org.opencms.gwt.shared.CmsListInfoBean; import org.opencms.gwt.shared.CmsUploadFileBean; import org.opencms.gwt.shared.CmsUploadFileBean.I_CmsUploadConstants; import org.opencms.gwt.shared.CmsUploadProgessInfo; import org.opencms.util.CmsStringUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.HTML; /** * Provides an upload dialog.<p> * * @author Ruediger Kurz * * @version $Revision: 1.3 $ * * @since 8.0.0 */ public abstract class A_CmsUploadDialog extends CmsPopupDialog { /** * Provides the upload progress information.<p> * * Has a progressbar and a table for showing details.<p> */ private class CmsUploadProgressInfo extends FlowPanel { /** The progress bar. */ private CmsProgressBar m_bar; /** The table for showing upload details. */ private FlexTable m_fileinfo; /** A sorted list of the filenames to upload. */ private List<String> m_orderedFilenamesToUpload; /** Signals if the progress was set at least one time. */ private boolean m_started; /** * Default constructor.<p> */ public CmsUploadProgressInfo() { // get a ordered list of filenames m_orderedFilenamesToUpload = new ArrayList<String>(getFilesToUpload().keySet()); Collections.sort(m_orderedFilenamesToUpload, String.CASE_INSENSITIVE_ORDER); // create the progress bar m_bar = new CmsProgressBar(); // create the file info table m_fileinfo = new FlexTable(); m_fileinfo.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().fileInfoTable()); // arrange the progress info addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().progressInfo()); add(m_bar); add(m_fileinfo); } /** * Finishes the state of the progress bar.<p> */ public void finish() { String length = formatBytes(new Long(getContentLength()).intValue()); int fileCount = m_orderedFilenamesToUpload.size(); m_bar.setValue(100); m_fileinfo.removeAllRows(); m_fileinfo.setHTML(0, 0, "<b>" + Messages.get().key(Messages.GUI_UPLOAD_FINISH_UPLOADED_0) + "</b>"); m_fileinfo.setText( 0, 1, Messages.get().key( Messages.GUI_UPLOAD_FINISH_UPLOADED_VALUE_4, new Integer(fileCount), new Integer(fileCount), getFileText(), length)); } /** * Sets the progress information.<p> * * @param info the progress info bean */ public void setProgress(CmsUploadProgessInfo info) { int currFile = info.getCurrentFile(); int currFileIndex = 0; if (currFile == 0) { // no files read so far } else { currFileIndex = currFile - 1; if (currFileIndex >= m_orderedFilenamesToUpload.size()) { currFileIndex = m_orderedFilenamesToUpload.size() - 1; } } if (getContentLength() == 0) { setContentLength(info.getContentLength()); } String currFilename = m_orderedFilenamesToUpload.get(currFileIndex); String contentLength = formatBytes(new Long(getContentLength()).intValue()); int fileCount = m_orderedFilenamesToUpload.size(); String readBytes = formatBytes(new Long(getBytesRead(info.getPercent())).intValue()); m_bar.setValue(info.getPercent()); if (!m_started) { m_started = true; m_fileinfo.setHTML(0, 0, "<b>" + Messages.get().key(Messages.GUI_UPLOAD_PROGRESS_CURRENT_FILE_0) + "</b>"); m_fileinfo.setHTML(1, 0, "<b>" + Messages.get().key(Messages.GUI_UPLOAD_PROGRESS_UPLOADING_0) + "</b>"); m_fileinfo.setHTML(2, 0, ""); m_fileinfo.setText(0, 1, ""); m_fileinfo.setText(1, 1, ""); m_fileinfo.setText(2, 1, ""); m_fileinfo.getColumnFormatter().setWidth(0, "100px"); } m_fileinfo.setText(0, 1, currFilename); m_fileinfo.setText( 1, 1, Messages.get().key( Messages.GUI_UPLOAD_PROGRESS_CURRENT_VALUE_3, new Integer(currFileIndex + 1), new Integer(fileCount), getFileText())); m_fileinfo.setText( 2, 1, Messages.get().key(Messages.GUI_UPLOAD_PROGRESS_UPLOADING_VALUE_2, readBytes, contentLength)); } /** * Returns the bytes that are read so far.<p> * * The total request size is larger than the sum of all file sizes that are uploaded. * Because boundaries and the target folder or even some other information than only * the plain file contents are submited to the server.<p> * * This method calculates the bytes that are read with the help of the file sizes.<p> * * @param percent the server side determined percentage * * @return the bytes that are read so far */ private long getBytesRead(long percent) { return percent != 0 ? getContentLength() * percent / 100 : 0; } } /** Maximum width for the file item widget list. */ private static final int DIALOG_WIDTH = 600; /** The size for kilobytes in bytes. */ private static final float KILOBYTE = 1024L; /** The minimal height of the content wrapper. */ private static final int MIN_CONTENT_HEIGHT = 110; /** Text metrics key. */ private static final String TM_FILE_UPLOAD_LIST = "FileUploadList"; /** The interval for updating the progress information in milliseconds. */ private static final int UPDATE_PROGRESS_INTERVALL = 1000; /** Stores all files that were added. */ private Map<String, CmsFileInfo> m_allFiles; /** Signals that the upload dialog was canceled. */ private boolean m_canceled; /** Signals that the client currently loading. */ private boolean m_clientLoading; /** The sum of all file sizes. */ private long m_contentLength; /** A flow panel with a dynamic height. */ private FlowPanel m_contentWrapper; /** The user information text widget. */ private HTML m_dialogInfo; /** The list of file item widgets. */ private CmsList<I_CmsListItem> m_fileList; /** The Map of files to upload. */ private Map<String, CmsFileInfo> m_filesToUpload; /** Stores the content height of the selection dialog. */ private int m_firstContentHeight; /** Stores the height of the user information text widget of the selection dialog. */ private int m_firstInfoHeight; /** Stores the height of the summary. */ private int m_firstSummaryHeight; /** The input file input fields. */ private Map<String, CmsFileInput> m_inputsToUpload; /** Stores the list items of all added files. */ private Map<String, CmsListItem> m_listItems; /** Signals if the dialog has already been loaded. */ private boolean m_loaded; /** A panel for showing client loading. */ private FlowPanel m_loadingPanel; /** The main panel. */ private FlowPanel m_mainPanel; /** The OK button. */ private CmsPushButton m_okButton; /** The progress bar for the upload process. */ private CmsUploadProgressInfo m_progressInfo; /** Signals whether the selection is done or not. */ private boolean m_selectionDone; /** The user information text widget. */ private HTML m_selectionSummary; /** The target folder to upload the selected files. */ private String m_targetFolder; /** The timer for updating the progress. */ private Timer m_updateProgressTimer = new Timer() { /** * @see com.google.gwt.user.client.Timer#run() */ @Override public void run() { updateProgress(); } }; /** The upload button of this dialog. */ private CmsUploadButton m_uploadButton; /** * Default constructor.<p> */ public A_CmsUploadDialog() { setText(Messages.get().key(Messages.GUI_UPLOAD_DIALOG_TITLE_0)); setModal(true); setGlassEnabled(true); catchNotifications(); setWidth(DIALOG_WIDTH + "px"); addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().uploadDialogContent()); // create a map that stores all files (upload, existing, invalid) m_allFiles = new HashMap<String, CmsFileInfo>(); // create a map the holds all the list items for the selection dialog m_listItems = new HashMap<String, CmsListItem>(); m_inputsToUpload = new HashMap<String, CmsFileInput>(); m_fileList = new CmsList<I_CmsListItem>(); m_fileList.truncate(TM_FILE_UPLOAD_LIST, DIALOG_WIDTH - 20); // initialize a map that stores all the files that should be uploaded m_filesToUpload = new HashMap<String, CmsFileInfo>(); // create the main panel m_mainPanel = new FlowPanel(); // add the user info to the main panel m_dialogInfo = new HTML(); m_dialogInfo.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().dialogInfo()); m_mainPanel.add(m_dialogInfo); // add the content wrapper to the main panel m_contentWrapper = new FlowPanel(); m_contentWrapper.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().mainContentWidget()); m_contentWrapper.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().cornerAll()); m_contentWrapper.getElement().getStyle().setPropertyPx("maxHeight", Window.getClientHeight() - 300); m_contentWrapper.getElement().getStyle().setPropertyPx("minHeight", MIN_CONTENT_HEIGHT); m_mainPanel.add(m_contentWrapper); m_selectionSummary = new HTML(); m_selectionSummary.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().summary()); m_mainPanel.add(m_selectionSummary); // set the main panel as content of the popup setContent(m_mainPanel); // create and add the "OK", "Cancel" and upload button createButtons(); } /** * Adds the given file input field to this dialog.<p> * * @param fileInput the file input field to add */ public void addFileInput(CmsFileInput fileInput) { m_okButton.enable(); // add the files selected by the user to the list of files to upload if (fileInput != null) { List<CmsFileInfo> fileObjects = Arrays.asList(fileInput.getFiles()); for (CmsFileInfo file : fileObjects) { m_allFiles.put(file.getFileName(), file); if (!isTooLarge(file)) { m_inputsToUpload.put(file.getFileName(), fileInput); m_filesToUpload.put(file.getFileName(), file); } if ((m_listItems.get(file.getFileName()) != null) && (m_listItems.get(file.getFileName()).getCheckBox() != null) && !m_listItems.get(file.getFileName()).getCheckBox().isChecked()) { m_filesToUpload.remove(file.getFileName()); } } rebuildList(m_allFiles); } // set the user info displayDialogInfo(Messages.get().key(Messages.GUI_UPLOAD_INFO_SELECTION_0), false); // set the selection summary updateSummary(); // add a upload button m_uploadButton.createFileInput(); // show the popup center(); getDialog().getElement().getStyle().setDisplay(Display.NONE); getDialog().getElement().getStyle().setDisplay(Display.BLOCK); } /** * Creates a bean that can be used for the list item widget.<p> * * @param file the info to create the bean for * * @return a list info bean */ public abstract CmsListInfoBean createInfoBean(CmsFileInfo file); /** * Returns the targetFolder.<p> * * @return the targetFolder */ public String getTargetFolder() { return m_targetFolder; } /** * Returns <code>true</code> if the file is too large, <code>false</code> otherwise.<p> * * @param cmsFileInfo the file to check * * @return <code>true</code> if the file is too large, <code>false</code> otherwise */ public abstract boolean isTooLarge(CmsFileInfo cmsFileInfo); /** * Loads and shows this dialog.<p> */ public void loadAndShow() { if (m_loaded) { throw new UnsupportedOperationException(); } else { addFileInput(null); m_loaded = true; } } /** * Loads and shows the dialog.<p> * * @param fileInput the first file input field */ public void loadAndShow(CmsFileInput fileInput) { if (m_loaded) { throw new UnsupportedOperationException(); } else { addFileInput(fileInput); m_loaded = true; } } /** * Sets the target folder.<p> * * @param target the target folder to set */ public void setTargetFolder(String target) { m_targetFolder = target; } /** * Executes the submit action.<p> */ public abstract void submit(); /** * Updates the file summary.<p> */ public abstract void updateSummary(); /** * Cancels the upload progress timer.<p> */ protected void cancelUpdateProgress() { m_updateProgressTimer.cancel(); } /** * Cancels the upload.<p> */ protected void cancelUpload() { m_canceled = true; cancelUpdateProgress(); hide(); CmsRpcAction<Void> callback = new CmsRpcAction<Void>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { CmsCoreProvider.getService().cancelUpload(this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(Void result) { // noop } }; callback.execute(); } /** * Disables the OK button.<p> * * @param disabledReason the reason for disabling the OK button */ protected void disableOKButton(String disabledReason) { m_okButton.disable(disabledReason); } /** * Enables the OK button.<p> */ protected void enableOKButton() { m_okButton.enable(); } /** * Formats a given bytes value (file size).<p> * * @param filesize the file size to format * * @return the formated file size in KB */ protected String formatBytes(int filesize) { int roundedKB = new Double(Math.ceil(filesize / KILOBYTE)).intValue(); String formated = NumberFormat.getDecimalFormat().format(new Double(roundedKB)); return formated + " KB"; } /** * Returns the contentLength.<p> * * @return the contentLength */ protected long getContentLength() { return m_contentLength; } /** * Returns the filesToUpload.<p> * * @return the filesToUpload */ protected Map<String, CmsFileInfo> getFilesToUpload() { return m_filesToUpload; } /** * Returns "files" or "file" depending on the files to upload.<p> * * @return "files" or "file" depending on the files to upload */ protected String getFileText() { if (m_filesToUpload.size() == 1) { return Messages.get().key(Messages.GUI_UPLOAD_FILES_SINGULAR_0); } return Messages.get().key(Messages.GUI_UPLOAD_FILES_PLURAL_0); } /** * Returns the inputsToUpload.<p> * * @return the inputsToUpload */ protected Collection<CmsFileInput> getInputsToUpload() { return Collections.unmodifiableCollection(m_inputsToUpload.values()); } /** * Returns the resource type name for a given filename.<p> * * @param filename the file name * * @return the resource type name */ protected String getResourceType(String filename) { String typeName = null; if (CmsStringUtil.isNotEmpty(filename)) { int pos = filename.lastIndexOf('.'); if (pos >= 0) { String suffix = filename.substring(pos); if (CmsStringUtil.isNotEmpty(suffix)) { typeName = CmsCoreProvider.get().getExtensionMapping().get(suffix.toLowerCase()); } } } if (typeName == null) { typeName = "plain"; } return typeName; } /** * Inserts a hidden form into.<p> * * @param form the form to insert */ protected void insertUploadForm(FormPanel form) { form.getElement().getStyle().setDisplay(Display.NONE); m_contentWrapper.add(form); } /** * The action that is executed if the user clicks on the OK button.<p> * * If the selection dialog is currently shown the selected files are checked * otherwise the upload is triggered.<p> */ protected void onOkClick() { if (!m_selectionDone) { checkSelection(); } else { commit(); } } /** * Parses the upload response of the server and decides what to do.<p> * * @param results a JSON Object */ protected void parseResponse(String results) { cancelUpdateProgress(); stopLoadingAnimation(); if ((!m_canceled) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(results)) { JSONObject jsonObject = JSONParser.parseStrict(results).isObject(); boolean success = jsonObject.get(I_CmsUploadConstants.KEY_SUCCESS).isBoolean().booleanValue(); String message = jsonObject.get(I_CmsUploadConstants.KEY_MESSAGE).isString().stringValue(); String stacktrace = jsonObject.get(I_CmsUploadConstants.KEY_STACKTRACE).isString().stringValue(); // If the upload is done so fast that we did not receive any progress information, then // the content length is unknown. For that reason take the request size to show how // much bytes were uploaded. double size = jsonObject.get(I_CmsUploadConstants.KEY_REQUEST_SIZE).isNumber().doubleValue(); long requestSize = new Double(size).longValue(); if (m_contentLength == 0) { m_contentLength = requestSize; } if (success) { displayDialogInfo(Messages.get().key(Messages.GUI_UPLOAD_INFO_FINISHING_0), false); m_progressInfo.finish(); closeOnSuccess(); } else { showErrorReport(message, stacktrace); } } } /** * Decides how to go on depending on the information of the server response.<p> * * Shows a warning if there is another upload process active (inside the same session).<p> * * Otherwise if the list of files to upload contains already existent resources on the VFS or if there * are files selected that have invalid file names the overwrite dialog is shown.<p> * * Only if there is no other upload process running and none of the selected files * is already existent on the VFS the upload is triggered.<p> * * @param result the bean that contains the information to evaluate */ protected void proceedWorkflow(CmsUploadFileBean result) { if (result.isActive()) { m_okButton.enable(); CmsNotification.get().send(Type.WARNING, Messages.get().key(Messages.GUI_UPLOAD_NOTIFICATION_RUNNING_0)); } else { if (!result.getExistingResourceNames().isEmpty() || !result.getInvalidFileNames().isEmpty()) { showOverwriteDialog(result); } else { commit(); } } } /** * Sets the contentLength.<p> * * @param contentLength the contentLength to set */ protected void setContentLength(long contentLength) { m_contentLength = contentLength; } /** * Sets the HTML of the selection summary.<p> * * @param html the HTML to set as String */ protected void setSummaryHTML(String html) { m_selectionSummary.setHTML(html); } /** * Shows the error report.<p> * * @param message the message to show * @param stacktrace the stacktrace to show */ protected void showErrorReport(final String message, final String stacktrace) { hide(); new CmsErrorDialog(message, stacktrace).center(); } /** * Retrieves the progress information from the server.<p> */ protected void updateProgress() { CmsRpcAction<CmsUploadProgessInfo> callback = new CmsRpcAction<CmsUploadProgessInfo>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { CmsCoreProvider.getService().getUploadProgressInfo(this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onFailure(java.lang.Throwable) */ @Override public void onFailure(Throwable t) { super.onFailure(t); cancelUpdateProgress(); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(CmsUploadProgessInfo result) { updateProgressBar(result); } }; callback.execute(); } /** * Updates the progress bar.<p> * * @param info the progress info */ protected void updateProgressBar(CmsUploadProgessInfo info) { if (info.isRunning()) { stopLoadingAnimation(); m_progressInfo.setProgress(info); } } /** * Adds a click handler for the given checkbox.<p> * * @param check the checkbox * @param file the file */ private void addClickHandlerToCheckBox(final CmsCheckBox check, final CmsFileInfo file) { check.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { // add or remove the file from the list of files to upload if (check.isChecked()) { getFilesToUpload().put(file.getFileName(), file); } else { getFilesToUpload().remove(file.getFileName()); } // disable or enable the OK button if (getFilesToUpload().isEmpty()) { disableOKButton(Messages.get().key(Messages.GUI_UPLOAD_NOTIFICATION_NO_FILES_0)); } else { enableOKButton(); } // update summary updateSummary(); } }); } /** * Adds a file to the list.<p> * * @param file the file to add * @param icon the resource type icon * @param invalid signals if the filename is invalid */ private void addFileToList(CmsFileInfo file, String icon, boolean invalid, boolean isTooLarge) { CmsListInfoBean infoBean = createInfoBean(file); CmsListItemWidget listItemWidget = new CmsListItemWidget(infoBean); listItemWidget.setIcon(icon); CmsCheckBox check = new CmsCheckBox(); check.setChecked(false); if (!invalid && !isTooLarge) { if (m_filesToUpload.containsKey(file.getFileName())) { check.setChecked(true); } check.setTitle(file.getFileName()); addClickHandlerToCheckBox(check, file); } else if (isTooLarge) { String message = Messages.get().key( Messages.GUI_UPLOAD_FILE_TOO_LARGE_2, formatBytes(file.getFileSize()), formatBytes(new Long(CmsCoreProvider.get().getUploadFileSizeLimit()).intValue())); check.disable(message); listItemWidget.setBackground(Background.RED); listItemWidget.setSubtitleLabel(message); } else { String message = Messages.get().key( Messages.GUI_UPLOAD_FILE_INVALID_NAME_2, file.getFileName(), formatBytes(file.getFileSize())); check.disable(message); listItemWidget.setBackground(Background.RED); listItemWidget.setSubtitleLabel(message); } CmsListItem listItem = new CmsListItem(); listItem.initContent(check, listItemWidget); m_fileList.addItem(listItem); m_listItems.put(file.getFileName(), listItem); } /** * Changes the height of the content wrapper so that the dialog finally has the * same height that the dialog has when the min height is set on the selection screen.<p> */ private void changeHeight() { int firstHeight = MIN_CONTENT_HEIGHT + m_firstInfoHeight + m_firstSummaryHeight + 2; int currentHeight = CmsDomUtil.getCurrentStyleInt(m_mainPanel.getElement(), CmsDomUtil.Style.height); int targetHeight = firstHeight - m_dialogInfo.getOffsetHeight() - m_selectionSummary.getOffsetHeight(); if (currentHeight > firstHeight) { CmsChangeHeightAnimation.change(m_contentWrapper.getElement(), targetHeight, new Command() { /** * @see com.google.gwt.user.client.Command#execute() */ @Override public void execute() { getDialog().getElement().getStyle().setDisplay(Display.NONE); getDialog().getElement().getStyle().setDisplay(Display.BLOCK); } }, 750); } } /** * Before the upload data is effectively submited we have to check * for already existent resources in the VFS.<p> * * Executes the RPC call that checks the VFS for existing resources. * Passes the response object to a method that evaluates the result.<p> */ private void checkSelection() { m_okButton.disable(Messages.get().key(Messages.GUI_UPLOAD_BUTTON_OK_DISABLE_CHECKING_0)); if (!m_selectionDone) { m_firstContentHeight = CmsDomUtil.getCurrentStyleInt(m_contentWrapper.getElement(), CmsDomUtil.Style.height); m_firstInfoHeight = m_dialogInfo.getOffsetHeight(); m_firstSummaryHeight = m_selectionSummary.getOffsetHeight(); } CmsRpcAction<CmsUploadFileBean> callback = new CmsRpcAction<CmsUploadFileBean>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { CmsCoreProvider.getService().checkUploadFiles( new ArrayList<String>(getFilesToUpload().keySet()), getTargetFolder(), this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(CmsUploadFileBean result) { proceedWorkflow(result); } }; callback.execute(); } /** * Closes the dialog after a delay.<p> */ private void closeOnSuccess() { Timer closeTimer = new Timer() { /** * @see com.google.gwt.user.client.Timer#run() */ @Override public void run() { A_CmsUploadDialog.this.hide(); } }; closeTimer.schedule(1500); } /** * Calls the submit action if there are any files selected for upload.<p> */ private void commit() { m_selectionDone = true; if (!m_filesToUpload.isEmpty()) { m_okButton.disable(Messages.get().key(Messages.GUI_UPLOAD_BUTTON_OK_DISABLE_UPLOADING_0)); m_uploadButton.getElement().getStyle().setDisplay(Display.NONE); showProgress(); submit(); } } /** * Creates the "OK", the "Cancel" and the "Upload" button.<p> */ private void createButtons() { CmsPushButton cancelButton = new CmsPushButton(); cancelButton.setTitle(Messages.get().key(Messages.GUI_CANCEL_0)); cancelButton.setText(Messages.get().key(Messages.GUI_CANCEL_0)); cancelButton.setSize(I_CmsButton.Size.medium); cancelButton.setUseMinWidth(true); cancelButton.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { cancelUpload(); } }); addButton(cancelButton); m_okButton = new CmsPushButton(); m_okButton.setTitle(Messages.get().key(Messages.GUI_OK_0)); m_okButton.setText(Messages.get().key(Messages.GUI_OK_0)); m_okButton.setSize(I_CmsButton.Size.medium); m_okButton.setUseMinWidth(true); m_okButton.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { onOkClick(); } }); addButton(m_okButton); // add a new upload button m_uploadButton = new CmsUploadButton(this); m_uploadButton.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().uploadDialogButton()); m_uploadButton.setText(Messages.get().key(Messages.GUI_UPLOAD_BUTTON_ADD_FILES_0)); addButton(m_uploadButton); } /** * Creates a Map containing file objects as values and the name of the file as key.<p> * * @param files the list of files * * @return the map of files */ private Map<String, CmsFileInfo> createFileMapFromList(List<CmsFileInfo> files) { Map<String, CmsFileInfo> result = new HashMap<String, CmsFileInfo>(); for (CmsFileInfo file : files) { result.put(file.getFileName(), file); } return result; } /** * Sets the user info.<p> * * @param msg the message to display * @param warning signals whether the message should be a warning or nor */ private void displayDialogInfo(String msg, boolean warning) { StringBuffer buffer = new StringBuffer(64); if (!warning) { buffer.append("<p class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadCss().dialogMessage()); buffer.append("\">"); buffer.append(msg); buffer.append("</p>"); } else { buffer.append("<div class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadCss().warningIcon()); buffer.append("\"></div>"); buffer.append("<p class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadCss().warningMessage()); buffer.append("\">"); buffer.append(msg); buffer.append("</p>"); } m_dialogInfo.setHTML(buffer.toString()); } /** * Searches in the map of files to upload for the filenames in the given list and * returns a list with the found file objects.<p> * * @param names the list of filenames to search for * * @return a list with the found file objects in the files to upload */ private List<CmsFileInfo> getFilesForFilenames(final List<String> names) { List<CmsFileInfo> result = new ArrayList<CmsFileInfo>(); for (String filename : names) { if (m_filesToUpload.containsKey(filename)) { result.add(m_filesToUpload.get(filename)); } } return result; } /** * Returns a map with filename as key and the according icon classes as value.<p> * * @param filenames the filenames to get the resource type icons for * * @return a map with filename as key and the according icon classes as value */ private Map<String, String> getResourceIcons(Collection<String> filenames) { Map<String, String> result = new HashMap<String, String>(); for (String filename : filenames) { String icon = CmsIconUtil.getResourceIconClasses(getResourceType(filename), filename, false); result.put(filename, icon); } return result; } /** * Rebuilds the list of files to upload.<p> * * @param files the map of the files to put in the list */ private void rebuildList(Map<String, CmsFileInfo> files) { removeContent(); m_fileList.clearList(); // sort the files for name List<String> sortedFileNames = new ArrayList<String>(); sortedFileNames.addAll(files.keySet()); Collections.sort(sortedFileNames, String.CASE_INSENSITIVE_ORDER); Map<String, String> icons = getResourceIcons(files.keySet()); for (String filename : sortedFileNames) { addFileToList(files.get(filename), icons.get(filename), false, isTooLarge(files.get(filename))); } m_contentWrapper.add(m_fileList); } /** * Removes all widgets from the content wrapper.<p> */ private void removeContent() { int widgetCount = m_contentWrapper.getWidgetCount(); for (int i = 0; i < widgetCount; i++) { m_contentWrapper.remove(0); } } /** * Sets the height for the content so that the dialog finally has the same height * as the dialog has on the selection screen.<p> */ private void setHeight() { int infoDiff = m_firstInfoHeight - m_dialogInfo.getOffsetHeight(); int summaryDiff = m_firstSummaryHeight - m_selectionSummary.getOffsetHeight(); int height = m_firstContentHeight + infoDiff + summaryDiff; m_contentWrapper.getElement().getStyle().setHeight(height, Unit.PX); m_contentWrapper.getElement().getStyle().clearProperty("minHeight"); m_contentWrapper.getElement().getStyle().clearProperty("maxHeight"); } /** * Shows the overwrite dialog.<p> * * @param infoBean the info bean containing the existing and invalid file names */ private void showOverwriteDialog(CmsUploadFileBean infoBean) { // update the dialog m_selectionDone = true; m_okButton.enable(); displayDialogInfo(Messages.get().key(Messages.GUI_UPLOAD_INFO_OVERWRITE_0), true); // hide the upload button m_uploadButton.getElement().getStyle().setDisplay(Display.NONE); // handle existing files List<CmsFileInfo> existings = getFilesForFilenames(infoBean.getExistingResourceNames()); Map<String, CmsFileInfo> existingFiles = createFileMapFromList(existings); rebuildList(existingFiles); // handle the invalid files List<String> invalids = new ArrayList<String>(infoBean.getInvalidFileNames()); Collections.sort(invalids, String.CASE_INSENSITIVE_ORDER); Map<String, String> icons = getResourceIcons(invalids); for (String filename : invalids) { addFileToList(m_filesToUpload.get(filename), icons.get(filename), true, false); m_filesToUpload.remove(filename); } setHeight(); } /** * Starts the upload progress bar.<p> */ private void showProgress() { removeContent(); displayDialogInfo(Messages.get().key(Messages.GUI_UPLOAD_INFO_UPLOADING_0), false); m_selectionSummary.removeFromParent(); m_progressInfo = new CmsUploadProgressInfo(); m_contentWrapper.add(m_progressInfo); m_updateProgressTimer.scheduleRepeating(UPDATE_PROGRESS_INTERVALL); startLoadingAnimation(Messages.get().key(Messages.GUI_UPLOAD_CLIENT_LOADING_0)); setHeight(); changeHeight(); } /** * Starts the loading animation.<p> * * Used while client is loading files from hard disk into memory.<p> * * @param msg the message that should be displayed below the loading animation (can also be HTML as String) */ private void startLoadingAnimation(String msg) { m_clientLoading = true; m_loadingPanel = new FlowPanel(); m_loadingPanel.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().loadingPanel()); m_loadingPanel.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().cornerAll()); HTML animationDiv = new HTML(); animationDiv.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().loadingAnimation()); m_loadingPanel.add(animationDiv); HTML messageDiv = new HTML(); messageDiv.addStyleName(I_CmsLayoutBundle.INSTANCE.uploadCss().loadingText()); messageDiv.setHTML(msg); m_loadingPanel.add(messageDiv); m_contentWrapper.add(m_loadingPanel); } /** * Stops the client loading animation.<p> */ private void stopLoadingAnimation() { if (m_clientLoading) { m_contentWrapper.remove(m_loadingPanel); m_clientLoading = false; } } }
package net.runelite.cache; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import net.runelite.cache.definitions.NpcDefinition; import net.runelite.cache.definitions.exporters.NpcExporter; import net.runelite.cache.definitions.loaders.NpcLoader; import net.runelite.cache.fs.Archive; import net.runelite.cache.fs.Index; import net.runelite.cache.fs.Store; import net.runelite.cache.util.Namer; public class NpcManager { private final Store store; private final List<NpcDefinition> npcs = new ArrayList<>(); private final Namer namer = new Namer(); public NpcManager(Store store) { this.store = store; } public void load() throws IOException { NpcLoader loader = new NpcLoader(); Index index = store.getIndex(IndexType.CONFIGS); Archive archive = index.getArchive(ConfigType.NPC.getId()); for (net.runelite.cache.fs.File f : archive.getFiles()) { NpcDefinition npc = loader.load(f.getFileId(), f.getContents()); npcs.add(npc); } } public List<NpcDefinition> getNpcs() { return npcs; } public void dump(File out) throws IOException { out.mkdirs(); for (NpcDefinition def : npcs) { NpcExporter exporter = new NpcExporter(def); File targ = new File(out, def.id + ".json"); exporter.exportTo(targ); } } public void java(File java) throws IOException { System.setProperty("line.separator", "\n"); java.mkdirs(); File targ = new File(java, "NpcID.java"); try (PrintWriter fw = new PrintWriter(targ)) { fw.println("/* This file is automatically generated. Do not edit. */"); fw.println("package net.runelite.api;"); fw.println(""); fw.println("public final class NpcID"); fw.println("{"); for (NpcDefinition def : npcs) { if (def.name.equalsIgnoreCase("NULL")) { continue; } String name = namer.name(def.name, def.id); if (name == null) { continue; } fw.println(" public static final int " + name + " = " + def.id + ";"); } fw.println("}"); } } }
package com.fsck.k9.activity; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.AbsoluteSizeSpan; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.util.Log; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.BaseAccount; import com.fsck.k9.FontSizes; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.SearchAccount; import com.fsck.k9.SearchSpecification; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.activity.setup.Prefs; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingController.SORT_TYPE; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.StorageManager; /** * MessageList is the primary user interface for the program. This Activity * shows a list of messages. * From this Activity the user can perform all standard message operations. */ public class MessageList extends K9Activity implements OnClickListener, AdapterView.OnItemClickListener, AnimationListener { /** * Reverses the result of a {@link Comparator}. * * @param <T> */ public static class ReverseComparator<T> implements Comparator<T> { private Comparator<T> mDelegate; /** * @param delegate * Never <code>null</code>. */ public ReverseComparator(final Comparator<T> delegate) { mDelegate = delegate; } @Override public int compare(final T object1, final T object2) { // arg1 & 2 are mixed up, this is done on purpose return mDelegate.compare(object2, object1); } } /** * Chains comparator to find a non-0 result. * * @param <T> */ public static class ComparatorChain<T> implements Comparator<T> { private List<Comparator<T>> mChain; /** * @param chain * Comparator chain. Never <code>null</code>. */ public ComparatorChain(final List<Comparator<T>> chain) { mChain = chain; } @Override public int compare(T object1, T object2) { int result = 0; for (final Comparator<T> comparator : mChain) { result = comparator.compare(object1, object2); if (result != 0) { break; } } return result; } } public static class AttachmentComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.message.hasAttachments() ? 0 : 1) - (object2.message.hasAttachments() ? 0 : 1); } } public static class FlaggedComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.flagged ? 0 : 1) - (object2.flagged ? 0 : 1); } } public static class UnreadComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.read ? 1 : 0) - (object2.read ? 1 : 0); } } public static class SenderComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareCounterparty.toLowerCase().compareTo(object2.compareCounterparty.toLowerCase()); } } public static class DateComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareDate.compareTo(object2.compareDate); } } public static class ArrivalComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareArrival.compareTo(object2.compareArrival); } } public static class SubjectComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder arg0, MessageInfoHolder arg1) { // XXX doesn't respect the Comparator contract since it alters the compared object if (arg0.compareSubject == null) { arg0.compareSubject = Utility.stripSubject(arg0.message.getSubject()); } if (arg1.compareSubject == null) { arg1.compareSubject = Utility.stripSubject(arg1.message.getSubject()); } return arg0.compareSubject.compareToIgnoreCase(arg1.compareSubject); } } /** * Immutable empty {@link Message} array */ private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_FOLDER = "folder"; private static final String EXTRA_QUERY = "query"; private static final String EXTRA_QUERY_FLAGS = "queryFlags"; private static final String EXTRA_FORBIDDEN_FLAGS = "forbiddenFlags"; private static final String EXTRA_INTEGRATE = "integrate"; private static final String EXTRA_ACCOUNT_UUIDS = "accountUuids"; private static final String EXTRA_FOLDER_NAMES = "folderNames"; private static final String EXTRA_TITLE = "title"; private static final String EXTRA_LIST_POSITION = "listPosition"; private static final String EXTRA_RETURN_FROM_MESSAGE_VIEW = "returnFromMessageView"; /** * Maps a {@link SORT_TYPE} to a {@link Comparator} implementation. */ private static final Map<SORT_TYPE, Comparator<MessageInfoHolder>> SORT_COMPARATORS; static { // fill the mapping at class time loading final Map<SORT_TYPE, Comparator<MessageInfoHolder>> map = new EnumMap<SORT_TYPE, Comparator<MessageInfoHolder>>(SORT_TYPE.class); map.put(SORT_TYPE.SORT_ATTACHMENT, new AttachmentComparator()); map.put(SORT_TYPE.SORT_DATE, new DateComparator()); map.put(SORT_TYPE.SORT_ARRIVAL, new ArrivalComparator()); map.put(SORT_TYPE.SORT_FLAGGED, new FlaggedComparator()); map.put(SORT_TYPE.SORT_SENDER, new SenderComparator()); map.put(SORT_TYPE.SORT_SUBJECT, new SubjectComparator()); map.put(SORT_TYPE.SORT_UNREAD, new UnreadComparator()); // make it immutable to prevent accidental alteration (content is immutable already) SORT_COMPARATORS = Collections.unmodifiableMap(map); } private ListView mListView; private boolean mTouchView = true; private int mPreviewLines = 0; private MessageListAdapter mAdapter; private View mFooterView; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private MessagingController mController; private Account mAccount; private int mUnreadMessageCount = 0; private GestureDetector gestureDetector; private View.OnTouchListener gestureListener; /** * Stores the name of the folder that we want to open as soon as possible * after load. */ private String mFolderName; /** * If we're doing a search, this contains the query string. */ private String mQueryString; private Flag[] mQueryFlags = null; private Flag[] mForbiddenFlags = null; private boolean mIntegrate = false; private String[] mAccountUuids = null; private String[] mFolderNames = null; private String mTitle; private MessageListHandler mHandler = new MessageListHandler(); private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; private boolean mStars = true; private boolean mCheckboxes = true; private int mSelectedCount = 0; private View mBatchButtonArea; private ImageButton mBatchReadButton; private ImageButton mBatchDeleteButton; private ImageButton mBatchFlagButton; private ImageButton mBatchArchiveButton; private ImageButton mBatchMoveButton; private ImageButton mBatchDoneButton; private FontSizes mFontSizes = K9.getFontSizes(); private Bundle mState = null; /** * Remember the selection to be consistent between menu display and menu item * selection */ private MessageInfoHolder mSelectedMessage; /** * Relevant messages for the current context when we have to remember the * chosen messages between user interactions (eg. Selecting a folder for * move operation) */ private List<MessageInfoHolder> mActiveMessages; private Context context; /* package visibility for faster inner class access */ MessageHelper mMessageHelper = MessageHelper.getInstance(this); private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override public void onUnmount(String providerId) { if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) { runOnUiThread(new Runnable() { @Override public void run() { onAccountUnavailable(); } }); } } @Override public void onMount(String providerId) { // no-op } } class MessageListHandler { /** * @param messages Never {@code null}. */ public void removeMessages(final List<MessageInfoHolder> messages) { if (messages.isEmpty()) { return; } runOnUiThread(new Runnable() { @Override public void run() { for (MessageInfoHolder message : messages) { if (message != null) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { if (message.selected && mSelectedCount > 0) { mSelectedCount } mAdapter.messages.remove(message); } } } resetUnreadCountOnThread(); mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } }); } /** * @param messages Never {@code null}. */ public void addMessages(final List<MessageInfoHolder> messages) { if (messages.isEmpty()) { return; } final boolean wasEmpty = mAdapter.messages.isEmpty(); runOnUiThread(new Runnable() { @Override public void run() { for (final MessageInfoHolder message : messages) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { int index; synchronized (mAdapter.messages) { index = Collections.binarySearch(mAdapter.messages, message, getComparator()); } if (index < 0) { index = (index * -1) - 1; } mAdapter.messages.add(index, message); } } if (wasEmpty) { mListView.setSelection(0); } resetUnreadCountOnThread(); mAdapter.notifyDataSetChanged(); } }); } private void resetUnreadCount() { runOnUiThread(new Runnable() { @Override public void run() { resetUnreadCountOnThread(); } }); } private void resetUnreadCountOnThread() { if (mQueryString != null) { int unreadCount = 0; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { unreadCount += holder.read ? 0 : 1; } } mUnreadMessageCount = unreadCount; refreshTitleOnThread(); } } private void sortMessages() { final Comparator<MessageInfoHolder> chainComparator = getComparator(); runOnUiThread(new Runnable() { @Override public void run() { synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages, chainComparator); } mAdapter.notifyDataSetChanged(); } }); } /** * @return The comparator to use to display messages in an ordered * fashion. Never <code>null</code>. */ protected Comparator<MessageInfoHolder> getComparator() { final List<Comparator<MessageInfoHolder>> chain = new ArrayList<Comparator<MessageInfoHolder>>(2 /* we add 2 comparators at most */); { // add the specified comparator final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(sortType); if (sortAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } { // add the date comparator if not already specified if (sortType != SORT_TYPE.SORT_DATE && sortType != SORT_TYPE.SORT_ARRIVAL) { final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(SORT_TYPE.SORT_DATE); if (sortDateAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } } // build the comparator chain final Comparator<MessageInfoHolder> chainComparator = new ComparatorChain<MessageInfoHolder>(chain); return chainComparator; } public void folderLoading(String folder, boolean loading) { if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } runOnUiThread(new Runnable() { @Override public void run() { updateFooterView(); } }); } private void refreshTitle() { runOnUiThread(new Runnable() { @Override public void run() { refreshTitleOnThread(); } }); } private void refreshTitleOnThread() { setWindowTitle(); setWindowProgress(); } private void setWindowProgress() { int level = Window.PROGRESS_END; if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { int divisor = mAdapter.mListener.getFolderTotal(); if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (mAdapter.mListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } } getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level); } private void setWindowTitle() { String displayName; if (mFolderName != null) { displayName = mFolderName; if (mAccount.getInboxFolderName().equalsIgnoreCase(displayName)) { displayName = getString(R.string.special_mailbox_name_inbox); } else if (mAccount.getOutboxFolderName().equals(displayName)) { displayName = getString(R.string.special_mailbox_name_outbox); } String dispString = mAdapter.mListener.formatHeader(MessageList.this, getString(R.string.message_list_title, mAccount.getDescription(), displayName), mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } else if (mQueryString != null) { if (mTitle != null) { String dispString = mAdapter.mListener.formatHeader(MessageList.this, mTitle, mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } else { setTitle(getString(R.string.search_results) + ": " + mQueryString); } } } public void progress(final boolean progress) { runOnUiThread(new Runnable() { @Override public void run() { showProgressIndicator(progress); } }); } } /** * Show the message list that was used to open the {@link MessageView} for a message. * * <p> * <strong>Note:</strong> * The {@link MessageList} instance should still be around and all we do is bring it back to * the front (see the activity flags).<br> * Out of sheer paranoia we also set the extras that were used to create the original * {@code MessageList} instance. Using those, the activity can be recreated in the unlikely * case of it having been killed by the OS. * </p> * * @param context * The {@link Context} instance to invoke the {@link Context#startActivity(Intent)} * method on. * @param extras * The extras used to create the original {@code MessageList} instance. * * @see MessageView#actionView(Context, MessageReference, ArrayList, Bundle) */ public static void actionHandleFolder(Context context, Bundle extras) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtras(extras); intent.putExtra(EXTRA_RETURN_FROM_MESSAGE_VIEW, true); context.startActivity(intent); } public static void actionHandleFolder(Context context, Account account, String folder) { Intent intent = actionHandleFolderIntent(context, account, folder); context.startActivity(intent); } public static Intent actionHandleFolderIntent(Context context, Account account, String folder) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } return intent; } public static void actionHandle(Context context, String title, String queryString, boolean integrate, Flag[] flags, Flag[] forbiddenFlags) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, queryString); if (flags != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(flags, ',')); } if (forbiddenFlags != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(forbiddenFlags, ',')); } intent.putExtra(EXTRA_INTEGRATE, integrate); intent.putExtra(EXTRA_TITLE, title); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(intent); } /** * Creates and returns an intent that opens Unified Inbox or All Messages screen. */ public static Intent actionHandleAccountIntent(Context context, String title, SearchSpecification searchSpecification) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, searchSpecification.getQuery()); if (searchSpecification.getRequiredFlags() != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(searchSpecification.getRequiredFlags(), ',')); } if (searchSpecification.getForbiddenFlags() != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(searchSpecification.getForbiddenFlags(), ',')); } intent.putExtra(EXTRA_INTEGRATE, searchSpecification.isIntegrate()); intent.putExtra(EXTRA_ACCOUNT_UUIDS, searchSpecification.getAccountUuids()); intent.putExtra(EXTRA_FOLDER_NAMES, searchSpecification.getFolderNames()); intent.putExtra(EXTRA_TITLE, title); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return intent; } public static void actionHandle(Context context, String title, SearchSpecification searchSpecification) { Intent intent = actionHandleAccountIntent(context, title, searchSpecification); context.startActivity(intent); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view == mFooterView) { if (mCurrentFolder != null) { mController.loadMoreMessages(mAccount, mFolderName, mAdapter.mListener); } return; } MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (mSelectedCount > 0) { // In multiselect mode make sure that clicking on the item results // in toggling the 'selected' checkbox. setSelected(Collections.singletonList(message), !message.selected); } else { onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { context = this; super.onCreate(savedInstanceState); mInflater = getLayoutInflater(); initializeLayout(); // Only set "touchable" when we're first starting up the activity. // Otherwise we get force closes when the user toggles it midstream. mTouchView = K9.messageListTouchable(); mPreviewLines = K9.messageListPreviewLines(); initializeMessageList(getIntent(), true); } @Override public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent initializeMessageList(intent, false); } private void initializeMessageList(Intent intent, boolean create) { boolean returnFromMessageView = intent.getBooleanExtra( EXTRA_RETURN_FROM_MESSAGE_VIEW, false); if (!create && returnFromMessageView) { // We're returning from the MessageView activity with "Manage back button" enabled. // So just leave the activity in the state it was left in. return; } String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); if (mAccount != null && !mAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return; } mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); String queryFlags = intent.getStringExtra(EXTRA_QUERY_FLAGS); if (queryFlags != null) { String[] flagStrings = queryFlags.split(","); mQueryFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mQueryFlags[i] = Flag.valueOf(flagStrings[i]); } } String forbiddenFlags = intent.getStringExtra(EXTRA_FORBIDDEN_FLAGS); if (forbiddenFlags != null) { String[] flagStrings = forbiddenFlags.split(","); mForbiddenFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mForbiddenFlags[i] = Flag.valueOf(flagStrings[i]); } } mIntegrate = intent.getBooleanExtra(EXTRA_INTEGRATE, false); mAccountUuids = intent.getStringArrayExtra(EXTRA_ACCOUNT_UUIDS); mFolderNames = intent.getStringArrayExtra(EXTRA_FOLDER_NAMES); mTitle = intent.getStringExtra(EXTRA_TITLE); // Take the initial folder into account only if we are *not* restoring // the activity already. if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } mAdapter = new MessageListAdapter(); restorePreviousData(); if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } // Hide "Load up to x more" footer for search views mFooterView.setVisibility((mQueryString != null) ? View.GONE : View.VISIBLE); mController = MessagingController.getInstance(getApplication()); mListView.setAdapter(mAdapter); } private void restorePreviousData() { final ActivityState previousData = getLastNonConfigurationInstance(); if (previousData != null) { mAdapter.messages.addAll(previousData.messages); mActiveMessages = previousData.activeMessages; } } @Override public void onPause() { super.onPause(); mController.removeListener(mAdapter.mListener); saveListState(); StorageManager.getInstance(getApplication()).removeListener(mStorageListener); } public void saveListState() { mState = new Bundle(); mState.putInt(EXTRA_LIST_POSITION, mListView.getSelectedItemPosition()); } public void restoreListState() { if (mState == null) { return; } int pos = mState.getInt(EXTRA_LIST_POSITION, ListView.INVALID_POSITION); if (pos >= mListView.getCount()) { pos = mListView.getCount() - 1; } if (pos == ListView.INVALID_POSITION) { mListView.setSelected(false); } else { mListView.setSelection(pos); } } /** * On resume we refresh messages for the folder that is currently open. * This guarantees that things like unread message count and read status * are updated. */ @Override public void onResume() { super.onResume(); if (mAccount != null && !mAccount.isAvailable(this)) { onAccountUnavailable(); return; } StorageManager.getInstance(getApplication()).addListener(mStorageListener); mStars = K9.messageListStars(); mCheckboxes = K9.messageListCheckboxes(); sortType = mController.getSortType(); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); mController.addListener(mAdapter.mListener); Account[] accountsWithNotification; if (mAccount != null) { accountsWithNotification = new Account[] { mAccount }; } else { Preferences preferences = Preferences.getPreferences(this); accountsWithNotification = preferences.getAccounts(); } for (Account accountWithNotification : accountsWithNotification) { mController.notifyAccountCancel(this, accountWithNotification); } if (mAdapter.messages.isEmpty()) { if (mFolderName != null) { mController.listLocalMessages(mAccount, mFolderName, mAdapter.mListener); // Hide the archive button if we don't have an archive folder. if (!mAccount.hasArchiveFolder()) { mBatchArchiveButton.setVisibility(View.GONE); } } else if (mQueryString != null) { mController.searchLocalMessages(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); // Don't show the archive button if this is a search. mBatchArchiveButton.setVisibility(View.GONE); } } else { // reread the selected date format preference in case it has changed mMessageHelper.refresh(); new Thread() { @Override public void run() { mAdapter.markAllMessagesAsDirty(); if (mFolderName != null) { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessagesSynchronous(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } mAdapter.pruneDirtyMessages(); runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); restoreListState(); } }); } } .start(); } if (mAccount != null && mFolderName != null) { mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } mHandler.refreshTitle(); } private void initializeLayout() { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.message_list); mListView = (ListView) findViewById(R.id.message_list); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(false); mListView.setOnItemClickListener(this); mListView.addFooterView(getFooterView(mListView)); registerForContextMenu(mListView); mBatchButtonArea = findViewById(R.id.batch_button_area); mBatchReadButton = (ImageButton) findViewById(R.id.batch_read_button); mBatchReadButton.setOnClickListener(this); mBatchDeleteButton = (ImageButton) findViewById(R.id.batch_delete_button); mBatchDeleteButton.setOnClickListener(this); mBatchFlagButton = (ImageButton) findViewById(R.id.batch_flag_button); mBatchFlagButton.setOnClickListener(this); mBatchArchiveButton = (ImageButton) findViewById(R.id.batch_archive_button); mBatchArchiveButton.setOnClickListener(this); mBatchMoveButton = (ImageButton) findViewById(R.id.batch_move_button); mBatchMoveButton.setOnClickListener(this); mBatchDoneButton = (ImageButton) findViewById(R.id.batch_done_button); mBatchDoneButton.setOnClickListener(this); mBatchReadButton.setVisibility(K9.batchButtonsMarkRead() ? View.VISIBLE : View.GONE); mBatchDeleteButton.setVisibility(K9.batchButtonsDelete() ? View.VISIBLE : View.GONE); mBatchArchiveButton.setVisibility(K9.batchButtonsArchive() ? View.VISIBLE : View.GONE); mBatchMoveButton.setVisibility(K9.batchButtonsMove() ? View.VISIBLE : View.GONE); mBatchFlagButton.setVisibility(K9.batchButtonsFlag() ? View.VISIBLE : View.GONE); mBatchDoneButton.setVisibility(K9.batchButtonsUnselect() ? View.VISIBLE : View.GONE); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector(true)); gestureListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; mListView.setOnTouchListener(gestureListener); } /** * Container for values to be kept while the device configuration is * modified at runtime (keyboard, orientation, etc.) and Android restarts * this activity. * * @see MessageList#onRetainNonConfigurationInstance() * @see MessageList#getLastNonConfigurationInstance() */ static class ActivityState { public List<MessageInfoHolder> messages; public List<MessageInfoHolder> activeMessages; } /* (non-Javadoc) * * Method overridden for proper typing within this class (the return type is * more specific than the super implementation) * * @see android.app.Activity#onRetainNonConfigurationInstance() */ @Override public ActivityState onRetainNonConfigurationInstance() { final ActivityState state = new ActivityState(); state.messages = mAdapter.messages; state.activeMessages = mActiveMessages; return state; } /* * (non-Javadoc) * * Method overridden for proper typing within this class (the return type is * more specific than the super implementation) * * @see android.app.Activity#getLastNonConfigurationInstance() */ @Override public ActivityState getLastNonConfigurationInstance() { return (ActivityState) super.getLastNonConfigurationInstance(); } @Override public void onBackPressed() { if (K9.manageBack()) { if (mQueryString == null) { onShowFolderList(); } else { onAccounts(); } } else { super.onBackPressed(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Shortcuts that work no matter what is selected switch (keyCode) { // messagelist is actually a K9Activity, not a K9ListActivity // This saddens me greatly, but to support volume key navigation // in MessageView, we implement this bit of wrapper code case KeyEvent.KEYCODE_VOLUME_UP: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition > 0) { mListView.setSelection(currentPosition - 1); } return true; } return false; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition < mListView.getCount()) { mListView.setSelection(currentPosition + 1); } return true; } return false; } case KeyEvent.KEYCODE_DPAD_LEFT: { if (mBatchButtonArea.hasFocus()) { return false; } else { return true; } } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (mBatchButtonArea.hasFocus()) { return false; } else { return true; } } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } boolean retval = true; int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); final List<MessageInfoHolder> selection = getSelectionFromMessage(message); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(selection); return true; } case KeyEvent.KEYCODE_S: { setSelected(selection, !message.selected); return true; } case KeyEvent.KEYCODE_D: { onDelete(selection); return true; } case KeyEvent.KEYCODE_F: { onForward(message); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; } case KeyEvent.KEYCODE_R: { onReply(message); return true; } case KeyEvent.KEYCODE_G: { setFlag(selection, Flag.FLAGGED, !message.flagged); return true; } case KeyEvent.KEYCODE_M: { onMove(selection); return true; } case KeyEvent.KEYCODE_V: { onArchive(selection); return true; } case KeyEvent.KEYCODE_Y: { onCopy(selection); return true; } case KeyEvent.KEYCODE_Z: { setFlag(selection, Flag.SEEN, !message.read); return true; } } } } } finally { retval = super.onKeyDown(keyCode, event); } return retval; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } return super.onKeyUp(keyCode, event); } private void onResendMessage(MessageInfoHolder message) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } private void onOpenMessage(MessageInfoHolder message) { if (message.folder.name.equals(message.message.getFolder().getAccount().getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } else { // Need to get the list before the sort starts ArrayList<MessageReference> messageRefs = new ArrayList<MessageReference>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { MessageReference ref = holder.message.makeMessageReference(); messageRefs.add(ref); } } MessageReference ref = message.message.makeMessageReference(); Log.i(K9.LOG_TAG, "MessageList sending message " + ref); MessageView.actionView(this, ref, messageRefs, getIntent().getExtras()); } /* * We set read=true here for UI performance reasons. The actual value * will get picked up on the refresh when the Activity is resumed but * that may take a second or so and we don't want this to show and * then go away. I've gone back and forth on this, and this gives a * better UI experience, so I am putting it back in. */ if (!message.read) { message.read = true; } } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount); finish(); } private void onCompose() { if (mQueryString != null) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ MessageCompose.actionCompose(this, null); } else { MessageCompose.actionCompose(this, mAccount); } } private void onEditPrefs() { Prefs.actionPrefs(this); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SORT_TYPE newSortType) { if (sortType == newSortType) { onToggleSortAscending(); } else { sortType = newSortType; mController.setSortType(sortType); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mHandler.sortMessages(); } private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onToggleSortAscending() { mController.setSortAscending(sortType, !sortAscending); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } /** * @param holders * Never {@code null}. */ private void onDelete(final List<MessageInfoHolder> holders) { final List<Message> messagesToRemove = new ArrayList<Message>(); for (MessageInfoHolder holder : holders) { messagesToRemove.add(holder.message); } mHandler.removeMessages(holders); mController.deleteMessages(messagesToRemove.toArray(EMPTY_MESSAGE_ARRAY), null); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: { if (data == null) { return; } final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); if (destFolderName != null) { final List<MessageInfoHolder> holders = mActiveMessages; mActiveMessages = null; // don't need it any more final Account account = holders.get(0).message.getFolder().getAccount(); account.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: move(holders, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: copy(holders, destFolderName); break; } } break; } } } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, false, null); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, true, null); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, holder.message.getFolder().getAccount(), holder.message, null); } private void onMarkAllAsRead(final Account account, final String folder) { if (K9.confirmMarkAllAsRead()) { showDialog(DIALOG_MARK_ALL_AS_READ); } else { markAllAsRead(); } } private void markAllAsRead() { try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } } mHandler.sortMessages(); } catch (Exception e) { // Ignore } } private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return ConfirmationDialog.create(this, id, R.string.mark_all_as_read_dlg_title, getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName), R.string.okay_action, R.string.cancel_action, new Runnable() { @Override public void run() { markAllAsRead(); } }); case R.id.dialog_confirm_spam: return ConfirmationDialog.create(this, id, R.string.dialog_confirm_spam_title, "" /* text is refreshed by #onPrepareDialog(int, Dialog) below */, R.string.dialog_confirm_spam_confirm_button, R.string.dialog_confirm_spam_cancel_button, new Runnable() { @Override public void run() { onSpamConfirmed(mActiveMessages); // No further need for this reference mActiveMessages = null; } }, new Runnable() { @Override public void run() { // event for cancel, we don't need this reference any more mActiveMessages = null; } }); } return super.onCreateDialog(id); } /* * (non-Javadoc) * * Android happens to invoke this method even if the given dialog is not * shown (eg. a dismissed dialog) as part of the automatic activity * reloading following a configuration change (orientation, keyboard, * locale, etc.). */ @Override public void onPrepareDialog(final int id, final Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: { if (mCurrentFolder != null) { ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); } break; } case R.id.dialog_confirm_spam: { // mActiveMessages can be null if Android restarts the activity // while this dialog is not actually shown (but was displayed at // least once) if (mActiveMessages != null) { final int selectionSize = mActiveMessages.size(); final String message; message = getResources().getQuantityString(R.plurals.dialog_confirm_spam_message, selectionSize, Integer.valueOf(selectionSize)); ((AlertDialog) dialog).setMessage(message); } break; } default: { super.onPrepareDialog(id, dialog); } } } private void onToggleRead(MessageInfoHolder holder) { LocalMessage message = holder.message; Folder folder = message.getFolder(); Account account = folder.getAccount(); String folderName = folder.getName(); mController.setFlag(account, folderName, new Message[] { message }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } private void onToggleFlag(MessageInfoHolder holder) { LocalMessage message = holder.message; Folder folder = message.getFolder(); Account account = folder.getAccount(); String folderName = folder.getName(); mController.setFlag(account, folderName, new Message[] { message }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener, null); mController.sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { final List<MessageInfoHolder> selection = getSelectionFromCheckboxes(); int itemId = item.getItemId(); switch (itemId) { case R.id.compose: { onCompose(); return true; } case R.id.accounts: { onAccounts(); return true; } case R.id.set_sort_date: { changeSort(SORT_TYPE.SORT_DATE); return true; } case R.id.set_sort_arrival: { changeSort(SORT_TYPE.SORT_ARRIVAL); return true; } case R.id.set_sort_subject: { changeSort(SORT_TYPE.SORT_SUBJECT); return true; } case R.id.set_sort_sender: { changeSort(SORT_TYPE.SORT_SENDER); return true; } case R.id.set_sort_flag: { changeSort(SORT_TYPE.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { changeSort(SORT_TYPE.SORT_UNREAD); return true; } case R.id.set_sort_attach: { changeSort(SORT_TYPE.SORT_ATTACHMENT); return true; } case R.id.select_all: case R.id.batch_select_all: { setAllSelected(true); toggleBatchButtons(); return true; } case R.id.batch_deselect_all: { setAllSelected(false); toggleBatchButtons(); return true; } case R.id.batch_delete_op: { onDelete(selection); return true; } case R.id.batch_mark_read_op: { setFlag(selection, Flag.SEEN, true); return true; } case R.id.batch_mark_unread_op: { setFlag(selection, Flag.SEEN, false); return true; } case R.id.batch_flag_op: { setFlag(selection, Flag.FLAGGED, true); return true; } case R.id.batch_unflag_op: { setFlag(selection, Flag.FLAGGED, false); return true; } case R.id.app_settings: { onEditPrefs(); return true; } } if (mQueryString != null) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.check_mail: { if (mFolderName != null) { checkMail(mAccount, mFolderName); } return true; } case R.id.send_messages: { mController.sendPendingMessages(mAccount, mAdapter.mListener); return true; } case R.id.list_folders: { onShowFolderList(); return true; } case R.id.mark_all_as_read: { if (mFolderName != null) { onMarkAllAsRead(mAccount, mFolderName); } return true; } case R.id.folder_settings: { if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; } case R.id.account_settings: { onEditAccount(); return true; } case R.id.batch_copy_op: { onCopy(selection); return true; } case R.id.batch_archive_op: { onArchive(selection); return true; } case R.id.batch_spam_op: { onSpam(selection); return true; } case R.id.batch_move_op: { onMove(selection); return true; } case R.id.expunge: { if (mCurrentFolder != null) { onExpunge(mAccount, mCurrentFolder.name); } return true; } default: { return super.onOptionsItemSelected(item); } } } private final int[] batch_ops = { R.id.batch_copy_op, R.id.batch_delete_op, R.id.batch_flag_op, R.id.batch_unflag_op, R.id.batch_mark_read_op, R.id.batch_mark_unread_op, R.id.batch_archive_op, R.id.batch_spam_op, R.id.batch_move_op, R.id.batch_select_all, R.id.batch_deselect_all }; private void setOpsState(Menu menu, boolean state, boolean enabled) { for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean anySelected = anySelected(); menu.findItem(R.id.select_all).setVisible(! anySelected); menu.findItem(R.id.batch_ops).setVisible(anySelected); setOpsState(menu, true, anySelected); if (mQueryString != null) { menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.list_folders).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.batch_archive_op).setVisible(false); menu.findItem(R.id.batch_spam_op).setVisible(false); menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); } else { if (mCurrentFolder != null && mCurrentFolder.name.equals(mAccount.getOutboxFolderName())) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } if (!mAccount.hasArchiveFolder()) { menu.findItem(R.id.batch_archive_op).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) { menu.findItem(R.id.batch_spam_op).setVisible(false); } if (!mController.isMoveCapable(mAccount)) { // FIXME: Really we want to do this for all local-only folders if (mCurrentFolder != null && !mAccount.getInboxFolderName().equals(mCurrentFolder.name)) { menu.findItem(R.id.check_mail).setVisible(false); } menu.findItem(R.id.batch_archive_op).setVisible(false); menu.findItem(R.id.batch_spam_op).setVisible(false); menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); } } boolean newFlagState = computeBatchDirection(true); boolean newReadState = computeBatchDirection(false); menu.findItem(R.id.batch_flag_op).setVisible(newFlagState); menu.findItem(R.id.batch_unflag_op).setVisible(!newFlagState); menu.findItem(R.id.batch_mark_read_op).setVisible(newReadState); menu.findItem(R.id.batch_mark_unread_op).setVisible(!newReadState); menu.findItem(R.id.batch_deselect_all).setVisible(anySelected); menu.findItem(R.id.batch_select_all).setEnabled(true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); final MessageInfoHolder holder = mSelectedMessage == null ? (MessageInfoHolder) mAdapter.getItem(info.position) : mSelectedMessage; // don't need this anymore mSelectedMessage = null; final List<MessageInfoHolder> selection = getSelectionFromMessage(holder); switch (item.getItemId()) { case R.id.open: { onOpenMessage(holder); break; } case R.id.select: { setSelected(selection, true); break; } case R.id.deselect: { setSelected(selection, false); break; } case R.id.delete: { onDelete(selection); break; } case R.id.reply: { onReply(holder); break; } case R.id.reply_all: { onReplyAll(holder); break; } case R.id.forward: { onForward(holder); break; } case R.id.send_again: { onResendMessage(holder); break; } case R.id.mark_as_read: { onToggleRead(holder); break; } case R.id.flag: { onToggleFlag(holder); break; } case R.id.archive: { onArchive(selection); break; } case R.id.spam: { onSpam(selection); break; } case R.id.move: { onMove(selection); break; } case R.id.copy: { onCopy(selection); break; } case R.id.send_alternate: { onSendAlternate(mAccount, holder); break; } case R.id.same_sender: { MessageList.actionHandle(MessageList.this, "From " + holder.sender, holder.senderAddress, false, null, null); break; } } return super.onContextItemSelected(item); } public void onSendAlternate(Account account, MessageInfoHolder holder) { mController.sendAlternate(this, account, holder.message); } public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); if (bar == null) { return; } bar.setIndeterminate(true); if (status) { bar.setVisibility(ProgressBar.VISIBLE); } else { bar.setVisibility(ProgressBar.INVISIBLE); } } @Override protected void onSwipeRightToLeft(final MotionEvent e1, final MotionEvent e2) { // Handle right-to-left as an un-select handleSwipe(e1, false); } @Override protected void onSwipeLeftToRight(final MotionEvent e1, final MotionEvent e2) { // Handle left-to-right as a select. handleSwipe(e1, true); } /** * Handle a select or unselect swipe event * @param downMotion Event that started the swipe * @param selected true if this was an attempt to select (i.e. left to right). */ private void handleSwipe(final MotionEvent downMotion, final boolean selected) { int position = mListView.pointToPosition((int) downMotion.getX(), (int) downMotion.getY()); if (position != AdapterView.INVALID_POSITION) { MessageInfoHolder msgInfoHolder = (MessageInfoHolder) mAdapter.getItem(position); if (msgInfoHolder != null && msgInfoHolder.selected != selected) { msgInfoHolder.selected = selected; mSelectedCount += (selected ? 1 : -1); mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position); // remember which message was originally selected, in case the list changes while the // dialog is up mSelectedMessage = message; if (message == null) { return; } getMenuInflater().inflate(R.menu.message_list_context, menu); menu.setHeaderTitle(message.message.getSubject()); if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } Account account = message.message.getFolder().getAccount(); if (!mController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!mController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (!account.hasArchiveFolder()) { menu.findItem(R.id.archive).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(account.getSpamFolderName())) { menu.findItem(R.id.spam).setVisible(false); } if (message.selected) { menu.findItem(R.id.select).setVisible(false); menu.findItem(R.id.deselect).setVisible(true); } else { menu.findItem(R.id.select).setVisible(true); menu.findItem(R.id.deselect).setVisible(false); } } class MessageListAdapter extends BaseAdapter { private final List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private final ActivityListener mListener = new ActivityListener() { @Override public void informUserOfStatus() { mHandler.refreshTitle(); } @Override public void synchronizeMailboxStarted(Account account, String folder) { if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } super.synchronizeMailboxStarted(account, folder); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } super.synchronizeMailboxFailed(account, folder, message); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, true); } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) { MessageInfoHolder holder = getMessage(message); if (holder == null) { Log.w(K9.LOG_TAG, "Got callback to remove non-existent message with UID " + message.getUid()); } else { removeMessages(Collections.singletonList(holder)); } } @Override public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.progress(true); if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesRemoveMessage(Account account, String folder, Message message) { MessageInfoHolder holder = getMessage(message); if (holder != null) { removeMessages(Collections.singletonList(holder)); } } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages, false); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, false); } @Override public void searchStats(AccountStats stats) { mUnreadMessageCount = stats.unreadMessageCount; super.searchStats(stats); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; } super.folderStatusChanged(account, folder, unreadMessageCount); } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { MessageReference ref = new MessageReference(); ref.accountUuid = account.getUuid(); ref.folderName = folder; ref.uid = oldUid; MessageInfoHolder holder = getMessage(ref); if (holder != null) { holder.uid = newUid; holder.message.setUid(newUid); } } }; private boolean updateForMe(Account account, String folder) { if ((account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; } else { return false; } } private Drawable mAttachmentIcon; private Drawable mAnsweredIcon; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_email_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_answered_small); } public void markAllMessagesAsDirty() { for (MessageInfoHolder holder : mAdapter.messages) { holder.dirty = true; } } public void pruneDirtyMessages() { synchronized (mAdapter.messages) { Iterator<MessageInfoHolder> iter = mAdapter.messages.iterator(); while (iter.hasNext()) { MessageInfoHolder holder = iter.next(); if (holder.dirty) { if (holder.selected) { mSelectedCount toggleBatchButtons(); } mAdapter.removeMessages(Collections.singletonList(holder)); } } } } /** * @param holders * Never {@code null}. */ public void removeMessages(List<MessageInfoHolder> holders) { mHandler.removeMessages(holders); } private void addOrUpdateMessage(Account account, String folderName, Message message, boolean verifyAgainstSearch) { List<Message> messages = new ArrayList<Message>(); messages.add(message); addOrUpdateMessages(account, folderName, messages, verifyAgainstSearch); } private void addOrUpdateMessages(final Account account, final String folderName, final List<Message> providedMessages, final boolean verifyAgainstSearch) { // we copy the message list because the callback doesn't expect // the callbacks to mutate it. final List<Message> messages = new ArrayList<Message>(providedMessages); boolean needsSort = false; final List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); List<Message> messagesToSearch = new ArrayList<Message>(); // cache field into local variable for faster access for JVM without JIT final MessageHelper messageHelper = mMessageHelper; for (Message message : messages) { MessageInfoHolder m = getMessage(message); if (message.isSet(Flag.DELETED)) { if (m != null) { messagesToRemove.add(m); } } else { final Folder messageFolder = message.getFolder(); final Account messageAccount = messageFolder.getAccount(); if (m == null) { if (updateForMe(account, folderName)) { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } else { if (mQueryString != null) { if (verifyAgainstSearch) { messagesToSearch.add(message); } else { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } } } } else { m.dirty = false; // as we reload the message, unset its dirty flag messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, account), account); needsSort = true; } } } if (!messagesToSearch.isEmpty()) { mController.searchLocalMessages(mAccountUuids, mFolderNames, messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY), mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, new MessagingListener() { @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages, false); } }); } if (!messagesToRemove.isEmpty()) { removeMessages(messagesToRemove); } if (!messagesToAdd.isEmpty()) { mHandler.addMessages(messagesToAdd); } if (needsSort) { mHandler.sortMessages(); mHandler.resetUnreadCount(); } } public MessageInfoHolder getMessage(Message message) { return getMessage(message.makeMessageReference()); } // XXX TODO - make this not use a for loop public MessageInfoHolder getMessage(MessageReference messageReference) { synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { /* * 2010-06-21 - cketti * Added null pointer check. Not sure what's causing 'holder' * to be null. See log provided in issue 1749, comment #15. * * Please remove this comment once the cause was found and the * bug(?) fixed. */ if ((holder != null) && holder.message.equalsReference(messageReference)) { return holder; } } } return null; } public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; try { LocalStore localStore = account.getLocalStore(); local_folder = localStore.getFolder(folder); return new FolderInfoHolder(context, local_folder, account); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ", e); return null; } finally { if (local_folder != null) { local_folder.close(); } } } private final OnClickListener flagClickListener = new OnClickListener() { @Override public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); } }; @Override public int getCount() { return messages.size(); } @Override public long getItemId(int position) { try { MessageInfoHolder messageHolder = (MessageInfoHolder) getItem(position); if (messageHolder != null) { return messageHolder.message.getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG, "getItemId(" + position + ") ", e); } return -1; } public Object getItem(long position) { return getItem((int)position); } @Override public Object getItem(int position) { try { synchronized (mAdapter.messages) { if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } @Override public View getView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { if (mTouchView) { view = mInflater.inflate(R.layout.message_list_item_touchable, parent, false); view.setId(R.layout.message_list_item); } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); } } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.preview = (TextView) view.findViewById(R.id.preview); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(flagClickListener); if (!mStars) { holder.flagged.setVisibility(View.GONE); } if (mCheckboxes) { holder.selected.setVisibility(View.VISIBLE); } if (holder.selected != null) { holder.selected.setOnCheckedChangeListener(holder); } holder.subject.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListSubject()); holder.date.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListDate()); if (mTouchView) { holder.preview.setLines(mPreviewLines); holder.preview.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListPreview()); } else { holder.from.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListSender()); } view.setTag(holder); } if (message != null) { bindView(position, view, holder, message); } else { // This branch code is triggered when the local store // hands us an invalid message holder.chip.getBackground().setAlpha(0); holder.subject.setText(getString(R.string.general_no_subject)); holder.subject.setTypeface(null, Typeface.NORMAL); String noSender = getString(R.string.general_no_sender); if (holder.preview != null) { holder.preview.setText(noSender, TextView.BufferType.SPANNABLE); Spannable str = (Spannable) holder.preview.getText(); str.setSpan(new StyleSpan(Typeface.NORMAL), 0, noSender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new AbsoluteSizeSpan(mFontSizes.getMessageListSender(), true), 0, noSender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { holder.from.setText(noSender); holder.from.setTypeface(null, Typeface.NORMAL); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } holder.date.setText(getString(R.string.general_no_date)); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); if (!mCheckboxes) { holder.selected.setVisibility(View.GONE); } holder.flagged.setChecked(false); } return view; } /** * Associate model data to view object. * * @param position * The position of the item within the adapter's data set of * the item whose view we want. * @param view * Main view component to alter. Never <code>null</code>. * @param holder * Convenience view holder - eases access to <tt>view</tt> * child views. Never <code>null</code>. * @param message * Never <code>null</code>. */ private void bindView(final int position, final View view, final MessageViewHolder holder, final MessageInfoHolder message) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag(position); holder.flagged.setChecked(message.flagged); // So that the mSelectedCount is only incremented/decremented // when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); if (!mCheckboxes) { holder.selected.setVisibility(message.selected ? View.VISIBLE : View.GONE); } holder.chip.setBackgroundDrawable(message.message.getFolder().getAccount().generateColorChip().drawable()); holder.chip.getBackground().setAlpha(message.read ? 127 : 255); view.getBackground().setAlpha(message.downloaded ? 0 : 127); if ((message.message.getSubject() == null) || message.message.getSubject().equals("")) { holder.subject.setText(getText(R.string.general_no_subject)); } else { holder.subject.setText(message.message.getSubject()); } int senderTypeface = message.read ? Typeface.NORMAL : Typeface.BOLD; if (holder.preview != null) { /* * In the touchable UI, we have previews. Otherwise, we * have just a "from" line. * Because text views can't wrap around each other(?) we * compose a custom view containing the preview and the * from. */ holder.preview.setText(new SpannableStringBuilder(recipientSigil(message)) .append(message.sender).append(" ").append(message.message.getPreview()), TextView.BufferType.SPANNABLE); Spannable str = (Spannable)holder.preview.getText(); // Create a span section for the sender, and assign the correct font size and weight. str.setSpan(new StyleSpan(senderTypeface), 0, message.sender.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new AbsoluteSizeSpan(mFontSizes.getMessageListSender(), true), 0, message.sender.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // set span for preview message. str.setSpan(new ForegroundColorSpan(Color.rgb(128, 128, 128)), // How do I can specify the android.R.attr.textColorTertiary message.sender.length() + 1, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { holder.from.setText(new SpannableStringBuilder(recipientSigil(message)).append(message.sender)); holder.from.setTypeface(null, senderTypeface); } holder.date.setText(message.getDate(mMessageHelper)); holder.subject.setCompoundDrawablesWithIntrinsicBounds( message.answered ? mAnsweredIcon : null, // left null, // top message.message.hasAttachments() ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } private String recipientSigil(MessageInfoHolder message) { if (message.message.toMe()) { return getString(R.string.messagelist_sent_to_me_sigil); } else if (message.message.ccMe()) { return getString(R.string.messagelist_sent_cc_me_sigil); } else { return ""; } } @Override public boolean hasStableIds() { return true; } public boolean isItemSelectable(int position) { if (position < mAdapter.messages.size()) { return true; } else { return false; } } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position != -1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message.selected != isChecked) { if (isChecked) { mSelectedCount++; } else if (mSelectedCount > 0) { mSelectedCount } // We must set the flag before showing the buttons as the // buttons text depends on what is selected. message.selected = isChecked; if (!mCheckboxes) { if (isChecked) { selected.setVisibility(View.VISIBLE); } else { selected.setVisibility(View.GONE); } } toggleBatchButtons(); } } } } private View getFooterView(ViewGroup parent) { if (mFooterView == null) { mFooterView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); mFooterView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar) mFooterView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView) mFooterView.findViewById(R.id.main_text); mFooterView.setTag(holder); } return mFooterView; } private void updateFooterView() { FooterViewHolder holder = (FooterViewHolder) mFooterView.getTag(); if (mCurrentFolder != null && mAccount != null) { if (mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (!mCurrentFolder.lastCheckFailed) { if (mAccount.getDisplayCount() == 0) { holder.main.setText(getString(R.string.message_list_load_more_messages_action)); } else { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } } else { holder.progress.setVisibility(ProgressBar.INVISIBLE); } } private void hideBatchButtons() { if (mBatchButtonArea.getVisibility() != View.GONE) { mBatchButtonArea.setVisibility(View.GONE); mBatchButtonArea.startAnimation( AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); } } private void showBatchButtons() { if (mBatchButtonArea.getVisibility() != View.VISIBLE) { mBatchButtonArea.setVisibility(View.VISIBLE); Animation animation = AnimationUtils.loadAnimation(this, R.anim.footer_appear); animation.setAnimationListener(this); mBatchButtonArea.startAnimation(animation); } } private void toggleBatchButtons() { runOnUiThread(new Runnable() { @Override public void run() { if (mSelectedCount < 0) { mSelectedCount = 0; } int readButtonIconId; int flagButtonIconId; if (mSelectedCount == 0) { readButtonIconId = R.drawable.ic_button_mark_read; flagButtonIconId = R.drawable.ic_button_flag; hideBatchButtons(); } else { boolean newReadState = computeBatchDirection(false); if (newReadState) { readButtonIconId = R.drawable.ic_button_mark_read; } else { readButtonIconId = R.drawable.ic_button_mark_unread; } boolean newFlagState = computeBatchDirection(true); if (newFlagState) { flagButtonIconId = R.drawable.ic_button_flag; } else { flagButtonIconId = R.drawable.ic_button_unflag; } showBatchButtons(); } mBatchReadButton.setImageResource(readButtonIconId); mBatchFlagButton.setImageResource(flagButtonIconId); } }); } static class FooterViewHolder { public ProgressBar progress; public TextView main; } private boolean computeBatchDirection(boolean flagged) { boolean newState = false; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (flagged) { if (!holder.flagged) { newState = true; break; } } else { if (!holder.read) { newState = true; break; } } } } } return newState; } private boolean anySelected() { synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { return true; } } } return false; } @Override public void onClick(View v) { boolean newState = false; List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); if (v == mBatchDoneButton) { setAllSelected(false); return; } if (v == mBatchFlagButton) { newState = computeBatchDirection(true); } else { newState = computeBatchDirection(false); } if (v == mBatchArchiveButton) { final List<MessageInfoHolder> selection = getSelectionFromCheckboxes(); onArchive(selection); return; } if (v == mBatchMoveButton) { final List<MessageInfoHolder> selection = getSelectionFromCheckboxes(); onMove(selection); return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (v == mBatchDeleteButton) { removeHolderList.add(holder); } else if (v == mBatchFlagButton) { holder.flagged = newState; } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); } } } mAdapter.removeMessages(removeHolderList); if (!messageList.isEmpty()) { if (v == mBatchDeleteButton) { mController.deleteMessages(messageList.toArray(EMPTY_MESSAGE_ARRAY), null); mSelectedCount = 0; toggleBatchButtons(); } else { mController.setFlag(messageList.toArray(EMPTY_MESSAGE_ARRAY), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } } else { // Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } } mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } private void setSelected(final List<MessageInfoHolder> holders, final boolean newState) { for (final MessageInfoHolder holder : holders) { if (holder.selected != newState) { holder.selected = newState; mSelectedCount += (newState ? 1 : -1); } } mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } /** * @param holders * Messages to update. Never {@code null}. * @param flag * Flag to be updated on the specified messages. Never * {@code null}. * @param newState * State to set for the given flag. */ private void setFlag(final List<MessageInfoHolder> holders, final Flag flag, final boolean newState) { if (holders.isEmpty()) { return; } final Message[] messageList = new Message[holders.size()]; int i = 0; for (final Iterator<MessageInfoHolder> iterator = holders.iterator(); iterator.hasNext(); i++) { final MessageInfoHolder holder = iterator.next(); messageList[i] = holder.message; if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } mController.setFlag(messageList, flag, newState); mHandler.sortMessages(); } /** * Display the message move activity. * * @param holders * Never {@code null}. */ private void onMove(final List<MessageInfoHolder> holders) { if (!checkCopyOrMovePossible(holders, FolderOperation.MOVE)) { return; } final Folder folder = holders.size() == 1 ? holders.get(0).message.getFolder() : mCurrentFolder.folder; displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_MOVE, folder, holders); } /** * Display the message copy activity. * * @param holders * Never {@code null}. */ private void onCopy(final List<MessageInfoHolder> holders) { if (!checkCopyOrMovePossible(holders, FolderOperation.COPY)) { return; } final Folder folder = holders.size() == 1 ? holders.get(0).message.getFolder() : mCurrentFolder.folder; displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_COPY, folder, holders); } /** * Helper method to manage the invocation of * {@link #startActivityForResult(Intent, int)} for a folder operation * ({@link ChooseFolder} activity), while saving a list of associated * messages. * * @param requestCode * If >= 0, this code will be returned in onActivityResult() when * the activity exits. * @param folder * Never {@code null}. * @param holders * Messages to be affected by the folder operation. Never * {@code null}. * @see #startActivityForResult(Intent, int) */ private void displayFolderChoice(final int requestCode, final Folder folder, final List<MessageInfoHolder> holders) { final Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, folder.getAccount().getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName()); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, folder.getAccount().getLastSelectedFolderName()); // remember the selected messages for #onActivityResult mActiveMessages = holders; startActivityForResult(intent, requestCode); } /** * @param holders * Never {@code null}. */ private void onArchive(final List<MessageInfoHolder> holders) { final String folderName = holders.get(0).message.getFolder().getAccount().getArchiveFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } // TODO one should separate messages by account and call move afterwards // (because each account might have a specific Archive folder name) move(holders, folderName); } /** * @param holders * Never {@code null}. */ private void onSpam(final List<MessageInfoHolder> holders) { if (K9.confirmSpam()) { // remember the message selection for #onCreateDialog(int) mActiveMessages = holders; showDialog(R.id.dialog_confirm_spam); } else { onSpamConfirmed(holders); } } /** * @param holders * Never {@code null}. */ private void onSpamConfirmed(final List<MessageInfoHolder> holders) { final String folderName = holders.get(0).message.getFolder().getAccount().getSpamFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } // TODO one should separate messages by account and call move afterwards // (because each account might have a specific Spam folder name) move(holders, folderName); } private static enum FolderOperation { COPY, MOVE } /** * Display an Toast message if any message isn't synchronized * * @param holders * Never <code>null</code>. * @param operation * Never {@code null}. * * @return <code>true</code> if operation is possible */ private boolean checkCopyOrMovePossible(final List<MessageInfoHolder> holders, final FolderOperation operation) { if (holders.isEmpty()) { return false; } boolean first = true; for (final MessageInfoHolder holder : holders) { final Message message = holder.message; if (first) { first = false; // account check final Account account = message.getFolder().getAccount(); if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(account)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(account))) { return false; } } // message check if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(message))) { final Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return false; } } return true; } /** * Helper method to get a List of message ready to be processed. This implementation will return a list containing the sole argument. * * @param holder Never {@code null}. * @return Never {@code null}. */ private List<MessageInfoHolder> getSelectionFromMessage(final MessageInfoHolder holder) { final List<MessageInfoHolder> selection = Collections.singletonList(holder); return selection; } /** * Helper method to get a List of message ready to be processed. This implementation will iterate over messages and choose the checked ones. * * @return Never {@code null}. */ private List<MessageInfoHolder> getSelectionFromCheckboxes() { final List<MessageInfoHolder> selection = new ArrayList<MessageInfoHolder>(); synchronized (mAdapter.messages) { for (final MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { selection.add(holder); } } } return selection; } /** * Copy the specified messages to the specified folder. * * @param holders Never {@code null}. * @param destination Never {@code null}. */ private void copy(final List<MessageInfoHolder> holders, final String destination) { copyOrMove(holders, destination, FolderOperation.COPY); } /** * Move the specified messages to the specified folder. * * @param holders Never {@code null}. * @param destination Never {@code null}. */ private void move(final List<MessageInfoHolder> holders, final String destination) { copyOrMove(holders, destination, FolderOperation.MOVE); } /** * The underlying implementation for {@link #copy(List, String)} and * {@link #move(List, String)}. This method was added mainly because those 2 * methods share common behavior. * * @param holders * Never {@code null}. * @param destination * Never {@code null}. * @param operation * Never {@code null}. */ private void copyOrMove(final List<MessageInfoHolder> holders, final String destination, final FolderOperation operation) { if (K9.FOLDER_NONE.equalsIgnoreCase(destination)) { return; } boolean first = true; Account account = null; String folderName = null; final List<Message> messages = new ArrayList<Message>(holders.size()); for (final MessageInfoHolder holder : holders) { final Message message = holder.message; if (first) { first = false; folderName = message.getFolder().getName(); account = message.getFolder().getAccount(); if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(account)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(account))) { // account is not copy/move capable return; } } else if (!account.equals(message.getFolder().getAccount()) || !folderName.equals(message.getFolder().getName())) { // make sure all messages come from the same account/folder? return; } if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(message))) { final Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); // XXX return meaningful error value? // message isn't synchronized return; } messages.add(message); } if (operation == FolderOperation.MOVE) { mController.moveMessages(account, folderName, messages.toArray(new Message[messages.size()]), destination, null); mHandler.removeMessages(holders); } else { mController.copyMessages(account, folderName, messages.toArray(new Message[messages.size()]), destination, null); } } protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); } }
package org.objectweb.proactive.p2p.service; import java.io.IOException; import java.io.Serializable; import java.util.Random; import java.util.Vector; import org.apache.log4j.Logger; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.Body; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.ProActiveInternalObject; import org.objectweb.proactive.Service; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.core.Constants; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.body.request.RequestFilter; import org.objectweb.proactive.core.config.PAProperties; import org.objectweb.proactive.core.config.ProActiveConfiguration; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl; import org.objectweb.proactive.core.util.URIBuilder; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.wrapper.StringWrapper; import org.objectweb.proactive.p2p.service.exception.P2POldMessageException; import org.objectweb.proactive.p2p.service.exception.PeerDoesntExist; import org.objectweb.proactive.p2p.service.messages.DumpAcquaintancesMessage; import org.objectweb.proactive.p2p.service.messages.ExplorationMessage; import org.objectweb.proactive.p2p.service.messages.Message; import org.objectweb.proactive.p2p.service.node.P2PNodeLookup; import org.objectweb.proactive.p2p.service.node.P2PNodeManager; import org.objectweb.proactive.p2p.service.util.P2PConstants; import org.objectweb.proactive.p2p.service.util.UniversalUniqueID; /** * <p>ProActive Peer-to-Peer Service.</p> * <p>This class is made to be actived.</p> * * * */ public class P2PService implements InitActive, P2PConstants, Serializable, ProActiveInternalObject { /** Logger. */ private static final Logger logger = ProActiveLogger.getLogger(Loggers.P2P_SERVICE); /** ProActive Group of acquaintances. **/ // private P2PService acquaintances; /** * ProActive Group representing <code>acquaintances</code>. */ public P2PAcquaintanceManager acquaintanceManager_active; /** * Reference to the current Node. */ private Node p2pServiceNode = null; static { ProActiveConfiguration.load(); } private static final int MSG_MEMORY = (PAProperties.PA_P2P_MSG_MEMORY.getValue() == null) ? 0 : Integer .parseInt(PAProperties.PA_P2P_MSG_MEMORY.getValue()); // private static final int NOA = Integer.parseInt(System.getProperty( // P2PConstants.PROPERTY_NOA)); private static final int EXPL_MSG = Integer.parseInt(PAProperties.PA_P2P_EXPLORING_MSG.getValue()) - 1; static public final long ACQ_TO = Long.parseLong(PAProperties.PA_P2P_NODES_ACQUISITION_T0.getValue()); static final long TTU = Long.parseLong(PAProperties.PA_P2P_TTU.getValue()); //static public final int NOA = Integer.parseInt(System.getProperty( // P2PConstants.PROPERTY_NOA)); static final int TTL = Integer.parseInt(PAProperties.PA_P2P_TTL.getValue()); /** * Randomizer uses in <code>shouldBeAcquaintance</code> method. */ private static final Random randomizer = new Random(); /** * Sequence number list of received messages. */ private Vector<UniversalUniqueID> oldMessageList = new Vector<UniversalUniqueID>(MSG_MEMORY); public P2PNodeManager nodeManager = null; /** * A collection of not full <code>P2PNodeLookup</code>. */ private Vector<P2PNodeLookup> waitingNodesLookup = new Vector<P2PNodeLookup>(); private Vector<P2PNodeLookup> waitingMaximunNodesLookup = new Vector<P2PNodeLookup>(); public P2PService stubOnThis = null; // For asking nodes public Service service = null; /** * Starting list of superpeers */ private Vector<String> superPeers; public RequestFilter filter = new RequestFilter() { /** * @see org.objectweb.proactive.core.body.request.RequestFilter#acceptRequest(org.objectweb.proactive.core.body.request.Request) */ public boolean acceptRequest(Request request) { String requestName = request.getMethodName(); if (requestName.compareToIgnoreCase("askingNode") == 0) { return false; } return true; } }; public static String getHostNameAndPortFromUrl(String url) { //String validUrl = checkUrl(url); // String validUrl = url; // int n = validUrl.indexOf("//"); // int m = validUrl.lastIndexOf("/"); // looking for the end of the host // if (m == (n + 1)) { // //the url has no name i.e it is a host url // return validUrl.substring(n + 2, validUrl.length()); // } else { // //check if there is a port // return validUrl.substring(n + 2, m); return URIBuilder.getHostNameFromUrl(url) + ":" + URIBuilder.getPortNumber(url); } // Class Constructors /** * The empty constructor. * * @see org.objectweb.proactive.api.PAActiveObject */ public P2PService() { this.superPeers = new Vector<String>(); } public P2PService(Vector<String> superPeers) { this.superPeers = superPeers; } // Public Class methods /** * Contact all specified peers to enter in the existing P2P network. * @param peers a list of peers URL. */ public void firstContact(Vector<String> peers) { System.out.println(">>>>>>>>>>>>>>>>> Have to conctact: " + peers.size()); this.acquaintanceManager_active.setPreferedAcq(peers); } /** * Just to test if the peer is alive. */ public void heartBeat() { logger.debug("Heart-beat message received"); } public void dumpAcquaintances() { DumpAcquaintancesMessage m = new DumpAcquaintancesMessage(10, this.generateUuid(), this.stubOnThis); this.dumpAcquaintances(m); } public void dumpAcquaintances(Message m) { m.setSender(this.stubOnThis); this.isAnOldMessage(m.getUuid()); //execute locally m.execute(this); //start the flooding // m.transmit(this.acquaintanceManager_active.getAcquaintances()); m.transmit(this); } /** * Start the exploration process * Build an exploration message and send it to the current acquaintances * */ public void explore() { ExplorationMessage m = new ExplorationMessage(10, this.generateUuid(), this.stubOnThis); // m.transmit(this.acquaintanceManager_active.getAcquaintances()); // this.acquaintanceManager_active.transmit(m); m.transmit(this); } public void requestNodes(Message m) { m.execute(this); System.out.println("AFTER EXECUTE"); //m.transmit(this.acquaintanceManager.getAcquaintances()); //this.acquaintanceManager_active.transmit(m); try { if (shouldTransmit(m)) { logger.debug("SHOULD TRANSMIT"); m.transmit(this); } } catch (P2POldMessageException e) { System.out.println("P2PService.requestNodes()"); //NOTHING } } public void message(Message message) { // System.out.println("P2PService.message()"+Thread.currentThread()); UniversalUniqueID uuid = message.getUuid(); int ttl = message.getTTL(); if (uuid != null) { logger.debug("Message " + message + " received with #" + uuid); ttl message.setTTL(ttl); } boolean transmit; try { transmit = shouldTransmit(message); } catch (P2POldMessageException e) { logger.debug("P2PService.message() received an old message"); return; } if (shouldExecute(message)) { message.execute(this); } if (transmit) { // message.transmit(this.acquaintanceManager_active.getAcquaintances()); // this.acquaintanceManager_active.transmit(message); message.transmit(this); } } private boolean shouldExecute(Message message) { return message.shouldExecute(); } /** Put in a <code>P2PNodeLookup</code>, the number of asked nodes. * @param numberOfNodes the number of asked nodes. * @param nodeFamilyRegexp the regexp for the famili, null or empty String for all. * @param vnName Virtual node name. * @param jobId of the vn. * @return the number of asked nodes. */ public P2PNodeLookup getNodes(int numberOfNodes, String nodeFamilyRegexp, String vnName, String jobId) { Object[] params = new Object[5]; params[0] = new Integer(numberOfNodes); params[1] = this.stubOnThis; params[2] = vnName; params[3] = jobId; params[4] = nodeFamilyRegexp; P2PNodeLookup lookup_active = null; try { lookup_active = (P2PNodeLookup) PAActiveObject.newActive(P2PNodeLookup.class.getName(), params, this.p2pServiceNode); PAActiveObject.enableAC(lookup_active); if (numberOfNodes == MAX_NODE) { this.waitingMaximunNodesLookup.add(lookup_active); } else { this.waitingNodesLookup.add(lookup_active); } } catch (ActiveObjectCreationException e) { logger.fatal("Couldn't create an active lookup", e); return null; } catch (NodeException e) { logger.fatal("Couldn't connect node to creat", e); return null; } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Couldn't enable AC for a nodes lookup", e); } } if (logger.isInfoEnabled()) { if (numberOfNodes != MAX_NODE) { logger.info("Asking for " + numberOfNodes + " nodes"); } else { logger.info("Asking for maxinum nodes"); } } return lookup_active; } /** Put in a <code>P2PNodeLookup</code>, the number of asked nodes. * @param numberOfNodes the number of asked nodes. * @param vnName Virtual node name. * @param jobId of the vn. * @return the number of asked nodes. */ public P2PNodeLookup getNodes(int numberOfNodes, String vnName, String jobId) { return this.getNodes(numberOfNodes, ".*", vnName, jobId); } /** * Put in a <code>P2PNodeLookup</code> all available nodes during all the * time where it is actived. * @param vnName Virtual node name. * @param jobId * @return an active object where nodes are received. */ public P2PNodeLookup getMaximunNodes(String vnName, String jobId) { return this.getNodes(P2PConstants.MAX_NODE, vnName, jobId); } /** * For load balancing. * @return URL of the node where the P2P service is running. */ public StringWrapper getAddress() { return new StringWrapper(this.p2pServiceNode.getNodeInformation().getURL()); } /** * Remove a no more waiting nodes accessor. * @param accessorToRemove the accessor to remove. */ public void removeWaitingAccessor(P2PNodeLookup accessorToRemove) { this.waitingNodesLookup.remove(accessorToRemove); logger.debug("Accessor succefuly removed"); } /** * @return the list of current acquaintances. */ public Vector getAcquaintanceList() { return this.acquaintanceManager_active.getAcquaintanceList(); } public P2PAcquaintanceManager getAcquaintanceManager() { return this.acquaintanceManager_active; } public void remove(P2PService p, Vector<String> acquaintancesURLs) { this.acquaintanceManager_active.remove(p, acquaintancesURLs); } // public P2PService randomPeer() { // return this.acquaintanceManager.randomPeer(); // Private class method /** * <b>* ONLY FOR INTERNAL USE *</b> * Generates a UUID and mark it as already received * @return a random UUID for sending message. */ public UniversalUniqueID generateUuid() { UniversalUniqueID uuid = UniversalUniqueID.randomUUID(); oldMessageList.add(uuid); logger.debug(" UUID generated with #" + uuid); return uuid; } /** * Transmit this message on behalf of another local * active object (P2PAcquaintanceManager * Generates a UUID * @param m */ public void transmit(Message m, P2PService p) { m.setUuid(this.generateUuid()); m.setSender(this.stubOnThis); System.out.println(" p.message(m); } /** * If not an old message and ttl > 1 return true else false. * @param ttl TTL of the message. * @param uuid UUID of the message. * @param remoteService P2PService of the first service. * @return true if you should broadcats, false else. */ private boolean shouldTransmit(Message message) throws P2POldMessageException { P2PService remoteService = message.getSender(); int ttl = message.getTTL(); UniversalUniqueID uuid = message.getUuid(); // is it an old message? boolean isAnOldMessage = this.isAnOldMessage(uuid); // String remoteNodeUrl = null; // try { // remoteNodeUrl = ProActive.getActiveObjectNodeUrl(remoteService); // } catch (Exception e) { // isAnOldMessage = true; //String thisNodeUrl = this.p2pServiceNode.getNodeInformation().getURL(); // if (!isAnOldMessage && !remoteNodeUrl.equals(thisNodeUrl)) { if (!isAnOldMessage) { if (ttl > 0) { logger.debug("Forwarding message request"); return message.shouldTransmit(); } return false; } // it is an old message: nothing to do // NO REMOVE the isDebugEnabled message if (logger.isDebugEnabled()) { if (isAnOldMessage) { logger.debug("Old message request with #" + uuid); } else { logger.debug("The peer is me: "); } } throw new P2POldMessageException(); } /** * If number of acquaintances is less than NOA return <code>true</code>, else * use random factor. * @param remoteService the remote service which is asking acquaintance. * @return <code>true</code> if this peer should be an acquaintance, else * <code>false</code>. */ public boolean shouldBeAcquaintance(P2PService remoteService) { return this.acquaintanceManager_active.shouldBeAcquaintance(remoteService); } /** * If ti's not an old message add the sequence number in the list. * @param uuid the uuid of the message. * @return <code>true</code> if it was an old message, <code>false</code> else. */ private boolean isAnOldMessage(UniversalUniqueID uuid) { if (uuid == null) { return false; } if (oldMessageList.contains(uuid)) { return true; } if (oldMessageList.size() == MSG_MEMORY) { oldMessageList.remove(0); } oldMessageList.add(uuid); return false; } /** * Wake up all node lookups. */ private void wakeUpEveryBody() { for (int i = 0; i < this.waitingNodesLookup.size(); i++) { (this.waitingNodesLookup.get(i)).wakeUp(); } } // Active Object methods /** * @see org.objectweb.proactive.InitActive#initActivity(org.objectweb.proactive.Body) */ public void initActivity(Body body) { logger.debug("Entering initActivity"); this.service = new Service(body); try { // Reference to my current p2pServiceNode this.p2pServiceNode = NodeFactory.getNode(body.getNodeURL()); } catch (NodeException e) { logger.fatal("Couldn't get reference to the local p2pServiceNode", e); } logger.debug("P2P Service running in p2pServiceNode: " + this.p2pServiceNode.getNodeInformation().getURL()); this.stubOnThis = (P2PService) PAActiveObject.getStubOnThis(); Object[] params = new Object[2]; params[0] = this.stubOnThis; params[1] = this.superPeers; try { // Active acquaintances this.acquaintanceManager_active = (P2PAcquaintanceManager) PAActiveObject.newActive( P2PAcquaintanceManager.class.getName(), params, this.p2pServiceNode); logger.debug("P2P acquaintance manager activated"); // logger.debug("Got active group reference"); // Active Node Manager this.nodeManager = (P2PNodeManager) PAActiveObject.newActive(P2PNodeManager.class.getName(), null, this.p2pServiceNode); logger.debug("P2P node manager activated"); } catch (ActiveObjectCreationException e) { logger.fatal("Couldn't create one of managers", e); } catch (NodeException e) { logger.fatal("Couldn't create one the managers", e); } logger.debug("Exiting initActivity"); } public static P2PService getLocalP2PService() throws Exception { UniversalBody body = ProActiveRuntimeImpl.getProActiveRuntime().getActiveObjects(P2P_NODE_NAME, P2PService.class.getName()).get(0); return (P2PService) MOP.newInstance(P2PService.class, (Object[]) null, Constants.DEFAULT_BODY_PROXY_CLASS_NAME, new Object[] { body }); } /** * Ask to the Load Balancer object if the state is underloaded * @param ranking * @return <code>true</code> if the state is underloaded, <code>false</code> else. */ public boolean amIUnderloaded(double ranking) { // if (ranking >= 0) { // return p2pLoadBalancer.AreYouUnderloaded(ranking); // return p2pLoadBalancer.AreYouUnderloaded(); //TEST FAb return true; } public P2PService randomPeer() throws PeerDoesntExist { return this.acquaintanceManager_active.randomPeer(); } }
package com.fsck.k9.activity; // import android.os.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.util.Config; import android.util.Log; import android.view.*; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.*; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.CompoundButton.OnCheckedChangeListener; import com.fsck.k9.*; import com.fsck.k9.MessagingController.SORT_TYPE; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.mail.*; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * MessageList is the primary user interface for the program. This * Activity shows a list of messages. * From this Activity the user can perform all standard message * operations. * */ public class MessageList extends K9Activity implements OnClickListener, AdapterView.OnItemClickListener { private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_STARTUP = "startup"; private static final String EXTRA_FOLDER = "folder"; private static final String STATE_KEY_LIST = "com.fsck.k9.activity.messagelist_state"; private static final String STATE_CURRENT_FOLDER = "com.fsck.k9.activity.messagelist_folder"; private static final String STATE_KEY_SELECTION = "com.fsck.k9.activity.messagelist_selection"; private static final String STATE_KEY_SELECTED_COUNT = "com.fsck.k9.activity.messagelist_selected_count"; private static final int WIDGET_NONE = 1; private static final int WIDGET_FLAG = 2; private static final int WIDGET_MULTISELECT = 3; private static final int[] colorChipResIds = new int[] { R.drawable.appointment_indicator_leftside_1, R.drawable.appointment_indicator_leftside_2, R.drawable.appointment_indicator_leftside_3, R.drawable.appointment_indicator_leftside_4, R.drawable.appointment_indicator_leftside_5, R.drawable.appointment_indicator_leftside_6, R.drawable.appointment_indicator_leftside_7, R.drawable.appointment_indicator_leftside_8, R.drawable.appointment_indicator_leftside_9, R.drawable.appointment_indicator_leftside_10, R.drawable.appointment_indicator_leftside_11, R.drawable.appointment_indicator_leftside_12, R.drawable.appointment_indicator_leftside_13, R.drawable.appointment_indicator_leftside_14, R.drawable.appointment_indicator_leftside_15, R.drawable.appointment_indicator_leftside_16, R.drawable.appointment_indicator_leftside_17, R.drawable.appointment_indicator_leftside_18, R.drawable.appointment_indicator_leftside_19, R.drawable.appointment_indicator_leftside_20, R.drawable.appointment_indicator_leftside_21, }; private ListView mListView; private int mSelectedWidget = WIDGET_FLAG; private int colorChipResId; private MessageListAdapter mAdapter; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private Account mAccount; /** * Stores the name of the folder that we want to open as soon as possible * after load. It is set to null once the folder has been opened once. */ private String mFolderName; private MessageListHandler mHandler = new MessageListHandler(); private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; private boolean mStartup = false; private boolean mLeftHanded = false; private int mSelectedCount = 0; private View mBatchButtonArea; private Button mBatchReadButton; private Button mBatchDeleteButton; private Button mBatchFlagButton; class MessageListHandler extends Handler { public void removeMessage(final List<MessageInfoHolder> messages) { runOnUiThread(new Runnable() { public void run() { for (MessageInfoHolder message : messages) { if (message != null && message.selected && mSelectedCount > 0) { mSelectedCount } mAdapter.messages.remove(message); } mAdapter.notifyDataSetChanged(); configureBatchButtons(); } }); } public void addMessages(List<MessageInfoHolder> messages) { boolean wasEmpty = mAdapter.messages.isEmpty(); for (final MessageInfoHolder message : messages) { runOnUiThread(new Runnable() { public void run() { int index = Collections.binarySearch(mAdapter.messages, message); if (index < 0) { index = (index * -1) - 1; } mAdapter.messages.add(index, message); } }); } if (wasEmpty) { runOnUiThread(new Runnable() { public void run() { mListView.setSelection(0); mAdapter.notifyDataSetChanged(); } }); } } private void sortMessages() { runOnUiThread(new Runnable() { public void run() { synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages); } mAdapter.notifyDataSetChanged(); } }); } public void folderLoading(String folder, boolean loading) { if (mCurrentFolder.name == folder) { mCurrentFolder.loading = loading; } } public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { showProgressIndicator(progress); } }); } public void folderSyncing(final String folder) { runOnUiThread(new Runnable() { public void run() { String dispString = mAccount.getDescription(); if (folder != null) { dispString += " (" + getString(R.string.status_loading) + folder + ")"; } setTitle(dispString); } }); } public void sendingOutbox(final boolean sending) { runOnUiThread(new Runnable() { public void run() { String dispString = mAccount.getDescription(); if (sending) { dispString += " (" + getString(R.string.status_sending) + ")"; } setTitle(dispString); } }); } } /** * This class is responsible for reloading the list of local messages for a * given folder, notifying the adapter that the message have been loaded and * queueing up a remote update of the folder. */ public static void actionHandleFolder(Context context, Account account, String folder, boolean startup) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT, account); intent.putExtra(EXTRA_STARTUP, startup); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } context.startActivity(intent); } public void onItemClick(AdapterView parent, View v, int position, long id) { // Debug.stopMethodTracing(); if ((position+1) == (mAdapter.getCount())) { MessagingController.getInstance(getApplication()).loadMoreMessages( mAccount, mFolderName, mAdapter.mListener); return; } else if (mSelectedWidget == WIDGET_MULTISELECT) { CheckBox selected = (CheckBox) v.findViewById(R.id.selected_checkbox); selected.setChecked(!selected.isChecked()); } else { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { // Debug.startMethodTracing("k9"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.message_list); mListView = (ListView) findViewById(R.id.message_list); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); mListView.setOnItemClickListener(this); registerForContextMenu(mListView); /* * We manually save and restore the list's state because our adapter is * slow. */ mListView.setSaveEnabled(false); mInflater = getLayoutInflater(); mBatchButtonArea = findViewById(R.id.batch_button_area); mBatchReadButton = (Button) findViewById(R.id.batch_read_button); mBatchReadButton.setOnClickListener(this); mBatchDeleteButton = (Button) findViewById(R.id.batch_delete_button); mBatchDeleteButton.setOnClickListener(this); mBatchFlagButton = (Button) findViewById(R.id.batch_flag_button); mBatchFlagButton.setOnClickListener(this); Intent intent = getIntent(); mAccount = (Account)intent.getSerializableExtra(EXTRA_ACCOUNT); mStartup = (boolean)intent.getBooleanExtra(EXTRA_STARTUP, false); // Take the initial folder into account only if we are *not* restoring the // activity already if (savedInstanceState == null) { mFolderName = intent.getStringExtra(EXTRA_FOLDER); if (mFolderName == null) { mFolderName = mAccount.getAutoExpandFolderName(); } } else { mFolderName = savedInstanceState.getString(STATE_CURRENT_FOLDER); mSelectedCount = savedInstanceState.getInt(STATE_KEY_SELECTED_COUNT); } /* * Since the color chip is always the same color for a given account we just * cache the id of the chip right here. */ colorChipResId = colorChipResIds[mAccount.getAccountNumber() % colorChipResIds.length]; mLeftHanded = mAccount.getLeftHanded(); mAdapter = new MessageListAdapter(); final Object previousData = getLastNonConfigurationInstance(); if (previousData != null) { //noinspection unchecked mAdapter.messages.addAll((List<MessageInfoHolder>) previousData); } mCurrentFolder = mAdapter.getFolder(mFolderName); mListView.setAdapter(mAdapter); if (savedInstanceState != null) { onRestoreListState(savedInstanceState); } setTitle(); } private void onRestoreListState(Bundle savedInstanceState) { String currentFolder = savedInstanceState.getString(STATE_CURRENT_FOLDER); int selectedChild = savedInstanceState.getInt(STATE_KEY_SELECTION, -1); if (selectedChild != 0) { mListView.setSelection(selectedChild); } if (currentFolder != null) { mCurrentFolder = mAdapter.getFolder(currentFolder); } mListView.onRestoreInstanceState(savedInstanceState.getParcelable(STATE_KEY_LIST)); } @Override public void onPause() { super.onPause(); //Debug.stopMethodTracing(); MessagingController.getInstance(getApplication()).removeListener(mAdapter.mListener); } /** * On resume we refresh * messages for any folder that is currently open. This guarantees that things * like unread message count and read status are updated. */ @Override public void onResume() { super.onResume(); MessagingController controller = MessagingController.getInstance(getApplication()); sortType = controller.getSortType(); sortAscending = controller.isSortAscending(sortType); sortDateAscending = controller.isSortAscending(SORT_TYPE.SORT_DATE); controller.addListener(mAdapter.mListener); mAdapter.messages.clear(); mAdapter.notifyDataSetChanged(); controller.listLocalMessages(mAccount, mFolderName, mAdapter.mListener); NotificationManager notifMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(mAccount.getAccountNumber()); notifMgr.cancel(-1000 - mAccount.getAccountNumber()); setTitle(); } private void setTitle() { setTitle( mAccount.getDescription() + " - " + mCurrentFolder.displayName ); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(STATE_KEY_LIST, mListView.onSaveInstanceState()); outState.putInt(STATE_KEY_SELECTION, mListView .getSelectedItemPosition()); outState.putString(STATE_CURRENT_FOLDER, mCurrentFolder.name); outState.putInt(STATE_KEY_SELECTED_COUNT, mSelectedCount); } @Override public Object onRetainNonConfigurationInstance() { return mAdapter.messages; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Shortcuts that work no matter what is selected switch (keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: { if (mBatchButtonArea.hasFocus()) { return false; } else { cycleVisibleWidgets(true); return true; } } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (mBatchButtonArea.hasFocus()) { return false; } else { cycleVisibleWidgets(false); return true; } } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: //case KeyEvent.KEYCODE_BACK: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } }//switch int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_D: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_F: { onForward(message); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; } case KeyEvent.KEYCODE_R: { onReply(message); return true; } case KeyEvent.KEYCODE_G: { onToggleFlag(message); return true; } case KeyEvent.KEYCODE_M: { onMove(message); return true; } case KeyEvent.KEYCODE_Y: { onCopy(message); return true; } case KeyEvent.KEYCODE_Z: { onToggleRead(message); return true; } } } } } finally { return super.onKeyDown(keyCode, event); } }//onKeyDown private void onOpenMessage(MessageInfoHolder message) { if (message.folder.name.equals(mAccount.getDraftsFolderName())) { MessageCompose.actionEditDraft(this, mAccount, message.message); } else { // Need to get the list before the sort starts ArrayList<String> messageUids = new ArrayList<String>(); for (MessageInfoHolder holder : mAdapter.messages) { messageUids.add(holder.uid); } MessageView.actionView(this, mAccount, message.folder.name, message.uid, messageUids); } /* * We set read=true here for UI performance reasons. The actual value will * get picked up on the refresh when the Activity is resumed but that may * take a second or so and we don't want this to show and then go away. I've * gone back and forth on this, and this gives a better UI experience, so I * am putting it back in. */ if (!message.read) { message.read = true; mHandler.sortMessages(); } } public void cycleVisibleWidgets(boolean ascending) { if (ascending) { switch (mSelectedWidget) { case WIDGET_FLAG: { mSelectedWidget = WIDGET_MULTISELECT; break; } case WIDGET_MULTISELECT: { mSelectedWidget = WIDGET_NONE; break; } case WIDGET_NONE: { mSelectedWidget = WIDGET_FLAG; break; } } } else { switch (mSelectedWidget) { case WIDGET_FLAG: { mSelectedWidget=WIDGET_NONE; break; } case WIDGET_NONE: { mSelectedWidget=WIDGET_MULTISELECT; break; } case WIDGET_MULTISELECT: { mSelectedWidget=WIDGET_FLAG; break; } } } configureWidgets(); } private void configureWidgets() { switch (mSelectedWidget) { case WIDGET_FLAG: hideBatchButtons(); break; case WIDGET_NONE: hideBatchButtons(); break; case WIDGET_MULTISELECT: showBatchButtons(); break; } int count = mListView.getChildCount(); for (int i=0; i<count; i++) { setVisibleWidgetsForListItem(mListView.getChildAt(i), mSelectedWidget); } } private void setVisibleWidgetsForListItem(View v, int nextWidget) { Button flagged = (Button) v.findViewById(R.id.flagged); CheckBox selected = (CheckBox) v.findViewById(R.id.selected_checkbox); if (flagged == null || selected == null) { return; } if (nextWidget == WIDGET_NONE) { v.findViewById(R.id.widgets).setVisibility(View.GONE); return; } else { v.findViewById(R.id.widgets).setVisibility(View.VISIBLE); } if (nextWidget == WIDGET_MULTISELECT) { flagged.setVisibility(View.GONE); selected.setVisibility(View.VISIBLE); } else { flagged.setVisibility(View.VISIBLE); selected.setVisibility(View.GONE); } } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount, false); finish(); } private void onCompose() { MessageCompose.actionCompose(this, mAccount); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SORT_TYPE newSortType) { if (sortType == newSortType) { onToggleSortAscending(); } else { sortType = newSortType; MessagingController.getInstance(getApplication()).setSortType(sortType); sortAscending = MessagingController.getInstance(getApplication()).isSortAscending(sortType); sortDateAscending = MessagingController.getInstance(getApplication()).isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mHandler.sortMessages(); } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onToggleSortAscending() { MessagingController.getInstance(getApplication()).setSortAscending(sortType, !sortAscending); sortAscending = MessagingController.getInstance(getApplication()).isSortAscending(sortType); sortDateAscending = MessagingController.getInstance(getApplication()).isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } private void onDelete(MessageInfoHolder holder, int position) { mAdapter.removeMessage(holder); MessagingController.getInstance(getApplication()).deleteMessages(mAccount, holder.message.getFolder().getName(), new Message[] { holder.message }, null); mListView.setSelection(position); } private void onMove(MessageInfoHolder holder) { if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false) { return; } if (MessagingController.getInstance(getApplication()).isMoveCapable(holder.message) == false) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE); } private void onCopy(MessageInfoHolder holder) { if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false) { return; } if (MessagingController.getInstance(getApplication()).isCopyCapable(holder.message) == false) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) return; switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: if (data == null) return; String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); String uid = data.getStringExtra(ChooseFolder.EXTRA_MESSAGE_UID); FolderInfoHolder srcHolder = mCurrentFolder; if (srcHolder != null && destFolderName != null) { MessageInfoHolder m = mAdapter.getMessage(uid); if (m != null) { switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: onMoveChosen(m, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: onCopyChosen(m, destFolderName); break; } } } } } private void onMoveChosen(MessageInfoHolder holder, String folderName) { if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false) { return; } if (folderName == null) { return; } mAdapter.removeMessage(holder); MessagingController.getInstance(getApplication()).moveMessage(mAccount, holder.message.getFolder().getName(), holder.message, folderName, null); } private void onCopyChosen(MessageInfoHolder holder, String folderName) { if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false) { return; } if (folderName == null) { return; } MessagingController.getInstance(getApplication()).copyMessage(mAccount, holder.message.getFolder().getName(), holder.message, folderName, null); } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, mAccount, holder.message, false); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, mAccount, holder.message, true); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, mAccount, holder.message); } private void onMarkAllAsRead(final Account account, final String folder) { showDialog(DIALOG_MARK_ALL_AS_READ); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); break; default: super.onPrepareDialog(id, dialog); } } private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)) .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); try { MessagingController.getInstance(getApplication()).markAllMessagesRead(mAccount, mCurrentFolder.name); for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } mHandler.sortMessages(); } catch (Exception e) { // Ignore } } }) .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) .create(); } private void onToggleRead(MessageInfoHolder holder) { MessagingController.getInstance(getApplication()).setFlag(mAccount, holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } private void onToggleFlag(MessageInfoHolder holder) { MessagingController.getInstance(getApplication()).setFlag(mAccount, holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } private void checkMail(Account account, String folderName) { MessagingController.getInstance(getApplication()).synchronizeMailbox(account, folderName, mAdapter.mListener); sendMail(account); } private void sendMail(Account account) { MessagingController.getInstance(getApplication()).sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.check_mail: checkMail(mAccount, mFolderName); return true; case R.id.send_messages: sendMail(mAccount); return true; case R.id.compose: onCompose(); return true; case R.id.accounts: onAccounts(); return true; case R.id.set_sort_date: changeSort(SORT_TYPE.SORT_DATE); return true; case R.id.set_sort_subject: changeSort(SORT_TYPE.SORT_SUBJECT); return true; case R.id.set_sort_sender: changeSort(SORT_TYPE.SORT_SENDER); return true; case R.id.set_sort_flag: changeSort(SORT_TYPE.SORT_FLAGGED); return true; case R.id.set_sort_unread: changeSort(SORT_TYPE.SORT_UNREAD); return true; case R.id.set_sort_attach: changeSort(SORT_TYPE.SORT_ATTACHMENT); return true; case R.id.list_folders: onShowFolderList(); return true; case R.id.mark_all_as_read: onMarkAllAsRead(mAccount, mFolderName); return true; case R.id.folder_settings: FolderSettings.actionSettings(this, mAccount, mFolderName); return true; case R.id.account_settings: onEditAccount(); return true; case R.id.batch_select_all: setAllSelected(true); return true; case R.id.batch_deselect_all: setAllSelected(false); return true; case R.id.batch_copy_op: moveOrCopySelected(false); return true; case R.id.batch_move_op: moveOrCopySelected(true); return true; case R.id.batch_delete_op: deleteSelected(); return true; case R.id.batch_mark_read_op: flagSelected(Flag.SEEN, true); return true; case R.id.batch_mark_unread_op: flagSelected(Flag.SEEN, false); return true; case R.id.batch_flag_op: flagSelected(Flag.FLAGGED, true); return true; case R.id.batch_unflag_op: flagSelected(Flag.FLAGGED, false); return true; case R.id.batch_plain_mode: mSelectedWidget = WIDGET_NONE; configureWidgets(); return true; case R.id.batch_select_mode: mSelectedWidget = WIDGET_MULTISELECT; configureWidgets(); return true; case R.id.batch_flag_mode: mSelectedWidget = WIDGET_FLAG; configureWidgets(); return true; default: return super.onOptionsItemSelected(item); } } private final int[] batch_ops = { R.id.batch_copy_op, R.id.batch_delete_op, R.id.batch_flag_op, R.id.batch_unflag_op, R.id.batch_mark_read_op, R.id.batch_mark_unread_op, R.id.batch_move_op , R.id.batch_select_all, R.id.batch_deselect_all }; private final int[] batch_modes = { R.id.batch_flag_mode, R.id.batch_select_mode, R.id.batch_plain_mode }; private void setOpsState(Menu menu, boolean state, boolean enabled) { for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } private void setOpsMode(Menu menu, int currentModeId) { for (int id : batch_modes) { menu.findItem(id).setVisible(id != currentModeId); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { switch (mSelectedWidget) { case WIDGET_FLAG: { setOpsState(menu, false, false); setOpsMode(menu, R.id.batch_flag_mode); break; } case WIDGET_MULTISELECT: { boolean anySelected = anySelected(); setOpsState(menu, true, anySelected); setOpsMode(menu, R.id.batch_select_mode); boolean newFlagState = computeBatchDirection(true); boolean newReadState = computeBatchDirection(false); menu.findItem(R.id.batch_flag_op).setVisible(newFlagState); menu.findItem(R.id.batch_unflag_op).setVisible(!newFlagState); menu.findItem(R.id.batch_mark_read_op).setVisible(newReadState); menu.findItem(R.id.batch_mark_unread_op).setVisible(!newReadState); menu.findItem(R.id.batch_deselect_all).setEnabled(anySelected); menu.findItem(R.id.batch_select_all).setEnabled(true); // TODO: batch move and copy not yet implemented menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); break; } case WIDGET_NONE: { setOpsState(menu, false, false); setOpsMode(menu, R.id.batch_plain_mode); break; } } if (mCurrentFolder.outbox) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); MessageInfoHolder holder = (MessageInfoHolder) mAdapter.getItem(info.position); switch (item.getItemId()) { case R.id.open: onOpenMessage(holder); break; case R.id.delete: onDelete(holder, info.position); break; case R.id.reply: onReply(holder); break; case R.id.reply_all: onReplyAll(holder); break; case R.id.forward: onForward(holder); break; case R.id.mark_as_read: onToggleRead(holder); break; case R.id.flag: onToggleFlag(holder); break; case R.id.move: onMove(holder); break; case R.id.copy: onCopy(holder); break; case R.id.send_alternate: onSendAlternate(mAccount, holder); break; } return super.onContextItemSelected(item); } public void onSendAlternate(Account account, MessageInfoHolder holder) { MessagingController.getInstance(getApplication()).sendAlternate(this, account, holder.message); } public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); if (bar == null) { return; } bar.setIndeterminate(true); if (status) { bar.setVisibility(bar.VISIBLE); } else { bar.setVisibility(bar.INVISIBLE); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position); if (message == null) { return; } getMenuInflater().inflate(R.menu.message_list_context, menu); menu.setHeaderTitle((CharSequence) message.subject); if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false) { menu.findItem(R.id.copy).setVisible(false); } if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false) { menu.findItem(R.id.move).setVisible(false); } } class MessageListAdapter extends BaseAdapter { private List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private MessagingListener mListener = new MessagingListener() { @Override public void synchronizeMailboxStarted(Account account, String folder) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } mHandler.progress(true); mHandler.folderLoading(folder, true); mHandler.folderSyncing(folder); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.folderSyncing(null); mHandler.sortMessages(); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } // Perhaps this can be restored, if done in the mHandler thread // Toast.makeText(MessageList.this, message, Toast.LENGTH_LONG).show(); mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.folderSyncing(null); mHandler.sortMessages(); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } addOrUpdateMessage(folder, message); } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) { removeMessage(getMessage(message.getUid())); } @Override public void listLocalMessagesStarted(Account account, String folder) { if (!account.equals(mAccount)) { return; } mHandler.progress(true); mHandler.folderLoading(folder, true); } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if (!account.equals(mAccount)) { return; } mHandler.sortMessages(); mHandler.progress(false); mHandler.folderLoading(folder, false); } @Override public void listLocalMessagesFinished(Account account, String folder) { if (!account.equals(mAccount)) { return; } mHandler.sortMessages(); mHandler.progress(false); mHandler.folderLoading(folder, false); } @Override public void listLocalMessages(Account account, String folder, Message[] messages) { if (!account.equals(mAccount)) { return; } if (folder != mFolderName) { return; } //synchronizeMessages(folder, messages); } @Override public void listLocalMessagesRemoveMessage(Account account, String folder,Message message) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } MessageInfoHolder holder = getMessage(message.getUid()); if (holder != null) { removeMessage(getMessage(message.getUid())); } } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } addOrUpdateMessages(folder, messages); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { if (!account.equals(mAccount) || !folder.equals(mFolderName)) { return; } addOrUpdateMessage(folder, message); } }; private Drawable mAttachmentIcon; private Drawable mAnsweredIcon; private View footerView = null; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_mms_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_mms_answered_small); } public void removeMessages(List<MessageInfoHolder> holders) { if (holders == null) { return; } mHandler.removeMessage(holders); } public void removeMessage(MessageInfoHolder holder) { List<MessageInfoHolder> messages = new ArrayList<MessageInfoHolder>(); messages.add(holder); removeMessages(messages); } private void addOrUpdateMessage(String folder, Message message) { FolderInfoHolder f = mCurrentFolder; if (f == null) { return; } addOrUpdateMessage(f, message); } private void addOrUpdateMessage(FolderInfoHolder folder, Message message) { List<Message> messages = new ArrayList<Message>(); messages.add(message); addOrUpdateMessages(folder, messages); } private void addOrUpdateMessages(String folder, List<Message> messages) { FolderInfoHolder f = mCurrentFolder; if (f == null) { return; } addOrUpdateMessages(f, messages); } private void addOrUpdateMessages(FolderInfoHolder folder, List<Message> messages) { boolean needsSort = false; List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); for (Message message : messages) { MessageInfoHolder m = getMessage(message.getUid()); if (m == null) { m = new MessageInfoHolder(message, folder); messagesToAdd.add(m); } else { if (message.isSet(Flag.DELETED)) { messagesToRemove.add(m); } else { m.populate(message, folder); needsSort = true; } } } if (messagesToRemove.size() > 0) { removeMessages(messagesToRemove); } if (messagesToAdd.size() > 0) { mHandler.addMessages(messagesToAdd); } if (needsSort) { mHandler.sortMessages(); } } // XXX TODO - make this not use a for loop public MessageInfoHolder getMessage(String messageUid) { MessageInfoHolder searchHolder = new MessageInfoHolder(); searchHolder.uid = messageUid; int index = mAdapter.messages.indexOf((Object) searchHolder); if (index >= 0) { return (MessageInfoHolder)mAdapter.messages.get(index); } return null; } public FolderInfoHolder getFolder(String folder) { LocalFolder local_folder = null; try { LocalStore localStore = (LocalStore)Store.getInstance(mAccount.getLocalStoreUri(), getApplication()); local_folder = localStore.getFolder(folder); return new FolderInfoHolder((Folder)local_folder); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ",e); return null; } finally { if (local_folder != null) { local_folder.close(false); } } } private static final int NON_MESSAGE_ITEMS = 1; public int getCount() { if (mAdapter.messages == null || mAdapter.messages.size() == 0) { return NON_MESSAGE_ITEMS ; } return mAdapter.messages.size() +NON_MESSAGE_ITEMS ; } public long getItemId(int position) { try { MessageInfoHolder messageHolder =(MessageInfoHolder) getItem(position); if (messageHolder != null) { return ((LocalStore.LocalMessage) messageHolder.message).getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG,"getItemId("+position+") ",e); } return -1; } public Object getItem(long position) { return getItem((int)position); } public Object getItem(int position) { try { if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } public View getView(int position, View convertView, ViewGroup parent) { if (position == mAdapter.messages.size()) { return getFooterView(position, convertView, parent); } else { return getItemView(position, convertView, parent); } } public View getItemView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); View widgetParent; if (mLeftHanded == false) { widgetParent = view.findViewById(R.id.widgets_right); } else { widgetParent = view.findViewById(R.id.widgets_left); } View widgets = mInflater.inflate(R.layout.message_list_widgets,parent,false); widgets.setId(R.id.widgets); ((LinearLayout) widgetParent).addView(widgets); } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); } }); holder.chip.setBackgroundResource(colorChipResId); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); if (holder.selected!=null) { holder.selected.setOnCheckedChangeListener(holder); } view.setTag(holder); } if (message != null) { holder.chip.getBackground().setAlpha(message.read ? 0 : 255); holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); int subjectColor = holder.from.getCurrentTextColor(); // Get from another field that never changes color setVisibleWidgetsForListItem(view, mSelectedWidget); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag((Integer)position); holder.flagged.setChecked(message.flagged); //So that the mSelectedCount is only incremented/decremented //when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); if (message.downloaded) { holder.chip.getBackground().setAlpha(message.read ? 0 : 127); view.getBackground().setAlpha(0); } else { view.getBackground().setAlpha(127); } holder.subject.setTextColor(0xff000000 | subjectColor); holder.subject.setText(message.subject); holder.from.setText(message.sender); holder.from.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); holder.date.setText(message.date); holder.subject.setCompoundDrawablesWithIntrinsicBounds( message.answered ? mAnsweredIcon : null, // left null, // top message.hasAttachments ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } else { holder.chip.getBackground().setAlpha(0); holder.subject.setText("No subject"); holder.subject.setTypeface(null, Typeface.NORMAL); holder.from.setText("No sender"); holder.from.setTypeface(null, Typeface.NORMAL); holder.date.setText("No date"); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); holder.flagged.setChecked(false); } return view; } public View getFooterView(int position, View convertView, ViewGroup parent) { if (footerView == null) { footerView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); footerView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar)footerView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView)footerView.findViewById(R.id.main_text); footerView.setTag(holder); } FooterViewHolder holder = (FooterViewHolder)footerView.getTag(); if (mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (mCurrentFolder.lastCheckFailed == false) { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } return footerView; } public boolean hasStableIds() { return true; } public boolean isItemSelectable(int position) { if (position < mAdapter.messages.size()) { return true; } else { return false; } } } public class MessageInfoHolder implements Comparable<MessageInfoHolder> { public String subject; public String date; public Date compareDate; public String compareSubject; public String sender; public String compareCounterparty; public String[] recipients; public boolean hasAttachments; public String uid; public boolean read; public boolean answered; public boolean flagged; public boolean downloaded; public boolean partially_downloaded; public Message message; public FolderInfoHolder folder; public boolean selected; // Empty constructor for comparison public MessageInfoHolder() { this.selected = false; } public MessageInfoHolder(Message m, FolderInfoHolder folder) { this(); populate(m, folder); } public void populate(Message m, FolderInfoHolder folder) { try { LocalMessage message = (LocalMessage) m; Date date = message.getSentDate(); this.compareDate = date; this.folder = folder; if (Utility.isDateToday(date)) { this.date = getTimeFormat().format(date); } else { this.date = getDateFormat().format(date); } this.hasAttachments = message.getAttachmentCount() > 0; this.read = message.isSet(Flag.SEEN); this.answered = message.isSet(Flag.ANSWERED); this.flagged = message.isSet(Flag.FLAGGED); this.downloaded = message.isSet(Flag.X_DOWNLOADED_FULL); this.partially_downloaded = message.isSet(Flag.X_DOWNLOADED_PARTIAL); Address[] addrs = message.getFrom(); if (addrs.length > 0 && mAccount.isAnIdentity(addrs[0])) { this.compareCounterparty = Address.toFriendly(message .getRecipients(RecipientType.TO)); this.sender = String.format(getString(R.string.message_list_to_fmt), this.compareCounterparty); } else { this.sender = Address.toFriendly(addrs); this.compareCounterparty = this.sender; } this.subject = message.getSubject(); this.uid = message.getUid(); this.message = m; } catch (MessagingException me) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "Unable to load message info", me); } } } public boolean equals(Object o) { if (this.uid.equals(((MessageInfoHolder)o).uid)) { return true; } else { return false; } } public int compareTo(MessageInfoHolder o) { int ascender = (sortAscending ? 1 : -1); int comparison = 0; if (sortType == SORT_TYPE.SORT_SUBJECT) { if (compareSubject == null) { compareSubject = stripPrefixes(subject).toLowerCase(); } if (o.compareSubject == null) { o.compareSubject = stripPrefixes(o.subject).toLowerCase(); } comparison = this.compareSubject.compareTo(o.compareSubject); } else if (sortType == SORT_TYPE.SORT_SENDER) { comparison = this.compareCounterparty.toLowerCase().compareTo(o.compareCounterparty.toLowerCase()); } else if (sortType == SORT_TYPE.SORT_FLAGGED) { comparison = (this.flagged ? 0 : 1) - (o.flagged ? 0 : 1); } else if (sortType == SORT_TYPE.SORT_UNREAD) { comparison = (this.read ? 1 : 0) - (o.read ? 1 : 0); } else if (sortType == SORT_TYPE.SORT_ATTACHMENT) { comparison = (this.hasAttachments ? 0 : 1) - (o.hasAttachments ? 0 : 1); } if (comparison != 0) { return comparison * ascender; } int dateAscender = (sortDateAscending ? 1 : -1); return this.compareDate.compareTo(o.compareDate) * dateAscender; } Pattern pattern = null; String patternString = "^ *(re|aw|fw|fwd): *"; private String stripPrefixes(String in) { synchronized (patternString) { if (pattern == null) { pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); } } Matcher matcher = pattern.matcher(in); int lastPrefix = -1; while (matcher.find()) { lastPrefix = matcher.end(); } if (lastPrefix > -1 && lastPrefix < in.length() - 1) { return in.substring(lastPrefix); } else { return in; } } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position!=-1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message.selected!=isChecked) { if (isChecked) { mSelectedCount++; } else if (mSelectedCount > 0) { mSelectedCount } showBatchButtons(); message.selected = isChecked; } } } } private void enableBatchButtons() { mBatchDeleteButton.setEnabled(true); mBatchReadButton.setEnabled(true); mBatchFlagButton.setEnabled(true); } private void disableBatchButtons() { mBatchDeleteButton.setEnabled(false); mBatchReadButton.setEnabled(false); mBatchFlagButton.setEnabled(false); } private void hideBatchButtons() { //TODO: Fade out animation mBatchButtonArea.setVisibility(View.GONE); } private void showBatchButtons() { configureBatchButtons(); //TODO: Fade in animation mBatchButtonArea.setVisibility(View.VISIBLE); } private void configureBatchButtons() { if (mSelectedCount < 0) { mSelectedCount = 0; } if (mSelectedCount==0) { disableBatchButtons(); } else { enableBatchButtons(); } } class FooterViewHolder { public ProgressBar progress; public TextView main; } public class FolderInfoHolder { public String name; public String displayName; public boolean loading; public boolean lastCheckFailed; /** * Outbox is handled differently from any other folder. */ public boolean outbox; public FolderInfoHolder(Folder folder) { populate(folder); } public void populate(Folder folder) { this.name = folder.getName(); if (this.name.equalsIgnoreCase(K9.INBOX)) { this.displayName = getString(R.string.special_mailbox_name_inbox); } else { this.displayName = folder.getName(); } if (this.name.equals(mAccount.getOutboxFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_outbox_fmt), this.name); this.outbox = true; } if (this.name.equals(mAccount.getDraftsFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_drafts_fmt), this.name); } if (this.name.equals(mAccount.getTrashFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_trash_fmt), this.name); } if (this.name.equals(mAccount.getSentFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_sent_fmt), this.name); } } } private boolean computeBatchDirection(boolean flagged) { boolean newState = false; for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (flagged) { if (!holder.flagged) { newState = true; } } else { if (!holder.read) { newState = true; } } } } return newState; } private boolean anySelected() { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { return true; } } return false; } public void onClick(View v) { boolean newState = false; List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); if (v == mBatchFlagButton) { newState = computeBatchDirection(true); } else { newState = computeBatchDirection(false); } for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (v == mBatchDeleteButton) { removeHolderList.add(holder); } else if (v == mBatchFlagButton) { holder.flagged = newState; } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); } } mAdapter.removeMessages(removeHolderList); if (!messageList.isEmpty()) { if (mBatchDeleteButton == v) { MessagingController.getInstance(getApplication()).deleteMessages(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), null); mSelectedCount = 0; configureBatchButtons(); } else { MessagingController.getInstance(getApplication()).setFlag(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } } else { //Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } mAdapter.notifyDataSetChanged(); showBatchButtons(); } private void flagSelected(Flag flag, boolean newState) { List<Message> messageList = new ArrayList<Message>(); for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { messageList.add(holder.message); if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } } MessagingController.getInstance(getApplication()).setFlag(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), flag , newState); mHandler.sortMessages(); } private void deleteSelected() { List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { removeHolderList.add(holder); messageList.add(holder.message); } } mAdapter.removeMessages(removeHolderList); MessagingController.getInstance(getApplication()).deleteMessages(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), null); mSelectedCount = 0; configureBatchButtons(); } private void moveOrCopySelected(boolean isMove) { } }
package com.fsck.k9.activity; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.util.Log; import android.util.TypedValue; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.CompoundButton.OnCheckedChangeListener; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.FontSizes; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.SearchSpecification; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.activity.setup.Prefs; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.controller.MessagingController.SORT_TYPE; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; /** * MessageList is the primary user interface for the program. This Activity * shows a list of messages. * From this Activity the user can perform all standard message operations. */ public class MessageList extends K9Activity implements OnClickListener, AdapterView.OnItemClickListener { /** * Reverses the result of a {@link Comparator}. * * @param <T> */ public static class ReverseComparator<T> implements Comparator<T> { private Comparator<T> mDelegate; /** * @param delegate * Never <code>null</code>. */ public ReverseComparator(final Comparator<T> delegate) { mDelegate = delegate; } @Override public int compare(final T object1, final T object2) { // arg1 & 2 are mixed up, this is done on purpose return mDelegate.compare(object2, object1); } } /** * Chains comparator to find a non-0 result. * * @param <T> */ public static class ComparatorChain<T> implements Comparator<T> { private List<Comparator<T>> mChain; /** * @param chain * Comparator chain. Never <code>null</code>. */ public ComparatorChain(final List<Comparator<T>> chain) { mChain = chain; } @Override public int compare(T object1, T object2) { int result = 0; for (final Comparator<T> comparator : mChain) { result = comparator.compare(object1, object2); if (result != 0) { break; } } return result; } } public static class AttachmentComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.hasAttachments ? 0 : 1) - (object2.hasAttachments ? 0 : 1); } } public static class FlaggedComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.flagged ? 0 : 1) - (object2.flagged ? 0 : 1); } } public static class UnreadComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.read ? 1 : 0) - (object2.read ? 1 : 0); } } public static class SenderComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareCounterparty.toLowerCase().compareTo(object2.compareCounterparty.toLowerCase()); } } public static class DateComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareDate.compareTo(object2.compareDate); } } public static class SubjectComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder arg0, MessageInfoHolder arg1) { // XXX doesn't respect the Comparator contract since it alters the compared object if (arg0.compareSubject == null) { arg0.compareSubject = Utility.stripSubject(arg0.subject); } if (arg1.compareSubject == null) { arg1.compareSubject = Utility.stripSubject(arg1.subject); } return arg0.compareSubject.compareToIgnoreCase(arg1.compareSubject); } } /** * Immutable empty {@link Message} array */ private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH = 3; private static final int ACTIVITY_CHOOSE_FOLDER_COPY_BATCH = 4; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_FOLDER = "folder"; private static final String EXTRA_QUERY = "query"; private static final String EXTRA_QUERY_FLAGS = "queryFlags"; private static final String EXTRA_FORBIDDEN_FLAGS = "forbiddenFlags"; private static final String EXTRA_INTEGRATE = "integrate"; private static final String EXTRA_ACCOUNT_UUIDS = "accountUuids"; private static final String EXTRA_FOLDER_NAMES = "folderNames"; private static final String EXTRA_TITLE = "title"; private static final String EXTRA_LIST_POSITION = "listPosition"; /** * Maps a {@link SORT_TYPE} to a {@link Comparator} implementation. */ private static final Map<SORT_TYPE, Comparator<MessageInfoHolder>> SORT_COMPARATORS; static { // fill the mapping at class time loading final Map<SORT_TYPE, Comparator<MessageInfoHolder>> map = new EnumMap<SORT_TYPE, Comparator<MessageInfoHolder>>(SORT_TYPE.class); map.put(SORT_TYPE.SORT_ATTACHMENT, new AttachmentComparator()); map.put(SORT_TYPE.SORT_DATE, new DateComparator()); map.put(SORT_TYPE.SORT_FLAGGED, new FlaggedComparator()); map.put(SORT_TYPE.SORT_SENDER, new SenderComparator()); map.put(SORT_TYPE.SORT_SUBJECT, new SubjectComparator()); map.put(SORT_TYPE.SORT_UNREAD, new UnreadComparator()); // make it immutable to prevent accidental alteration (content is immutable already) SORT_COMPARATORS = Collections.unmodifiableMap(map); } private ListView mListView; private boolean mTouchView = true; private MessageListAdapter mAdapter; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private MessagingController mController; private Account mAccount; private int mUnreadMessageCount = 0; private GestureDetector gestureDetector; private View.OnTouchListener gestureListener; /** * Stores the name of the folder that we want to open as soon as possible * after load. */ private String mFolderName; /** * If we're doing a search, this contains the query string. */ private String mQueryString; private Flag[] mQueryFlags = null; private Flag[] mForbiddenFlags = null; private boolean mIntegrate = false; private String[] mAccountUuids = null; private String[] mFolderNames = null; private String mTitle; private MessageListHandler mHandler = new MessageListHandler(); private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; private boolean mStars = true; private boolean mCheckboxes = true; private int mSelectedCount = 0; private View mBatchButtonArea; private ImageButton mBatchReadButton; private ImageButton mBatchDeleteButton; private ImageButton mBatchFlagButton; private ImageButton mBatchDoneButton; private FontSizes mFontSizes = K9.getFontSizes(); private Bundle mState = null; private MessageInfoHolder mSelectedMessage = null; private Context context = null; /* package visibility for faster inner class access */ MessageHelper mMessageHelper = MessageHelper.getInstance(this); class MessageListHandler { public void removeMessage(final List<MessageInfoHolder> messages) { runOnUiThread(new Runnable() { public void run() { for (MessageInfoHolder message : messages) { if (message != null) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { if (message.selected && mSelectedCount > 0) { mSelectedCount } mAdapter.messages.remove(message); } } } resetUnreadCountOnThread(); mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } }); } public void addMessages(final List<MessageInfoHolder> messages) { final boolean wasEmpty = mAdapter.messages.isEmpty(); runOnUiThread(new Runnable() { public void run() { for (final MessageInfoHolder message : messages) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { int index; synchronized (mAdapter.messages) { index = Collections.binarySearch(mAdapter.messages, message, getComparator()); } Log.v(K9.LOG_TAG," Index was "+index + "For "+message.subject); if (index < 0) { index = (index * -1) - 1; } mAdapter.messages.add(index, message); } } if (wasEmpty) { mListView.setSelection(0); } resetUnreadCountOnThread(); mAdapter.notifyDataSetChanged(); } }); } private void resetUnreadCount() { runOnUiThread(new Runnable() { public void run() { resetUnreadCountOnThread(); } }); } private void resetUnreadCountOnThread() { if (mQueryString != null) { int unreadCount = 0; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { unreadCount += holder.read ? 0 : 1; } } mUnreadMessageCount = unreadCount; refreshTitleOnThread(); } } private void sortMessages() { final Comparator<MessageInfoHolder> chainComparator = getComparator(); runOnUiThread(new Runnable() { public void run() { synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages, chainComparator); } mAdapter.notifyDataSetChanged(); } }); } /** * @return The comparator to use to display messages in an ordered * fashion. Never <code>null</code>. */ protected Comparator<MessageInfoHolder> getComparator() { final List<Comparator<MessageInfoHolder>> chain = new ArrayList<Comparator<MessageInfoHolder>>(2 /* we add 2 comparators at most */ ); { // add the specified comparator final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(sortType); if (sortAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } { // add the date comparator if not already specified if (sortType != SORT_TYPE.SORT_DATE) { final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(SORT_TYPE.SORT_DATE); if (sortDateAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } } // build the comparator chain final Comparator<MessageInfoHolder> chainComparator = new ComparatorChain<MessageInfoHolder>(chain); return chainComparator; } public void folderLoading(String folder, boolean loading) { if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } } private void refreshTitle() { runOnUiThread(new Runnable() { public void run() { refreshTitleOnThread(); } }); } private void refreshTitleOnThread() { setWindowTitle(); setWindowProgress(); } private void setWindowProgress() { int level = Window.PROGRESS_END; if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { int divisor = mAdapter.mListener.getFolderTotal(); if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (mAdapter.mListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } } getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level); } private void setWindowTitle() { String displayName; if (mFolderName != null) { displayName = mFolderName; if (K9.INBOX.equalsIgnoreCase(displayName)) { displayName = getString(R.string.special_mailbox_name_inbox); } String dispString = mAdapter.mListener.formatHeader(MessageList.this, getString(R.string.message_list_title, mAccount.getDescription(), displayName), mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } else if (mQueryString != null) { if (mTitle != null) { String dispString = mAdapter.mListener.formatHeader(MessageList.this, mTitle, mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } else { setTitle(getString(R.string.search_results) + ": "+ mQueryString); } } } public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { showProgressIndicator(progress); } }); } } public static void actionHandleFolder(Context context, Account account, String folder) { Intent intent = actionHandleFolderIntent(context,account,folder); context.startActivity(intent); } public static Intent actionHandleFolderIntent(Context context, Account account, String folder) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } return intent; } public static void actionHandle(Context context, String title, String queryString, boolean integrate, Flag[] flags, Flag[] forbiddenFlags) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, queryString); if (flags != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(flags, ',')); } if (forbiddenFlags != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(forbiddenFlags, ',')); } intent.putExtra(EXTRA_INTEGRATE, integrate); intent.putExtra(EXTRA_TITLE, title); context.startActivity(intent); } public static void actionHandle(Context context, String title, SearchSpecification searchSpecification) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, searchSpecification.getQuery()); if (searchSpecification.getRequiredFlags() != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(searchSpecification.getRequiredFlags(), ',')); } if (searchSpecification.getForbiddenFlags() != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(searchSpecification.getForbiddenFlags(), ',')); } intent.putExtra(EXTRA_INTEGRATE, searchSpecification.isIntegrate()); intent.putExtra(EXTRA_ACCOUNT_UUIDS, searchSpecification.getAccountUuids()); intent.putExtra(EXTRA_FOLDER_NAMES, searchSpecification.getFolderNames()); intent.putExtra(EXTRA_TITLE, title); context.startActivity(intent); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mCurrentFolder != null && ((position+1) == mAdapter.getCount())) { mController.loadMoreMessages(mAccount, mFolderName, mAdapter.mListener); return; } MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (mSelectedCount > 0) { // In multiselect mode make sure that clicking on the item results // in toggling the 'selected' checkbox. setSelected(message, !message.selected); } else { onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { context=this; super.onCreate(savedInstanceState); mInflater = getLayoutInflater(); initializeLayout(); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent // Only set "touchable" when we're first starting up the activity. // Otherwise we get force closes when the user toggles it midstream. mTouchView = K9.messageListTouchable(); String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); String queryFlags = intent.getStringExtra(EXTRA_QUERY_FLAGS); if (queryFlags != null) { String[] flagStrings = queryFlags.split(","); mQueryFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mQueryFlags[i] = Flag.valueOf(flagStrings[i]); } } String forbiddenFlags = intent.getStringExtra(EXTRA_FORBIDDEN_FLAGS); if (forbiddenFlags != null) { String[] flagStrings = forbiddenFlags.split(","); mForbiddenFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mForbiddenFlags[i] = Flag.valueOf(flagStrings[i]); } } mIntegrate = intent.getBooleanExtra(EXTRA_INTEGRATE, false); mAccountUuids = intent.getStringArrayExtra(EXTRA_ACCOUNT_UUIDS); mFolderNames = intent.getStringArrayExtra(EXTRA_FOLDER_NAMES); mTitle = intent.getStringExtra(EXTRA_TITLE); // Take the initial folder into account only if we are *not* restoring // the activity already. if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } mAdapter = new MessageListAdapter(); final Object previousData = getLastNonConfigurationInstance(); if (previousData != null) { //noinspection unchecked mAdapter.messages.addAll((List<MessageInfoHolder>) previousData); } if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } mController = MessagingController.getInstance(getApplication()); mListView.setAdapter(mAdapter); } @Override public void onPause() { super.onPause(); mController.removeListener(mAdapter.mListener); saveListState(); } public void saveListState() { mState = new Bundle(); mState.putInt(EXTRA_LIST_POSITION, mListView.getSelectedItemPosition()); } public void restoreListState() { if (mState == null) { return; } int pos = mState.getInt(EXTRA_LIST_POSITION, ListView.INVALID_POSITION); if (pos >= mListView.getCount()) { pos = mListView.getCount() - 1; } if (pos == ListView.INVALID_POSITION) { mListView.setSelected(false); } else { mListView.setSelection(pos); } } /** * On resume we refresh messages for the folder that is currently open. * This guarantees that things like unread message count and read status * are updated. */ @Override public void onResume() { super.onResume(); mStars = K9.messageListStars(); mCheckboxes = K9.messageListCheckboxes(); sortType = mController.getSortType(); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); mController.addListener(mAdapter.mListener); mAdapter.markAllMessagesAsDirty(); if (mFolderName != null) { if (mAdapter.messages.isEmpty()) { mController.listLocalMessages(mAccount, mFolderName, mAdapter.mListener); } else { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); } mController.notifyAccountCancel(this, mAccount); MessagingController.getInstance(getApplication()).notifyAccountCancel(this, mAccount); mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessages(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } mHandler.refreshTitle(); mAdapter.pruneDirtyMessages(); mAdapter.notifyDataSetChanged(); restoreListState(); } private void initializeLayout() { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.message_list); mListView = (ListView) findViewById(R.id.message_list); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); mListView.setOnItemClickListener(this); registerForContextMenu(mListView); mBatchButtonArea = findViewById(R.id.batch_button_area); mBatchReadButton = (ImageButton) findViewById(R.id.batch_read_button); mBatchReadButton.setOnClickListener(this); mBatchDeleteButton = (ImageButton) findViewById(R.id.batch_delete_button); mBatchDeleteButton.setOnClickListener(this); mBatchFlagButton = (ImageButton) findViewById(R.id.batch_flag_button); mBatchFlagButton.setOnClickListener(this); mBatchDoneButton = (ImageButton) findViewById(R.id.batch_done_button); mBatchDoneButton.setOnClickListener(this); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; mListView.setOnTouchListener(gestureListener); } @Override public Object onRetainNonConfigurationInstance() { return mAdapter.messages; } @Override public void onBackPressed() { // This will be called either automatically for you on 2.0 // or later, or by the code above on earlier versions of the // platform. if (K9.manageBack()) { if (mQueryString == null) { onShowFolderList(); } else { onAccounts(); } } else { finish(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ( // XXX TODO - when we go to android 2.0, uncomment this // android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) { // Take care of calling this method on earlier versions of // the platform where it doesn't exist. onBackPressed(); return true; } // Shortcuts that work no matter what is selected switch (keyCode) { // messagelist is actually a K9Activity, not a K9ListActivity // This saddens me greatly, but to support volume key navigation // in MessageView, we implement this bit of wrapper code case KeyEvent.KEYCODE_VOLUME_UP: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition > 0) { mListView.setSelection(currentPosition - 1); } return true; } return false; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition < mListView.getCount()) { mListView.setSelection(currentPosition + 1); } return true; } return false; } case KeyEvent.KEYCODE_DPAD_LEFT: { if (mBatchButtonArea.hasFocus()) { return false; } else { return true; } } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (mBatchButtonArea.hasFocus()) { return false; } else { return true; } } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_S: { setSelected(message, !message.selected); return true; } case KeyEvent.KEYCODE_D: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_F: { onForward(message); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; } case KeyEvent.KEYCODE_R: { onReply(message); return true; } case KeyEvent.KEYCODE_G: { onToggleFlag(message); return true; } case KeyEvent.KEYCODE_M: { onMove(message); return true; } case KeyEvent.KEYCODE_V: { onArchive(message); return true; } case KeyEvent.KEYCODE_Y: { onCopy(message); return true; } case KeyEvent.KEYCODE_Z: { onToggleRead(message); return true; } } } } } finally { return super.onKeyDown(keyCode, event); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } return super.onKeyUp(keyCode,event); } private void onOpenMessage(MessageInfoHolder message) { if (message.folder.name.equals(message.message.getFolder().getAccount().getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } else { // Need to get the list before the sort starts ArrayList<MessageReference> messageRefs = new ArrayList<MessageReference>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { MessageReference ref = holder.message.makeMessageReference(); messageRefs.add(ref); } } MessageReference ref = message.message.makeMessageReference(); Log.i(K9.LOG_TAG, "MessageList sending message " + ref); MessageView.actionView(this, ref, messageRefs); } /* * We set read=true here for UI performance reasons. The actual value * will get picked up on the refresh when the Activity is resumed but * that may take a second or so and we don't want this to show and * then go away. I've gone back and forth on this, and this gives a * better UI experience, so I am putting it back in. */ if (!message.read) { message.read = true; } } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount); finish(); } private void onCompose() { if (mQueryString != null) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ MessageCompose.actionCompose(this, null); } else { MessageCompose.actionCompose(this, mAccount); } } private void onEditPrefs() { Prefs.actionPrefs(this); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SORT_TYPE newSortType) { if (sortType == newSortType) { onToggleSortAscending(); } else { sortType = newSortType; mController.setSortType(sortType); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mHandler.sortMessages(); } private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onToggleSortAscending() { mController.setSortAscending(sortType, !sortAscending); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } private void onDelete(MessageInfoHolder holder, int position) { mAdapter.removeMessage(holder); mController.deleteMessages(new Message[] { holder.message }, null); } private void onMove(MessageInfoHolder holder) { if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } final Account account = holder.message.getFolder().getAccount(); Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, account.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, account.getLastSelectedFolderName()); intent.putExtra(ChooseFolder.EXTRA_MESSAGE, holder.message.makeMessageReference()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE); } private void onArchive(MessageInfoHolder holder) { if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } onMoveChosen(holder, holder.message.getFolder().getAccount().getArchiveFolderName()); } private void onSpam(MessageInfoHolder holder) { if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } onMoveChosen(holder, holder.message.getFolder().getAccount().getSpamFolderName()); } private void onCopy(MessageInfoHolder holder) { if (!mController.isCopyCapable(holder.message.getFolder().getAccount())) { return; } if (!mController.isCopyCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } final Account account = holder.message.getFolder().getAccount(); Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, account.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, account.getLastSelectedFolderName()); intent.putExtra(ChooseFolder.EXTRA_MESSAGE, holder.message.makeMessageReference()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) return; switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: { if (data == null) return; final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final MessageReference ref = (MessageReference)data.getSerializableExtra(ChooseFolder.EXTRA_MESSAGE); final MessageInfoHolder m = mAdapter.getMessage(ref); if ((destFolderName != null) && (m != null)) { final Account account = m.message.getFolder().getAccount(); account.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: onMoveChosen(m, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: onCopyChosen(m, destFolderName); break; } } break; } case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: { final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final String accountUuid = data.getStringExtra(ChooseFolder.EXTRA_ACCOUNT); final Account account = Preferences.getPreferences(this).getAccount(accountUuid); account.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: onMoveChosenBatch(destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: onCopyChosenBatch(destFolderName); break; } } } } private void onMoveChosen(MessageInfoHolder holder, String folderName) { if (mController.isMoveCapable(holder.message.getFolder().getAccount()) && folderName != null) { if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } mAdapter.removeMessage(holder); mController.moveMessage(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onCopyChosen(MessageInfoHolder holder, String folderName) { if (mController.isCopyCapable(holder.message.getFolder().getAccount()) && folderName != null) { mController.copyMessage(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, false, null); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, true, null); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, holder.message.getFolder().getAccount(), holder.message, null); } private void onMarkAllAsRead(final Account account, final String folder) { showDialog(DIALOG_MARK_ALL_AS_READ); } private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } @Override public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: { if (mCurrentFolder != null) { ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); } break; } default: { super.onPrepareDialog(id, dialog); } } } private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)) .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } } mHandler.sortMessages(); } catch (Exception e) { // Ignore } } }) .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) .create(); } private void onToggleRead(MessageInfoHolder holder) { mController.setFlag(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } private void onToggleFlag(MessageInfoHolder holder) { mController.setFlag(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener, null); sendMail(account); } private void sendMail(Account account) { mController.sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.compose: { onCompose(); return true; } case R.id.accounts: { onAccounts(); return true; } case R.id.set_sort_date: { changeSort(SORT_TYPE.SORT_DATE); return true; } case R.id.set_sort_subject: { changeSort(SORT_TYPE.SORT_SUBJECT); return true; } case R.id.set_sort_sender: { changeSort(SORT_TYPE.SORT_SENDER); return true; } case R.id.set_sort_flag: { changeSort(SORT_TYPE.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { changeSort(SORT_TYPE.SORT_UNREAD); return true; } case R.id.set_sort_attach: { changeSort(SORT_TYPE.SORT_ATTACHMENT); return true; } case R.id.select_all: case R.id.batch_select_all: { setAllSelected(true); toggleBatchButtons(); return true; } case R.id.batch_deselect_all: { setAllSelected(false); toggleBatchButtons(); return true; } case R.id.batch_delete_op: { deleteSelected(); return true; } case R.id.batch_mark_read_op: { flagSelected(Flag.SEEN, true); return true; } case R.id.batch_mark_unread_op: { flagSelected(Flag.SEEN, false); return true; } case R.id.batch_flag_op: { flagSelected(Flag.FLAGGED, true); return true; } case R.id.batch_unflag_op: { flagSelected(Flag.FLAGGED, false); return true; } case R.id.app_settings: { onEditPrefs(); return true; } } if (mQueryString != null) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.check_mail: { if (mFolderName != null) { checkMail(mAccount, mFolderName); } return true; } case R.id.send_messages: { sendMail(mAccount); return true; } case R.id.list_folders: { onShowFolderList(); return true; } case R.id.mark_all_as_read: { if (mFolderName != null) { onMarkAllAsRead(mAccount, mFolderName); } return true; } case R.id.folder_settings: { if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; } case R.id.account_settings: { onEditAccount(); return true; } case R.id.batch_copy_op: { onCopyBatch(); return true; } case R.id.batch_archive_op: { onArchiveBatch(); return true; } case R.id.batch_spam_op: { onSpamBatch(); return true; } case R.id.batch_move_op: { onMoveBatch(); return true; } case R.id.expunge: { if (mCurrentFolder != null) { onExpunge(mAccount, mCurrentFolder.name); } return true; } default: { return super.onOptionsItemSelected(item); } } } private final int[] batch_ops = { R.id.batch_copy_op, R.id.batch_delete_op, R.id.batch_flag_op, R.id.batch_unflag_op, R.id.batch_mark_read_op, R.id.batch_mark_unread_op, R.id.batch_archive_op, R.id.batch_spam_op, R.id.batch_move_op, R.id.batch_select_all, R.id.batch_deselect_all }; private void setOpsState(Menu menu, boolean state, boolean enabled) { for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean anySelected = anySelected(); menu.findItem(R.id.select_all).setVisible(! anySelected); menu.findItem(R.id.batch_ops).setVisible(anySelected); setOpsState(menu, true, anySelected); if (mQueryString != null) { menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.list_folders).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.batch_archive_op).setVisible(false); menu.findItem(R.id.batch_spam_op).setVisible(false); menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); } else { if (mCurrentFolder != null && mCurrentFolder.outbox) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) { menu.findItem(R.id.batch_archive_op).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) { menu.findItem(R.id.batch_spam_op).setVisible(false); } } boolean newFlagState = computeBatchDirection(true); boolean newReadState = computeBatchDirection(false); menu.findItem(R.id.batch_flag_op).setVisible(newFlagState); menu.findItem(R.id.batch_unflag_op).setVisible(!newFlagState); menu.findItem(R.id.batch_mark_read_op).setVisible(newReadState); menu.findItem(R.id.batch_mark_unread_op).setVisible(!newReadState); menu.findItem(R.id.batch_deselect_all).setVisible(anySelected); menu.findItem(R.id.batch_select_all).setEnabled(true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); MessageInfoHolder holder = mSelectedMessage; // don't need this anymore mSelectedMessage = null; if (holder == null) { holder = (MessageInfoHolder) mAdapter.getItem(info.position); } switch (item.getItemId()) { case R.id.open: { onOpenMessage(holder); break; } case R.id.select: { setSelected(holder, true); break; } case R.id.deselect: { setSelected(holder, false); break; } case R.id.delete: { onDelete(holder, info.position); break; } case R.id.reply: { onReply(holder); break; } case R.id.reply_all: { onReplyAll(holder); break; } case R.id.forward: { onForward(holder); break; } case R.id.mark_as_read: { onToggleRead(holder); break; } case R.id.flag: { onToggleFlag(holder); break; } case R.id.archive: { onArchive(holder); break; } case R.id.spam: { onSpam(holder); break; } case R.id.move: { onMove(holder); break; } case R.id.copy: { onCopy(holder); break; } case R.id.send_alternate: { onSendAlternate(mAccount, holder); break; } case R.id.same_sender: { MessageList.actionHandle(MessageList.this, "From "+holder.sender, holder.senderAddress, true, null, null); break; } } return super.onContextItemSelected(item); } public void onSendAlternate(Account account, MessageInfoHolder holder) { mController.sendAlternate(this, account, holder.message); } public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); if (bar == null) { return; } bar.setIndeterminate(true); if (status) { bar.setVisibility(ProgressBar.VISIBLE); } else { bar.setVisibility(ProgressBar.INVISIBLE); } } class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e2 == null || e1 == null) return true; float deltaX = e2.getX() - e1.getX(), deltaY = e2.getY() - e1.getY(); boolean movedAcross = (Math.abs(deltaX) > Math.abs(deltaY * 4)); boolean steadyHand = (Math.abs(deltaX / deltaY) > 2); if (movedAcross && steadyHand) { boolean selected = (deltaX > 0); int position = mListView.pointToPosition((int)e1.getX(), (int)e1.getY()); if (position != AdapterView.INVALID_POSITION) { MessageInfoHolder msgInfoHolder = (MessageInfoHolder) mAdapter.getItem(position); if (msgInfoHolder != null && msgInfoHolder.selected != selected) { msgInfoHolder.selected = selected; mSelectedCount += (selected ? 1 : -1); mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } } } return false; } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position); // remember which message was originally selected, in case the list changes while the // dialog is up mSelectedMessage = message; if (message == null) { return; } getMenuInflater().inflate(R.menu.message_list_context, menu); menu.setHeaderTitle((CharSequence) message.subject); if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } Account account = message.message.getFolder().getAccount(); if (!mController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!mController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(account.getArchiveFolderName())) { menu.findItem(R.id.archive).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(account.getSpamFolderName())) { menu.findItem(R.id.spam).setVisible(false); } if (message.selected) { menu.findItem(R.id.select).setVisible(false); menu.findItem(R.id.deselect).setVisible(true); } else { menu.findItem(R.id.select).setVisible(true); menu.findItem(R.id.deselect).setVisible(false); } } class MessageListAdapter extends BaseAdapter { private final List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private final ActivityListener mListener = new ActivityListener() { @Override public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } mHandler.refreshTitle(); } @Override public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxHeadersProgress(account,folder,completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxHeadersFinished(Account account, String folder, int total, int completed) { super.synchronizeMailboxHeadersFinished(account,folder, total, completed); mHandler.refreshTitle(); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } mHandler.refreshTitle(); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { super.synchronizeMailboxFailed(account, folder, message); if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } mHandler.refreshTitle(); } @Override public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); } @Override public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); } @Override public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); } @Override public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, true); } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) { MessageInfoHolder holder = getMessage(message); if (holder == null) { Log.w(K9.LOG_TAG, "Got callback to remove non-existent message with UID " + message.getUid()); } else { removeMessage(holder); } } @Override public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount)) ) { mHandler.progress(true); if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesRemoveMessage(Account account, String folder,Message message) { MessageInfoHolder holder = getMessage(message); if (holder != null) { removeMessage(holder); } } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages, false); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, false); } @Override public void searchStats(AccountStats stats) { mUnreadMessageCount = stats.unreadMessageCount; mHandler.refreshTitle(); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { super.folderStatusChanged(account, folder, unreadMessageCount); if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; mHandler.refreshTitle(); } } @Override public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } @Override public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } @Override public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } @Override public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { MessageReference ref = new MessageReference(); ref.accountUuid = account.getUuid(); ref.folderName = folder; ref.uid = oldUid; MessageInfoHolder holder = getMessage(ref); if (holder != null) { holder.uid = newUid; holder.message.setUid(newUid); } } }; private boolean updateForMe(Account account, String folder) { if ((account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; } else { return false; } } private Drawable mAttachmentIcon; private Drawable mAnsweredIcon; private View footerView = null; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_mms_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_mms_answered_small); } public void markAllMessagesAsDirty() { for (MessageInfoHolder holder : mAdapter.messages) { holder.dirty = true; } } public void pruneDirtyMessages() { Iterator<MessageInfoHolder> iter = mAdapter.messages.iterator(); while (iter.hasNext()) { MessageInfoHolder holder = iter.next(); if (holder.dirty) { if (holder.selected) { mSelectedCount toggleBatchButtons(); } iter.remove(); } } } public void removeMessages(List<MessageInfoHolder> holders) { if (holders != null) { mHandler.removeMessage(holders); } } public void removeMessage(MessageInfoHolder holder) { List<MessageInfoHolder> messages = new ArrayList<MessageInfoHolder>(); messages.add(holder); removeMessages(messages); } private void addOrUpdateMessage(Account account, String folderName, Message message, boolean verifyAgainstSearch) { List<Message> messages = new ArrayList<Message>(); messages.add(message); addOrUpdateMessages(account, folderName, messages, verifyAgainstSearch); } private void addOrUpdateMessages(final Account account, final String folderName, final List<Message> providedMessages, final boolean verifyAgainstSearch) { // we copy the message list because the callback doesn't expect // the callbacks to mutate it. final List<Message> messages = new ArrayList<Message>(providedMessages); runOnUiThread(new Runnable() { public void run() { boolean needsSort = false; final List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); List<Message> messagesToSearch = new ArrayList<Message>(); // cache field into local variable for faster access for JVM without JIT final MessageHelper messageHelper = mMessageHelper; for (Message message : messages) { MessageInfoHolder m = getMessage(message); if (message.isSet(Flag.DELETED)) { if (m != null) { messagesToRemove.add(m); } } else { final Folder messageFolder = message.getFolder(); final Account messageAccount = messageFolder.getAccount(); if (m == null) { if (updateForMe(account, folderName)) { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } else { if (mQueryString != null) { if (verifyAgainstSearch) { messagesToSearch.add(message); } else { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } } } } else { m.dirty = false; // as we reload the message, unset its dirty flag messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, account), account); needsSort = true; } } } if (messagesToSearch.size() > 0) { mController.searchLocalMessages(mAccountUuids, mFolderNames, messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY), mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, new MessagingListener() { @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages, false); } }); } if (messagesToRemove.size() > 0) { removeMessages(messagesToRemove); } if (messagesToAdd.size() > 0) { mHandler.addMessages(messagesToAdd); } if (needsSort) { mHandler.sortMessages(); mHandler.resetUnreadCount(); } } }); } public MessageInfoHolder getMessage(Message message) { return getMessage(message.makeMessageReference()); } // XXX TODO - make this not use a for loop public MessageInfoHolder getMessage(MessageReference messageReference) { synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { /* * 2010-06-21 - cketti * Added null pointer check. Not sure what's causing 'holder' * to be null. See log provided in issue 1749, comment #15. * * Please remove this comment once the cause was found and the * bug(?) fixed. */ if ((holder != null) && holder.message.equalsReference(messageReference)) { return holder; } } } return null; } public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; try { LocalStore localStore = account.getLocalStore(); local_folder = localStore.getFolder(folder); return new FolderInfoHolder(context, (Folder)local_folder, account); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ",e); return null; } finally { if (local_folder != null) { local_folder.close(); } } } private static final int NON_MESSAGE_ITEMS = 1; private final OnClickListener flagClickListener = new OnClickListener() { public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); } }; @Override public int getCount() { return messages.size() + NON_MESSAGE_ITEMS; } @Override public long getItemId(int position) { try { MessageInfoHolder messageHolder =(MessageInfoHolder) getItem(position); if (messageHolder != null) { return ((LocalStore.LocalMessage) messageHolder.message).getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG,"getItemId("+position+") ",e); } return -1; } public Object getItem(long position) { return getItem((int)position); } @Override public Object getItem(int position) { try { synchronized (mAdapter.messages) { if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position == mAdapter.messages.size()) { return getFooterView(position, convertView, parent); } else { return getItemView(position, convertView, parent); } } public View getItemView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { if (mTouchView) { view = mInflater.inflate(R.layout.message_list_item_touchable, parent, false); view.setId(R.layout.message_list_item); } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); } } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.preview = (TextView) view.findViewById(R.id.preview); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(flagClickListener); if (!mStars) { holder.flagged.setVisibility(View.GONE); } if (mCheckboxes) { holder.selected.setVisibility(View.VISIBLE); } if (holder.selected != null) { holder.selected.setOnCheckedChangeListener(holder); } view.setTag(holder); } if (message != null) { bindView(position, view, holder, message); } else { // TODO is this branch ever reached/executed? holder.chip.getBackground().setAlpha(0); holder.subject.setText("No subject"); holder.subject.setTypeface(null, Typeface.NORMAL); if (holder.preview != null) { holder.preview.setText("No sender"); holder.preview.setTypeface(null, Typeface.NORMAL); holder.preview.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } else { holder.from.setText("No sender"); holder.from.setTypeface(null, Typeface.NORMAL); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } holder.date.setText("No date"); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); if (!mCheckboxes) { holder.selected.setVisibility(View.GONE); } holder.flagged.setChecked(false); } holder.subject.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSubject()); holder.date.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListDate()); if (mTouchView) { holder.preview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSender()); } else { holder.from.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSender()); } return view; } /** * Associate model data to view object. * * @param position * The position of the item within the adapter's data set of * the item whose view we want. * @param view * Main view component to alter. Never <code>null</code>. * @param holder * Convenience view holder - eases access to <tt>view</tt> * child views. Never <code>null</code>. * @param message * Never <code>null</code>. */ private void bindView(final int position, final View view, final MessageViewHolder holder, final MessageInfoHolder message) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag((Integer)position); holder.flagged.setChecked(message.flagged); // So that the mSelectedCount is only incremented/decremented // when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); if (!mCheckboxes) { holder.selected.setVisibility(message.selected ? View.VISIBLE : View.GONE); } holder.chip.setBackgroundColor(message.message.getFolder().getAccount().getChipColor()); holder.chip.getBackground().setAlpha(message.read ? 127 : 255); view.getBackground().setAlpha(message.downloaded ? 0 : 127); if ((message.subject == null) || message.subject.equals("")) { holder.subject.setText(getText(R.string.general_no_subject)); } else { holder.subject.setText(message.subject); } if (holder.preview != null) { /* * In the touchable UI, we have previews. Otherwise, we * have just a "from" line. * Because text views can't wrap around each other(?) we * compose a custom view containing the preview and the * from. */ holder.preview.setText(new SpannableStringBuilder(message.sender).append(" ").append(message.preview), TextView.BufferType.SPANNABLE); Spannable str = (Spannable)holder.preview.getText(); // Create our span sections, and assign a format to each. str.setSpan(new StyleSpan(Typeface.BOLD), 0, message.sender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); str.setSpan(new ForegroundColorSpan(Color.rgb(128,128,128)), // TODO: How do I can specify the android.R.attr.textColorTertiary message.sender.length(), str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } else { holder.from.setText(message.sender); holder.from.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); } holder.date.setText(message.date); holder.subject.setCompoundDrawablesWithIntrinsicBounds( message.answered ? mAnsweredIcon : null, // left null, // top message.hasAttachments ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } public View getFooterView(int position, View convertView, ViewGroup parent) { if (footerView == null) { footerView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); if (mQueryString != null) { footerView.setVisibility(View.GONE); } footerView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar)footerView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView)footerView.findViewById(R.id.main_text); footerView.setTag(holder); } FooterViewHolder holder = (FooterViewHolder)footerView.getTag(); if (mCurrentFolder != null && mAccount != null) { if (mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (!mCurrentFolder.lastCheckFailed) { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } } else { holder.progress.setVisibility(ProgressBar.INVISIBLE); } return footerView; } @Override public boolean hasStableIds() { return true; } public boolean isItemSelectable(int position) { if (position < mAdapter.messages.size()) { return true; } else { return false; } } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position!=-1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message.selected!=isChecked) { if (isChecked) { mSelectedCount++; } else if (mSelectedCount > 0) { mSelectedCount } // We must set the flag before showing the buttons as the // buttons text depends on what is selected. message.selected = isChecked; if (!mCheckboxes) { if (isChecked) { selected.setVisibility(View.VISIBLE); } else { selected.setVisibility(View.GONE); } } toggleBatchButtons(); } } } } private void hideBatchButtons() { //TODO: Fade out animation mBatchButtonArea.setVisibility(View.GONE); } private void showBatchButtons() { //TODO: Fade in animation mBatchButtonArea.setVisibility(View.VISIBLE); } private void toggleBatchButtons() { if (mSelectedCount < 0) { mSelectedCount = 0; } int readButtonIconId; int flagButtonIconId; if (mSelectedCount==0) { readButtonIconId = R.drawable.ic_button_mark_read; flagButtonIconId = R.drawable.ic_button_flag; hideBatchButtons(); } else { boolean newReadState = computeBatchDirection(false); if (newReadState) { readButtonIconId = R.drawable.ic_button_mark_read; } else { readButtonIconId = R.drawable.ic_button_mark_unread; } boolean newFlagState = computeBatchDirection(true); if (newFlagState) { flagButtonIconId = R.drawable.ic_button_flag; } else { flagButtonIconId = R.drawable.ic_button_unflag; } showBatchButtons(); } mBatchReadButton.setImageResource(readButtonIconId); mBatchFlagButton.setImageResource(flagButtonIconId); } class FooterViewHolder { public ProgressBar progress; public TextView main; } private boolean computeBatchDirection(boolean flagged) { boolean newState = false; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (flagged) { if (!holder.flagged) { newState = true; break; } } else { if (!holder.read) { newState = true; break; } } } } } return newState; } private boolean anySelected() { synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { return true; } } } return false; } @Override public void onClick(View v) { boolean newState = false; List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); if (v == mBatchDoneButton) { setAllSelected(false); return; } if (v == mBatchFlagButton) { newState = computeBatchDirection(true); } else { newState = computeBatchDirection(false); } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (v == mBatchDeleteButton) { removeHolderList.add(holder); } else if (v == mBatchFlagButton) { holder.flagged = newState; } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); } } } mAdapter.removeMessages(removeHolderList); if (!messageList.isEmpty()) { if (v == mBatchDeleteButton) { mController.deleteMessages(messageList.toArray(EMPTY_MESSAGE_ARRAY), null); mSelectedCount = 0; toggleBatchButtons(); } else { mController.setFlag(messageList.toArray(EMPTY_MESSAGE_ARRAY), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } } else { // Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } } mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } private void setSelected(MessageInfoHolder holder, boolean newState) { if (holder.selected != newState) { holder.selected = newState; mSelectedCount += (newState ? 1 : -1); } mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } private void flagSelected(Flag flag, boolean newState) { List<Message> messageList = new ArrayList<Message>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { messageList.add(holder.message); if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } } } mController.setFlag(messageList.toArray(EMPTY_MESSAGE_ARRAY), flag, newState); mHandler.sortMessages(); } private void deleteSelected() { List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { removeHolderList.add(holder); messageList.add(holder.message); } } } mAdapter.removeMessages(removeHolderList); mController.deleteMessages(messageList.toArray(EMPTY_MESSAGE_ARRAY), null); mSelectedCount = 0; toggleBatchButtons(); } private void onMoveBatch() { if (!mController.isMoveCapable(mAccount)) { return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } } } } final Folder folder = mCurrentFolder.folder; final Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName()); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, folder.getAccount().getLastSelectedFolderName()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH); } private void onMoveChosenBatch(String folderName) { if (!mController.isMoveCapable(mAccount)) { return; } List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } messageList.add(holder.message); removeHolderList.add(holder); } } } mAdapter.removeMessages(removeHolderList); mController.moveMessages(mAccount, mCurrentFolder.name, messageList.toArray(EMPTY_MESSAGE_ARRAY), folderName, null); mSelectedCount = 0; toggleBatchButtons(); } private void onArchiveBatch() { if (!mController.isMoveCapable(mAccount)) { return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } } } } String folderName = mAccount.getArchiveFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } onMoveChosenBatch(folderName); } private void onSpamBatch() { if (!mController.isMoveCapable(mAccount)) { return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } } } } String folderName = mAccount.getSpamFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } onMoveChosenBatch(folderName); } private void onCopyBatch() { if (!mController.isCopyCapable(mAccount)) { return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isCopyCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } } } } final Folder folder = mCurrentFolder.folder; final Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName()); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, folder.getAccount().getLastSelectedFolderName()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY_BATCH); } private void onCopyChosenBatch(String folderName) { if (!mController.isCopyCapable(mAccount)) { return; } List<Message> messageList = new ArrayList<Message>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isCopyCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } messageList.add(holder.message); } } } mController.copyMessages(mAccount, mCurrentFolder.name, messageList.toArray(EMPTY_MESSAGE_ARRAY), folderName, null); } }
package ru.job4j.exam; public class FirstExam { public int[] united(int[] first, int[] second) { if (first == null) { return second; } if (second == null) { return first; } int[] third = new int[first.length + second.length]; int firstIndex = 0; int secondIndex = 0; for (int i = 0; i < third.length; i++) { if (firstIndex >= first.length) { third[i] = second[secondIndex]; secondIndex++; } else if (secondIndex >= second.length) { third[i] = first[firstIndex]; firstIndex++; } else if (first[firstIndex] < second[secondIndex]) { third[i] = first[firstIndex]; firstIndex++; } else if (first[firstIndex] > second[secondIndex]) { third[i] = second[secondIndex]; secondIndex++; } else { third[i] = first[firstIndex]; third[i + 1] = second[secondIndex]; i = i + 1; firstIndex++; secondIndex++; } } return third; } }
package com.fsck.k9.activity; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.TextAppearanceSpan; import android.util.Log; import android.util.TypedValue; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Animation.AnimationListener; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.CompoundButton.OnCheckedChangeListener; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.FontSizes; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.SearchSpecification; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.activity.setup.Prefs; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.controller.MessagingController.SORT_TYPE; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.StorageManager; import com.fsck.k9.mail.store.LocalStore.LocalFolder; /** * MessageList is the primary user interface for the program. This Activity * shows a list of messages. * From this Activity the user can perform all standard message operations. */ public class MessageList extends K9Activity implements OnClickListener, AdapterView.OnItemClickListener, AnimationListener { /** * Reverses the result of a {@link Comparator}. * * @param <T> */ public static class ReverseComparator<T> implements Comparator<T> { private Comparator<T> mDelegate; /** * @param delegate * Never <code>null</code>. */ public ReverseComparator(final Comparator<T> delegate) { mDelegate = delegate; } @Override public int compare(final T object1, final T object2) { // arg1 & 2 are mixed up, this is done on purpose return mDelegate.compare(object2, object1); } } /** * Chains comparator to find a non-0 result. * * @param <T> */ public static class ComparatorChain<T> implements Comparator<T> { private List<Comparator<T>> mChain; /** * @param chain * Comparator chain. Never <code>null</code>. */ public ComparatorChain(final List<Comparator<T>> chain) { mChain = chain; } @Override public int compare(T object1, T object2) { int result = 0; for (final Comparator<T> comparator : mChain) { result = comparator.compare(object1, object2); if (result != 0) { break; } } return result; } } public static class AttachmentComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.message.hasAttachments() ? 0 : 1) - (object2.message.hasAttachments() ? 0 : 1); } } public static class FlaggedComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.flagged ? 0 : 1) - (object2.flagged ? 0 : 1); } } public static class UnreadComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.read ? 1 : 0) - (object2.read ? 1 : 0); } } public static class SenderComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareCounterparty.toLowerCase().compareTo(object2.compareCounterparty.toLowerCase()); } } public static class DateComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareDate.compareTo(object2.compareDate); } } public static class SubjectComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder arg0, MessageInfoHolder arg1) { // XXX doesn't respect the Comparator contract since it alters the compared object if (arg0.compareSubject == null) { arg0.compareSubject = Utility.stripSubject(arg0.message.getSubject()); } if (arg1.compareSubject == null) { arg1.compareSubject = Utility.stripSubject(arg1.message.getSubject()); } return arg0.compareSubject.compareToIgnoreCase(arg1.compareSubject); } } /** * Immutable empty {@link Message} array */ private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH = 3; private static final int ACTIVITY_CHOOSE_FOLDER_COPY_BATCH = 4; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_FOLDER = "folder"; private static final String EXTRA_QUERY = "query"; private static final String EXTRA_QUERY_FLAGS = "queryFlags"; private static final String EXTRA_FORBIDDEN_FLAGS = "forbiddenFlags"; private static final String EXTRA_INTEGRATE = "integrate"; private static final String EXTRA_ACCOUNT_UUIDS = "accountUuids"; private static final String EXTRA_FOLDER_NAMES = "folderNames"; private static final String EXTRA_TITLE = "title"; private static final String EXTRA_LIST_POSITION = "listPosition"; /** * Maps a {@link SORT_TYPE} to a {@link Comparator} implementation. */ private static final Map<SORT_TYPE, Comparator<MessageInfoHolder>> SORT_COMPARATORS; static { // fill the mapping at class time loading final Map<SORT_TYPE, Comparator<MessageInfoHolder>> map = new EnumMap<SORT_TYPE, Comparator<MessageInfoHolder>>(SORT_TYPE.class); map.put(SORT_TYPE.SORT_ATTACHMENT, new AttachmentComparator()); map.put(SORT_TYPE.SORT_DATE, new DateComparator()); map.put(SORT_TYPE.SORT_FLAGGED, new FlaggedComparator()); map.put(SORT_TYPE.SORT_SENDER, new SenderComparator()); map.put(SORT_TYPE.SORT_SUBJECT, new SubjectComparator()); map.put(SORT_TYPE.SORT_UNREAD, new UnreadComparator()); // make it immutable to prevent accidental alteration (content is immutable already) SORT_COMPARATORS = Collections.unmodifiableMap(map); } private ListView mListView; private boolean mTouchView = true; private int mPreviewLines = 0; private MessageListAdapter mAdapter; private View mFooterView; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private MessagingController mController; private Account mAccount; private int mUnreadMessageCount = 0; private GestureDetector gestureDetector; private View.OnTouchListener gestureListener; /** * Stores the name of the folder that we want to open as soon as possible * after load. */ private String mFolderName; /** * If we're doing a search, this contains the query string. */ private String mQueryString; private Flag[] mQueryFlags = null; private Flag[] mForbiddenFlags = null; private boolean mIntegrate = false; private String[] mAccountUuids = null; private String[] mFolderNames = null; private String mTitle; private MessageListHandler mHandler = new MessageListHandler(); private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; private boolean mStars = true; private boolean mCheckboxes = true; private int mSelectedCount = 0; private View mBatchButtonArea; private ImageButton mBatchReadButton; private ImageButton mBatchDeleteButton; private ImageButton mBatchFlagButton; private ImageButton mBatchDoneButton; private FontSizes mFontSizes = K9.getFontSizes(); private Bundle mState = null; private MessageInfoHolder mSelectedMessage = null; private Context context = null; /* package visibility for faster inner class access */ MessageHelper mMessageHelper = MessageHelper.getInstance(this); private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override public void onUnmount(String providerId) { if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) { runOnUiThread(new Runnable() { @Override public void run() { onAccountUnavailable(); } }); } } @Override public void onMount(String providerId) { // no-op } } class MessageListHandler { public void removeMessage(final List<MessageInfoHolder> messages) { runOnUiThread(new Runnable() { public void run() { for (MessageInfoHolder message : messages) { if (message != null) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { if (message.selected && mSelectedCount > 0) { mSelectedCount } mAdapter.messages.remove(message); } } } resetUnreadCountOnThread(); mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } }); } public void addMessages(final List<MessageInfoHolder> messages) { final boolean wasEmpty = mAdapter.messages.isEmpty(); runOnUiThread(new Runnable() { public void run() { for (final MessageInfoHolder message : messages) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { int index; synchronized (mAdapter.messages) { index = Collections.binarySearch(mAdapter.messages, message, getComparator()); } if (index < 0) { index = (index * -1) - 1; } mAdapter.messages.add(index, message); } } if (wasEmpty) { mListView.setSelection(0); } resetUnreadCountOnThread(); mAdapter.notifyDataSetChanged(); } }); } private void resetUnreadCount() { runOnUiThread(new Runnable() { public void run() { resetUnreadCountOnThread(); } }); } private void resetUnreadCountOnThread() { if (mQueryString != null) { int unreadCount = 0; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { unreadCount += holder.read ? 0 : 1; } } mUnreadMessageCount = unreadCount; refreshTitleOnThread(); } } private void sortMessages() { final Comparator<MessageInfoHolder> chainComparator = getComparator(); runOnUiThread(new Runnable() { public void run() { synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages, chainComparator); } mAdapter.notifyDataSetChanged(); } }); } /** * @return The comparator to use to display messages in an ordered * fashion. Never <code>null</code>. */ protected Comparator<MessageInfoHolder> getComparator() { final List<Comparator<MessageInfoHolder>> chain = new ArrayList<Comparator<MessageInfoHolder>>(2 /* we add 2 comparators at most */); { // add the specified comparator final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(sortType); if (sortAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } { // add the date comparator if not already specified if (sortType != SORT_TYPE.SORT_DATE) { final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(SORT_TYPE.SORT_DATE); if (sortDateAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } } // build the comparator chain final Comparator<MessageInfoHolder> chainComparator = new ComparatorChain<MessageInfoHolder>(chain); return chainComparator; } public void folderLoading(String folder, boolean loading) { if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } runOnUiThread(new Runnable() { @Override public void run() { updateFooterView(); } }); } private void refreshTitle() { runOnUiThread(new Runnable() { public void run() { refreshTitleOnThread(); } }); } private void refreshTitleOnThread() { setWindowTitle(); setWindowProgress(); } private void setWindowProgress() { int level = Window.PROGRESS_END; if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { int divisor = mAdapter.mListener.getFolderTotal(); if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (mAdapter.mListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } } getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level); } private void setWindowTitle() { String displayName; if (mFolderName != null) { displayName = mFolderName; if (K9.INBOX.equalsIgnoreCase(displayName)) { displayName = getString(R.string.special_mailbox_name_inbox); } else if (mAccount.getOutboxFolderName().equals(displayName)) { displayName = getString(R.string.special_mailbox_name_outbox); } String dispString = mAdapter.mListener.formatHeader(MessageList.this, getString(R.string.message_list_title, mAccount.getDescription(), displayName), mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } else if (mQueryString != null) { if (mTitle != null) { String dispString = mAdapter.mListener.formatHeader(MessageList.this, mTitle, mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } else { setTitle(getString(R.string.search_results) + ": " + mQueryString); } } } public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { showProgressIndicator(progress); } }); } } public static void actionHandleFolder(Context context, Account account, String folder) { Intent intent = actionHandleFolderIntent(context, account, folder); context.startActivity(intent); } public static Intent actionHandleFolderIntent(Context context, Account account, String folder) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } return intent; } public static void actionHandle(Context context, String title, String queryString, boolean integrate, Flag[] flags, Flag[] forbiddenFlags) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, queryString); if (flags != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(flags, ',')); } if (forbiddenFlags != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(forbiddenFlags, ',')); } intent.putExtra(EXTRA_INTEGRATE, integrate); intent.putExtra(EXTRA_TITLE, title); context.startActivity(intent); } public static void actionHandle(Context context, String title, SearchSpecification searchSpecification) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, searchSpecification.getQuery()); if (searchSpecification.getRequiredFlags() != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(searchSpecification.getRequiredFlags(), ',')); } if (searchSpecification.getForbiddenFlags() != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(searchSpecification.getForbiddenFlags(), ',')); } intent.putExtra(EXTRA_INTEGRATE, searchSpecification.isIntegrate()); intent.putExtra(EXTRA_ACCOUNT_UUIDS, searchSpecification.getAccountUuids()); intent.putExtra(EXTRA_FOLDER_NAMES, searchSpecification.getFolderNames()); intent.putExtra(EXTRA_TITLE, title); context.startActivity(intent); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Use mListView.getAdapter() to get the WrapperListAdapter that includes the footer view. if (mCurrentFolder != null && ((position + 1) == mListView.getAdapter().getCount())) { mController.loadMoreMessages(mAccount, mFolderName, mAdapter.mListener); return; } MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (mSelectedCount > 0) { // In multiselect mode make sure that clicking on the item results // in toggling the 'selected' checkbox. setSelected(message, !message.selected); } else { onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { context = this; super.onCreate(savedInstanceState); mInflater = getLayoutInflater(); initializeLayout(); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent // Only set "touchable" when we're first starting up the activity. // Otherwise we get force closes when the user toggles it midstream. mTouchView = K9.messageListTouchable(); mPreviewLines = K9.messageListPreviewLines(); String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); if (mAccount != null && !mAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return; } String queryFlags = intent.getStringExtra(EXTRA_QUERY_FLAGS); if (queryFlags != null) { String[] flagStrings = queryFlags.split(","); mQueryFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mQueryFlags[i] = Flag.valueOf(flagStrings[i]); } } String forbiddenFlags = intent.getStringExtra(EXTRA_FORBIDDEN_FLAGS); if (forbiddenFlags != null) { String[] flagStrings = forbiddenFlags.split(","); mForbiddenFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mForbiddenFlags[i] = Flag.valueOf(flagStrings[i]); } } mIntegrate = intent.getBooleanExtra(EXTRA_INTEGRATE, false); mAccountUuids = intent.getStringArrayExtra(EXTRA_ACCOUNT_UUIDS); mFolderNames = intent.getStringArrayExtra(EXTRA_FOLDER_NAMES); mTitle = intent.getStringExtra(EXTRA_TITLE); // Take the initial folder into account only if we are *not* restoring // the activity already. if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } mAdapter = new MessageListAdapter(); restorePreviousData(); if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } mController = MessagingController.getInstance(getApplication()); mListView.setAdapter(mAdapter); } @SuppressWarnings("unchecked") private void restorePreviousData() { final Object previousData = getLastNonConfigurationInstance(); if (previousData != null) { mAdapter.messages.addAll((List<MessageInfoHolder>) previousData); } } @Override public void onPause() { super.onPause(); mController.removeListener(mAdapter.mListener); saveListState(); StorageManager.getInstance(getApplication()).removeListener(mStorageListener); } public void saveListState() { mState = new Bundle(); mState.putInt(EXTRA_LIST_POSITION, mListView.getSelectedItemPosition()); } public void restoreListState() { if (mState == null) { return; } int pos = mState.getInt(EXTRA_LIST_POSITION, ListView.INVALID_POSITION); if (pos >= mListView.getCount()) { pos = mListView.getCount() - 1; } if (pos == ListView.INVALID_POSITION) { mListView.setSelected(false); } else { mListView.setSelection(pos); } } /** * On resume we refresh messages for the folder that is currently open. * This guarantees that things like unread message count and read status * are updated. */ @Override public void onResume() { super.onResume(); if (mAccount != null && !mAccount.isAvailable(this)) { onAccountUnavailable(); return; } StorageManager.getInstance(getApplication()).addListener(mStorageListener); mStars = K9.messageListStars(); mCheckboxes = K9.messageListCheckboxes(); sortType = mController.getSortType(); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); mController.addListener(mAdapter.mListener); if (mAccount != null) { mController.notifyAccountCancel(this, mAccount); MessagingController.getInstance(getApplication()).notifyAccountCancel(this, mAccount); } if (mAdapter.messages.isEmpty()) { if (mFolderName != null) { mController.listLocalMessages(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessages(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } } else { new Thread() { @Override public void run() { mAdapter.markAllMessagesAsDirty(); if (mFolderName != null) { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessagesSynchronous(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } mAdapter.pruneDirtyMessages(); runOnUiThread(new Runnable() { public void run() { mAdapter.notifyDataSetChanged(); restoreListState(); } }); } } .start(); } if (mAccount != null && mFolderName != null) { mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } mHandler.refreshTitle(); } private void initializeLayout() { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.message_list); mListView = (ListView) findViewById(R.id.message_list); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); mListView.setOnItemClickListener(this); mListView.addFooterView(getFooterView(mListView)); registerForContextMenu(mListView); mBatchButtonArea = findViewById(R.id.batch_button_area); mBatchReadButton = (ImageButton) findViewById(R.id.batch_read_button); mBatchReadButton.setOnClickListener(this); mBatchDeleteButton = (ImageButton) findViewById(R.id.batch_delete_button); mBatchDeleteButton.setOnClickListener(this); mBatchFlagButton = (ImageButton) findViewById(R.id.batch_flag_button); mBatchFlagButton.setOnClickListener(this); mBatchDoneButton = (ImageButton) findViewById(R.id.batch_done_button); mBatchDoneButton.setOnClickListener(this); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; mListView.setOnTouchListener(gestureListener); } @Override public Object onRetainNonConfigurationInstance() { return mAdapter.messages; } @Override public void onBackPressed() { // This will be called either automatically for you on 2.0 // or later, or by the code above on earlier versions of the // platform. if (K9.manageBack()) { if (mQueryString == null) { onShowFolderList(); } else { onAccounts(); } } else { finish(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ( // XXX TODO - when we go to android 2.0, uncomment this // android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) { // Take care of calling this method on earlier versions of // the platform where it doesn't exist. onBackPressed(); return true; } // Shortcuts that work no matter what is selected switch (keyCode) { // messagelist is actually a K9Activity, not a K9ListActivity // This saddens me greatly, but to support volume key navigation // in MessageView, we implement this bit of wrapper code case KeyEvent.KEYCODE_VOLUME_UP: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition > 0) { mListView.setSelection(currentPosition - 1); } return true; } return false; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition < mListView.getCount()) { mListView.setSelection(currentPosition + 1); } return true; } return false; } case KeyEvent.KEYCODE_DPAD_LEFT: { if (mBatchButtonArea.hasFocus()) { return false; } else { return true; } } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (mBatchButtonArea.hasFocus()) { return false; } else { return true; } } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } boolean retval = true; int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_S: { setSelected(message, !message.selected); return true; } case KeyEvent.KEYCODE_D: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_F: { onForward(message); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; } case KeyEvent.KEYCODE_R: { onReply(message); return true; } case KeyEvent.KEYCODE_G: { onToggleFlag(message); return true; } case KeyEvent.KEYCODE_M: { onMove(message); return true; } case KeyEvent.KEYCODE_V: { onArchive(message); return true; } case KeyEvent.KEYCODE_Y: { onCopy(message); return true; } case KeyEvent.KEYCODE_Z: { onToggleRead(message); return true; } } } } } finally { retval = super.onKeyDown(keyCode, event); } return retval; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } return super.onKeyUp(keyCode, event); } private void onResendMessage(MessageInfoHolder message) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } private void onOpenMessage(MessageInfoHolder message) { if (message.folder.name.equals(message.message.getFolder().getAccount().getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } else { // Need to get the list before the sort starts ArrayList<MessageReference> messageRefs = new ArrayList<MessageReference>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { MessageReference ref = holder.message.makeMessageReference(); messageRefs.add(ref); } } MessageReference ref = message.message.makeMessageReference(); Log.i(K9.LOG_TAG, "MessageList sending message " + ref); MessageView.actionView(this, ref, messageRefs); } /* * We set read=true here for UI performance reasons. The actual value * will get picked up on the refresh when the Activity is resumed but * that may take a second or so and we don't want this to show and * then go away. I've gone back and forth on this, and this gives a * better UI experience, so I am putting it back in. */ if (!message.read) { message.read = true; } } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount); finish(); } private void onCompose() { if (mQueryString != null) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ MessageCompose.actionCompose(this, null); } else { MessageCompose.actionCompose(this, mAccount); } } private void onEditPrefs() { Prefs.actionPrefs(this); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SORT_TYPE newSortType) { if (sortType == newSortType) { onToggleSortAscending(); } else { sortType = newSortType; mController.setSortType(sortType); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mHandler.sortMessages(); } private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onToggleSortAscending() { mController.setSortAscending(sortType, !sortAscending); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } private void onDelete(MessageInfoHolder holder, int position) { mAdapter.removeMessage(holder); mController.deleteMessages(new Message[] { holder.message }, null); } private void onMove(MessageInfoHolder holder) { if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } final Account account = holder.message.getFolder().getAccount(); Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, account.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, account.getLastSelectedFolderName()); intent.putExtra(ChooseFolder.EXTRA_MESSAGE, holder.message.makeMessageReference()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE); } private void onArchive(MessageInfoHolder holder) { if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } onMoveChosen(holder, holder.message.getFolder().getAccount().getArchiveFolderName()); } private void onSpam(MessageInfoHolder holder) { if (K9.confirmSpam()) { // The action handler needs this to move the message later mSelectedMessage = holder; showDialog(R.id.dialog_confirm_spam); } else { moveToSpamFolder(holder); } } private void moveToSpamFolder(MessageInfoHolder holder){ if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } onMoveChosen(holder, holder.message.getFolder().getAccount().getSpamFolderName()); } private void onCopy(MessageInfoHolder holder) { if (!mController.isCopyCapable(holder.message.getFolder().getAccount())) { return; } if (!mController.isCopyCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } final Account account = holder.message.getFolder().getAccount(); Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, account.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, account.getLastSelectedFolderName()); intent.putExtra(ChooseFolder.EXTRA_MESSAGE, holder.message.makeMessageReference()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) return; switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: { if (data == null) return; final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final MessageReference ref = data.getParcelableExtra(ChooseFolder.EXTRA_MESSAGE); final MessageInfoHolder m = mAdapter.getMessage(ref); if ((destFolderName != null) && (m != null)) { final Account account = m.message.getFolder().getAccount(); account.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: onMoveChosen(m, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: onCopyChosen(m, destFolderName); break; } } break; } case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: { final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final String accountUuid = data.getStringExtra(ChooseFolder.EXTRA_ACCOUNT); final Account account = Preferences.getPreferences(this).getAccount(accountUuid); account.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: onMoveChosenBatch(destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: onCopyChosenBatch(destFolderName); break; } } } } private void onMoveChosen(MessageInfoHolder holder, String folderName) { if (mController.isMoveCapable(holder.message.getFolder().getAccount()) && folderName != null) { if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } mAdapter.removeMessage(holder); mController.moveMessage(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onCopyChosen(MessageInfoHolder holder, String folderName) { if (mController.isCopyCapable(holder.message.getFolder().getAccount()) && folderName != null) { mController.copyMessage(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, false, null); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, true, null); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, holder.message.getFolder().getAccount(), holder.message, null); } private void onMarkAllAsRead(final Account account, final String folder) { showDialog(DIALOG_MARK_ALL_AS_READ); } private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return ConfirmationDialog.create(this, id, R.string.mark_all_as_read_dlg_title, getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName), R.string.okay_action, R.string.cancel_action, new Runnable() { @Override public void run() { try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } } mHandler.sortMessages(); } catch (Exception e) { // Ignore } } }); case R.id.dialog_confirm_spam: return ConfirmationDialog.create(this, id, R.string.dialog_confirm_spam_title, R.string.dialog_confirm_spam_message, R.string.dialog_confirm_spam_confirm_button, R.string.dialog_confirm_spam_cancel_button, new Runnable() { @Override public void run() { moveToSpamFolder(mSelectedMessage); // No further need for this reference mSelectedMessage = null; } }); } return super.onCreateDialog(id); } @Override public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: { if (mCurrentFolder != null) { ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); } break; } default: { super.onPrepareDialog(id, dialog); } } } private void onToggleRead(MessageInfoHolder holder) { mController.setFlag(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } private void onToggleFlag(MessageInfoHolder holder) { mController.setFlag(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener, null); mController.sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.compose: { onCompose(); return true; } case R.id.accounts: { onAccounts(); return true; } case R.id.set_sort_date: { changeSort(SORT_TYPE.SORT_DATE); return true; } case R.id.set_sort_subject: { changeSort(SORT_TYPE.SORT_SUBJECT); return true; } case R.id.set_sort_sender: { changeSort(SORT_TYPE.SORT_SENDER); return true; } case R.id.set_sort_flag: { changeSort(SORT_TYPE.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { changeSort(SORT_TYPE.SORT_UNREAD); return true; } case R.id.set_sort_attach: { changeSort(SORT_TYPE.SORT_ATTACHMENT); return true; } case R.id.select_all: case R.id.batch_select_all: { setAllSelected(true); toggleBatchButtons(); return true; } case R.id.batch_deselect_all: { setAllSelected(false); toggleBatchButtons(); return true; } case R.id.batch_delete_op: { deleteSelected(); return true; } case R.id.batch_mark_read_op: { flagSelected(Flag.SEEN, true); return true; } case R.id.batch_mark_unread_op: { flagSelected(Flag.SEEN, false); return true; } case R.id.batch_flag_op: { flagSelected(Flag.FLAGGED, true); return true; } case R.id.batch_unflag_op: { flagSelected(Flag.FLAGGED, false); return true; } case R.id.app_settings: { onEditPrefs(); return true; } } if (mQueryString != null) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.check_mail: { if (mFolderName != null) { checkMail(mAccount, mFolderName); } return true; } case R.id.send_messages: { mController.sendPendingMessages(mAccount, mAdapter.mListener); return true; } case R.id.list_folders: { onShowFolderList(); return true; } case R.id.mark_all_as_read: { if (mFolderName != null) { onMarkAllAsRead(mAccount, mFolderName); } return true; } case R.id.folder_settings: { if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; } case R.id.account_settings: { onEditAccount(); return true; } case R.id.batch_copy_op: { onCopyBatch(); return true; } case R.id.batch_archive_op: { onArchiveBatch(); return true; } case R.id.batch_spam_op: { onSpamBatch(); return true; } case R.id.batch_move_op: { onMoveBatch(); return true; } case R.id.expunge: { if (mCurrentFolder != null) { onExpunge(mAccount, mCurrentFolder.name); } return true; } default: { return super.onOptionsItemSelected(item); } } } private final int[] batch_ops = { R.id.batch_copy_op, R.id.batch_delete_op, R.id.batch_flag_op, R.id.batch_unflag_op, R.id.batch_mark_read_op, R.id.batch_mark_unread_op, R.id.batch_archive_op, R.id.batch_spam_op, R.id.batch_move_op, R.id.batch_select_all, R.id.batch_deselect_all }; private void setOpsState(Menu menu, boolean state, boolean enabled) { for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean anySelected = anySelected(); menu.findItem(R.id.select_all).setVisible(! anySelected); menu.findItem(R.id.batch_ops).setVisible(anySelected); setOpsState(menu, true, anySelected); if (mQueryString != null) { menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.list_folders).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.batch_archive_op).setVisible(false); menu.findItem(R.id.batch_spam_op).setVisible(false); menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); } else { if (mCurrentFolder != null && mCurrentFolder.name.equals(mAccount.getOutboxFolderName())) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) { menu.findItem(R.id.batch_archive_op).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) { menu.findItem(R.id.batch_spam_op).setVisible(false); } } boolean newFlagState = computeBatchDirection(true); boolean newReadState = computeBatchDirection(false); menu.findItem(R.id.batch_flag_op).setVisible(newFlagState); menu.findItem(R.id.batch_unflag_op).setVisible(!newFlagState); menu.findItem(R.id.batch_mark_read_op).setVisible(newReadState); menu.findItem(R.id.batch_mark_unread_op).setVisible(!newReadState); menu.findItem(R.id.batch_deselect_all).setVisible(anySelected); menu.findItem(R.id.batch_select_all).setEnabled(true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); MessageInfoHolder holder = mSelectedMessage; // don't need this anymore mSelectedMessage = null; if (holder == null) { holder = (MessageInfoHolder) mAdapter.getItem(info.position); } switch (item.getItemId()) { case R.id.open: { onOpenMessage(holder); break; } case R.id.select: { setSelected(holder, true); break; } case R.id.deselect: { setSelected(holder, false); break; } case R.id.delete: { onDelete(holder, info.position); break; } case R.id.reply: { onReply(holder); break; } case R.id.reply_all: { onReplyAll(holder); break; } case R.id.forward: { onForward(holder); break; } case R.id.send_again: { onResendMessage(holder); break; } case R.id.mark_as_read: { onToggleRead(holder); break; } case R.id.flag: { onToggleFlag(holder); break; } case R.id.archive: { onArchive(holder); break; } case R.id.spam: { onSpam(holder); break; } case R.id.move: { onMove(holder); break; } case R.id.copy: { onCopy(holder); break; } case R.id.send_alternate: { onSendAlternate(mAccount, holder); break; } case R.id.same_sender: { MessageList.actionHandle(MessageList.this, "From " + holder.sender, holder.senderAddress, true, null, null); break; } } return super.onContextItemSelected(item); } public void onSendAlternate(Account account, MessageInfoHolder holder) { mController.sendAlternate(this, account, holder.message); } public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); if (bar == null) { return; } bar.setIndeterminate(true); if (status) { bar.setVisibility(ProgressBar.VISIBLE); } else { bar.setVisibility(ProgressBar.INVISIBLE); } } class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e2 == null || e1 == null) return true; float deltaX = e2.getX() - e1.getX(), deltaY = e2.getY() - e1.getY(); boolean movedAcross = (Math.abs(deltaX) > Math.abs(deltaY * 4)); boolean steadyHand = (Math.abs(deltaX / deltaY) > 2); if (movedAcross && steadyHand) { boolean selected = (deltaX > 0); int position = mListView.pointToPosition((int)e1.getX(), (int)e1.getY()); if (position != AdapterView.INVALID_POSITION) { MessageInfoHolder msgInfoHolder = (MessageInfoHolder) mAdapter.getItem(position); if (msgInfoHolder != null && msgInfoHolder.selected != selected) { msgInfoHolder.selected = selected; mSelectedCount += (selected ? 1 : -1); mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } } } return false; } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position); // remember which message was originally selected, in case the list changes while the // dialog is up mSelectedMessage = message; if (message == null) { return; } getMenuInflater().inflate(R.menu.message_list_context, menu); menu.setHeaderTitle(message.message.getSubject()); if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } Account account = message.message.getFolder().getAccount(); if (!mController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!mController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(account.getArchiveFolderName())) { menu.findItem(R.id.archive).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(account.getSpamFolderName())) { menu.findItem(R.id.spam).setVisible(false); } if (message.selected) { menu.findItem(R.id.select).setVisible(false); menu.findItem(R.id.deselect).setVisible(true); } else { menu.findItem(R.id.select).setVisible(true); menu.findItem(R.id.deselect).setVisible(false); } } class MessageListAdapter extends BaseAdapter { private final List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private final ActivityListener mListener = new ActivityListener() { @Override public void informUserOfStatus() { mHandler.refreshTitle(); } @Override public void synchronizeMailboxStarted(Account account, String folder) { if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } super.synchronizeMailboxStarted(account, folder); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } super.synchronizeMailboxFailed(account, folder, message); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, true); } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) { MessageInfoHolder holder = getMessage(message); if (holder == null) { Log.w(K9.LOG_TAG, "Got callback to remove non-existent message with UID " + message.getUid()); } else { removeMessage(holder); } } @Override public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.progress(true); if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesRemoveMessage(Account account, String folder, Message message) { MessageInfoHolder holder = getMessage(message); if (holder != null) { removeMessage(holder); } } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages, false); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, false); } @Override public void searchStats(AccountStats stats) { mUnreadMessageCount = stats.unreadMessageCount; super.searchStats(stats); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; } super.folderStatusChanged(account, folder, unreadMessageCount); } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { MessageReference ref = new MessageReference(); ref.accountUuid = account.getUuid(); ref.folderName = folder; ref.uid = oldUid; MessageInfoHolder holder = getMessage(ref); if (holder != null) { holder.uid = newUid; holder.message.setUid(newUid); } } }; private boolean updateForMe(Account account, String folder) { if ((account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; } else { return false; } } private Drawable mAttachmentIcon; private Drawable mAnsweredIcon; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_email_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_answered_small); } public void markAllMessagesAsDirty() { for (MessageInfoHolder holder : mAdapter.messages) { holder.dirty = true; } } public void pruneDirtyMessages() { synchronized (mAdapter.messages) { Iterator<MessageInfoHolder> iter = mAdapter.messages.iterator(); while (iter.hasNext()) { MessageInfoHolder holder = iter.next(); if (holder.dirty) { if (holder.selected) { mSelectedCount toggleBatchButtons(); } mAdapter.removeMessage(holder); } } } } public void removeMessages(List<MessageInfoHolder> holders) { if (holders != null) { mHandler.removeMessage(holders); } } public void removeMessage(MessageInfoHolder holder) { List<MessageInfoHolder> messages = new ArrayList<MessageInfoHolder>(); messages.add(holder); removeMessages(messages); } private void addOrUpdateMessage(Account account, String folderName, Message message, boolean verifyAgainstSearch) { List<Message> messages = new ArrayList<Message>(); messages.add(message); addOrUpdateMessages(account, folderName, messages, verifyAgainstSearch); } private void addOrUpdateMessages(final Account account, final String folderName, final List<Message> providedMessages, final boolean verifyAgainstSearch) { // we copy the message list because the callback doesn't expect // the callbacks to mutate it. final List<Message> messages = new ArrayList<Message>(providedMessages); boolean needsSort = false; final List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); List<Message> messagesToSearch = new ArrayList<Message>(); // cache field into local variable for faster access for JVM without JIT final MessageHelper messageHelper = mMessageHelper; for (Message message : messages) { MessageInfoHolder m = getMessage(message); if (message.isSet(Flag.DELETED)) { if (m != null) { messagesToRemove.add(m); } } else { final Folder messageFolder = message.getFolder(); final Account messageAccount = messageFolder.getAccount(); if (m == null) { if (updateForMe(account, folderName)) { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } else { if (mQueryString != null) { if (verifyAgainstSearch) { messagesToSearch.add(message); } else { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } } } } else { m.dirty = false; // as we reload the message, unset its dirty flag messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, account), account); needsSort = true; } } } if (messagesToSearch.size() > 0) { mController.searchLocalMessages(mAccountUuids, mFolderNames, messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY), mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, new MessagingListener() { @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages, false); } }); } if (messagesToRemove.size() > 0) { removeMessages(messagesToRemove); } if (messagesToAdd.size() > 0) { mHandler.addMessages(messagesToAdd); } if (needsSort) { mHandler.sortMessages(); mHandler.resetUnreadCount(); } } public MessageInfoHolder getMessage(Message message) { return getMessage(message.makeMessageReference()); } // XXX TODO - make this not use a for loop public MessageInfoHolder getMessage(MessageReference messageReference) { synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { /* * 2010-06-21 - cketti * Added null pointer check. Not sure what's causing 'holder' * to be null. See log provided in issue 1749, comment #15. * * Please remove this comment once the cause was found and the * bug(?) fixed. */ if ((holder != null) && holder.message.equalsReference(messageReference)) { return holder; } } } return null; } public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; try { LocalStore localStore = account.getLocalStore(); local_folder = localStore.getFolder(folder); return new FolderInfoHolder(context, local_folder, account); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ", e); return null; } finally { if (local_folder != null) { local_folder.close(); } } } private final OnClickListener flagClickListener = new OnClickListener() { public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); } }; @Override public int getCount() { return messages.size(); } @Override public long getItemId(int position) { try { MessageInfoHolder messageHolder = (MessageInfoHolder) getItem(position); if (messageHolder != null) { return messageHolder.message.getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG, "getItemId(" + position + ") ", e); } return -1; } public Object getItem(long position) { return getItem((int)position); } @Override public Object getItem(int position) { try { synchronized (mAdapter.messages) { if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } @Override public View getView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { if (mTouchView) { view = mInflater.inflate(R.layout.message_list_item_touchable, parent, false); view.setId(R.layout.message_list_item); } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); } } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.preview = (TextView) view.findViewById(R.id.preview); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(flagClickListener); if (!mStars) { holder.flagged.setVisibility(View.GONE); } if (mCheckboxes) { holder.selected.setVisibility(View.VISIBLE); } if (holder.selected != null) { holder.selected.setOnCheckedChangeListener(holder); } holder.subject.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSubject()); holder.date.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListDate()); if (mTouchView) { holder.preview.setLines(mPreviewLines); holder.preview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListPreview()); } else { holder.from.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSender()); } view.setTag(holder); } if (message != null) { bindView(position, view, holder, message); } else { // This branch code is triggered when the local store // hands us an invalid message holder.chip.getBackground().setAlpha(0); holder.subject.setText(getString(R.string.general_no_subject)); holder.subject.setTypeface(null, Typeface.NORMAL); String noSender = getString(R.string.general_no_sender); if (holder.preview != null) { holder.preview.setText(noSender, TextView.BufferType.SPANNABLE); Spannable str = (Spannable) holder.preview.getText(); ColorStateList color = holder.subject.getTextColors(); ColorStateList linkColor = holder.subject.getLinkTextColors(); str.setSpan(new TextAppearanceSpan(null, Typeface.NORMAL, mFontSizes.getMessageListSender(), color, linkColor), 0, noSender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } else { holder.from.setText(noSender); holder.from.setTypeface(null, Typeface.NORMAL); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } holder.date.setText(getString(R.string.general_no_date)); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); if (!mCheckboxes) { holder.selected.setVisibility(View.GONE); } holder.flagged.setChecked(false); } return view; } /** * Associate model data to view object. * * @param position * The position of the item within the adapter's data set of * the item whose view we want. * @param view * Main view component to alter. Never <code>null</code>. * @param holder * Convenience view holder - eases access to <tt>view</tt> * child views. Never <code>null</code>. * @param message * Never <code>null</code>. */ private void bindView(final int position, final View view, final MessageViewHolder holder, final MessageInfoHolder message) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag(position); holder.flagged.setChecked(message.flagged); // So that the mSelectedCount is only incremented/decremented // when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); if (!mCheckboxes) { holder.selected.setVisibility(message.selected ? View.VISIBLE : View.GONE); } holder.chip.setBackgroundDrawable(message.message.getFolder().getAccount().generateColorChip().drawable()); holder.chip.getBackground().setAlpha(message.read ? 127 : 255); view.getBackground().setAlpha(message.downloaded ? 0 : 127); if ((message.message.getSubject() == null) || message.message.getSubject().equals("")) { holder.subject.setText(getText(R.string.general_no_subject)); } else { holder.subject.setText(message.message.getSubject()); } int senderTypeface = message.read ? Typeface.NORMAL : Typeface.BOLD; if (holder.preview != null) { /* * In the touchable UI, we have previews. Otherwise, we * have just a "from" line. * Because text views can't wrap around each other(?) we * compose a custom view containing the preview and the * from. */ holder.preview.setText(new SpannableStringBuilder(recipientSigil(message)) .append(message.sender).append(" ").append(message.message.getPreview()), TextView.BufferType.SPANNABLE); Spannable str = (Spannable)holder.preview.getText(); // Create a span section for the sender, and assign the correct font size and weight. ColorStateList color = holder.subject.getTextColors(); ColorStateList linkColor = holder.subject.getLinkTextColors(); str.setSpan(new TextAppearanceSpan(null, senderTypeface, mFontSizes.getMessageListSender(), color, linkColor), 0, message.sender.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); } else { holder.from.setText(new SpannableStringBuilder(recipientSigil(message)).append(message.sender)); holder.from.setTypeface(null, senderTypeface); } holder.date.setText(message.getDate(mMessageHelper)); holder.subject.setCompoundDrawablesWithIntrinsicBounds( message.answered ? mAnsweredIcon : null, // left null, // top message.message.hasAttachments() ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } private String recipientSigil(MessageInfoHolder message) { if (message.message.toMe()) { return getString(R.string.messagelist_sent_to_me_sigil); } else if (message.message.ccMe()) { return getString(R.string.messagelist_sent_cc_me_sigil); } else { return ""; } } @Override public boolean hasStableIds() { return true; } public boolean isItemSelectable(int position) { if (position < mAdapter.messages.size()) { return true; } else { return false; } } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position != -1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message.selected != isChecked) { if (isChecked) { mSelectedCount++; } else if (mSelectedCount > 0) { mSelectedCount } // We must set the flag before showing the buttons as the // buttons text depends on what is selected. message.selected = isChecked; if (!mCheckboxes) { if (isChecked) { selected.setVisibility(View.VISIBLE); } else { selected.setVisibility(View.GONE); } } toggleBatchButtons(); } } } } private View getFooterView(ViewGroup parent) { if (mFooterView == null) { mFooterView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); if (mQueryString != null) { mFooterView.setVisibility(View.GONE); } mFooterView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar) mFooterView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView) mFooterView.findViewById(R.id.main_text); mFooterView.setTag(holder); } return mFooterView; } private void updateFooterView() { FooterViewHolder holder = (FooterViewHolder) mFooterView.getTag(); if (mCurrentFolder != null && mAccount != null) { if (mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (!mCurrentFolder.lastCheckFailed) { if (mAccount.getDisplayCount() == 0) { holder.main.setText(getString(R.string.message_list_load_more_messages_action)); } else { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } } else { holder.progress.setVisibility(ProgressBar.INVISIBLE); } } private void hideBatchButtons() { if (mBatchButtonArea.getVisibility() != View.GONE) { mBatchButtonArea.setVisibility(View.GONE); mBatchButtonArea.startAnimation( AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); } } private void showBatchButtons() { if (mBatchButtonArea.getVisibility() != View.VISIBLE) { mBatchButtonArea.setVisibility(View.VISIBLE); Animation animation = AnimationUtils.loadAnimation(this, R.anim.footer_appear); animation.setAnimationListener(this); mBatchButtonArea.startAnimation(animation); } } private void toggleBatchButtons() { runOnUiThread(new Runnable() { @Override public void run() { if (mSelectedCount < 0) { mSelectedCount = 0; } int readButtonIconId; int flagButtonIconId; if (mSelectedCount == 0) { readButtonIconId = R.drawable.ic_button_mark_read; flagButtonIconId = R.drawable.ic_button_flag; hideBatchButtons(); } else { boolean newReadState = computeBatchDirection(false); if (newReadState) { readButtonIconId = R.drawable.ic_button_mark_read; } else { readButtonIconId = R.drawable.ic_button_mark_unread; } boolean newFlagState = computeBatchDirection(true); if (newFlagState) { flagButtonIconId = R.drawable.ic_button_flag; } else { flagButtonIconId = R.drawable.ic_button_unflag; } showBatchButtons(); } mBatchReadButton.setImageResource(readButtonIconId); mBatchFlagButton.setImageResource(flagButtonIconId); } }); } static class FooterViewHolder { public ProgressBar progress; public TextView main; } private boolean computeBatchDirection(boolean flagged) { boolean newState = false; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (flagged) { if (!holder.flagged) { newState = true; break; } } else { if (!holder.read) { newState = true; break; } } } } } return newState; } private boolean anySelected() { synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { return true; } } } return false; } @Override public void onClick(View v) { boolean newState = false; List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); if (v == mBatchDoneButton) { setAllSelected(false); return; } if (v == mBatchFlagButton) { newState = computeBatchDirection(true); } else { newState = computeBatchDirection(false); } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (v == mBatchDeleteButton) { removeHolderList.add(holder); } else if (v == mBatchFlagButton) { holder.flagged = newState; } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); } } } mAdapter.removeMessages(removeHolderList); if (!messageList.isEmpty()) { if (v == mBatchDeleteButton) { mController.deleteMessages(messageList.toArray(EMPTY_MESSAGE_ARRAY), null); mSelectedCount = 0; toggleBatchButtons(); } else { mController.setFlag(messageList.toArray(EMPTY_MESSAGE_ARRAY), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } } else { // Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } public void onAnimationEnd(Animation animation) { } public void onAnimationRepeat(Animation animation) { } public void onAnimationStart(Animation animation) { } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } } mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } private void setSelected(MessageInfoHolder holder, boolean newState) { if (holder.selected != newState) { holder.selected = newState; mSelectedCount += (newState ? 1 : -1); } mAdapter.notifyDataSetChanged(); toggleBatchButtons(); } private void flagSelected(Flag flag, boolean newState) { List<Message> messageList = new ArrayList<Message>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { messageList.add(holder.message); if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } } } mController.setFlag(messageList.toArray(EMPTY_MESSAGE_ARRAY), flag, newState); mHandler.sortMessages(); } private void deleteSelected() { List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { removeHolderList.add(holder); messageList.add(holder.message); } } } mAdapter.removeMessages(removeHolderList); mController.deleteMessages(messageList.toArray(EMPTY_MESSAGE_ARRAY), null); mSelectedCount = 0; toggleBatchButtons(); } private void onMoveBatch() { if (!mController.isMoveCapable(mAccount)) { return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } } } } final Folder folder = mCurrentFolder.folder; final Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName()); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, folder.getAccount().getLastSelectedFolderName()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH); } private void onMoveChosenBatch(String folderName) { if (!mController.isMoveCapable(mAccount)) { return; } List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } messageList.add(holder.message); removeHolderList.add(holder); } } } mAdapter.removeMessages(removeHolderList); mController.moveMessages(mAccount, mCurrentFolder.name, messageList.toArray(EMPTY_MESSAGE_ARRAY), folderName, null); mSelectedCount = 0; toggleBatchButtons(); } private void onArchiveBatch() { String folderName = mAccount.getArchiveFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } onMoveChosenBatch(folderName); } private void onSpamBatch() { String folderName = mAccount.getSpamFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } onMoveChosenBatch(folderName); } private void onCopyBatch() { if (!mController.isCopyCapable(mAccount)) { return; } synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isCopyCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } } } } final Folder folder = mCurrentFolder.folder; final Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName()); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, folder.getAccount().getLastSelectedFolderName()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY_BATCH); } private void onCopyChosenBatch(String folderName) { if (!mController.isCopyCapable(mAccount)) { return; } List<Message> messageList = new ArrayList<Message>(); synchronized (mAdapter.messages) { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { Message message = holder.message; if (!mController.isCopyCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } messageList.add(holder.message); } } } mController.copyMessages(mAccount, mCurrentFolder.name, messageList.toArray(EMPTY_MESSAGE_ARRAY), folderName, null); } protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); } }
package ru.job4j.io; import org.junit.Test; import java.io.*; import static org.junit.Assert.assertEquals; /** * Class Analyze | Analyze server availability [#859] * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com) * @since 10.04.2019 */ public class AnalyzeTest { /** * Test unavailable(). */ @Test public void whenReadLogFileThenGetAnavailablePeriods() throws Exception { String rootPath = System.getProperty("java.io.tmpdir"); final String separator = File.separator; File sourceData = new File(rootPath + separator + "sourcelog.txt"); PrintWriter sourceLog = new PrintWriter(sourceData); sourceLog.println("200 10:56:01"); sourceLog.println("500 10:57:01"); sourceLog.println("400 10:58:01"); sourceLog.println("200 10:59:01"); sourceLog.println("500 11:01:02"); sourceLog.println("200 11:02:02"); sourceLog.close(); Analyze analyze = new Analyze(); String source = sourceData.getPath(); String target = rootPath + separator + "target.csv"; analyze.unavailable(source, target); String expected = "10:57:01;10:59:01;"; String result; try (BufferedReader br = new BufferedReader(new FileReader(target))) { result = br.readLine(); } assertEquals(expected, result); } }
package org.pentaho.ui.xul.swt.tags; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TreeItem; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.DefaultBinding; import org.pentaho.ui.xul.binding.InlineBindingExpression; import org.pentaho.ui.xul.components.XulTreeCell; import org.pentaho.ui.xul.components.XulTreeCol; import org.pentaho.ui.xul.containers.XulTree; import org.pentaho.ui.xul.containers.XulTreeChildren; import org.pentaho.ui.xul.containers.XulTreeCols; import org.pentaho.ui.xul.containers.XulTreeItem; import org.pentaho.ui.xul.containers.XulTreeRow; import org.pentaho.ui.xul.dnd.DropEffectType; import org.pentaho.ui.xul.dnd.DropEvent; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swt.AbstractSwtXulContainer; import org.pentaho.ui.xul.swt.TableSelection; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeTextCellEditor; import org.pentaho.ui.xul.util.ColumnType; import org.pentaho.ui.xul.util.TreeCellEditor; import org.pentaho.ui.xul.util.TreeCellRenderer; public class SwtTree extends AbstractSwtXulContainer implements XulTree { // Tables and trees // share so much of the same API, I wrapped their common methods // into an interface (TabularWidget) and set the component to two // separate member variables here so that I don't have to reference // them separately. private static final Log logger = LogFactory.getLog(SwtTree.class); protected XulTreeCols columns = null; protected XulTreeChildren rootChildren = null; protected XulComponent parentComponent = null; private Object data = null; private boolean disabled = false; private boolean enableColumnDrag = false; private boolean editable = false; private String onedit; private String onSelect = null; private int rowsToDisplay = 0; private TableSelection selType = TableSelection.SINGLE; private boolean isHierarchical = false; private ColumnType[] currentColumnTypes = null; private int activeRow = -1; private int activeColumn = -1; private XulDomContainer domContainer; private TableViewer table; private TreeViewer tree; private int selectedIndex = -1; protected boolean controlDown; private int[] selectedRows; public SwtTree(Element self, XulComponent parent, XulDomContainer container, String tagName) { super(tagName); this.parentComponent = parent; // According to XUL spec, in order for a hierarchical tree to be rendered, a // primary column must be identified AND at least one treeitem must be // listed as a container. // Following code does not work with the current instantiation routine. When // transitioned to onDomReady() instantiation this should work. domContainer = container; } @Override public void layout() { XulComponent primaryColumn = this.getElementByXPath("treecols/treecol[@primary='true']"); XulComponent isaContainer = this.getElementByXPath("treechildren/treeitem[@container='true']"); isHierarchical = (primaryColumn != null) || (isaContainer != null); if (isHierarchical) { int style = (this.selType == TableSelection.MULTIPLE) ? SWT.MULTI : SWT.None; style |= SWT.BORDER; tree = new TreeViewer((Composite) parentComponent.getManagedObject(), style); setManagedObject(tree); } else { table = new TableViewer((Composite) parentComponent.getManagedObject(), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); setManagedObject(table); } if (isHierarchical) { setupTree(); if (getOndrag() != null) { DropEffectType effect = DropEffectType.COPY; if (getDrageffect() != null) { effect = DropEffectType.valueOfIgnoreCase(getDrageffect()); } super.enableDrag(effect); } if (getOndrop() != null) { super.enableDrop(); } } else { setupTable(); } this.initialized = true; } private void setupTree() { tree.setCellEditors(new CellEditor[] { new XulTreeTextCellEditor(tree.getTree()) }); tree.setCellModifier(new XulTreeColumnModifier(this)); tree.setLabelProvider(new XulTreeLabelProvider(this, this.domContainer)); tree.setContentProvider(new XulTreeContentProvider(this)); tree.setInput(this); tree.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); tree.setColumnProperties(new String[] { "0" }); //TreeViewerColumn tc = new TreeViewerColumn(tree, SWT.LEFT); TreeViewerEditor.create(tree, new ColumnViewerEditorActivationStrategy(tree) { @Override protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) { return super.isEditorActivationEvent(event); } }, ColumnViewerEditor.DEFAULT); tree.getTree().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = true; break; case SWT.ESC: // End editing session tree.getTree().deselectAll(); setSelectedRows(new int[] {}); break; } } @Override public void keyReleased(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = false; break; } } }); // Add a focus listener to clear the contol down selector tree.getTree().addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { } public void focusLost(FocusEvent arg0) { if (tree.getCellEditors()[0].isActivated() == false) { SwtTree.this.controlDown = false; } } }); tree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { // if the selection is empty clear the label if (event.getSelection().isEmpty()) { SwtTree.this.setSelectedIndex(-1); return; } if (event.getSelection() instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); int[] selected = new int[selection.size()]; List selectedItems = new ArrayList(); int i = 0; for (Object o : selection.toArray()) { XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), selectedItem); selected[i++] = b.curPos; selectedItems.add(b.selectedItem); } if (selected.length == 0) { setSelectedIndex(-1); } else { setSelectedIndex(selected[0]); } int[] selectedRows = null; if (SwtTree.this.controlDown && Arrays.equals(selected, selectedRows) && tree.getCellEditors()[0].isActivated() == false) { tree.getTree().deselectAll(); selectedRows = new int[] {}; } else { selectedRows = selected; } changeSupport.firePropertyChange("selectedRows", null, selectedRows); changeSupport.firePropertyChange("absoluteSelectedRows", null, selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); //Single selection binding. Object selectedItem = (selectedItems.size() > 0) ? selectedItems.get(0) : null; changeSupport.firePropertyChange("selectedItem", null, selectedItem); } } }); } private class SearchBundle { int curPos; boolean found; Object selectedItem; } private SearchBundle findSelectedIndex(SearchBundle bundle, XulTreeChildren children, XulTreeItem selectedItem) { for (XulComponent c : children.getChildNodes()) { if (c == selectedItem) { bundle.found = true; if (elements != null) { bundle.selectedItem = findSelectedTreeItem(bundle.curPos); } return bundle; } bundle.curPos++; if (c.getChildNodes().size() > 1) { SearchBundle b = findSelectedIndex(bundle, (XulTreeChildren) c.getChildNodes().get(1), selectedItem); if (b.found) { return b; } } } return bundle; } private Object findSelectedTreeItem(int pos) { if (this.isHierarchical && this.elements != null) { if (elements == null || elements.size() == 0) { return null; } String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); if (pos == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, method, new FindSelectedItemTuple(pos)); return tuple != null ? tuple.selectedItem : null; } return null; } private void setupTable() { table.setContentProvider(new XulTableContentProvider(this)); table.setLabelProvider(new XulTableColumnLabelProvider(this)); table.setCellModifier(new XulTableColumnModifier(this)); Table baseTable = table.getTable(); baseTable.setLayoutData(new GridData(GridData.FILL_BOTH)); setupColumns(); table.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf(selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i = 0; for (Iterator it = selection.iterator(); it.hasNext();) { Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } changeSupport.firePropertyChange("selectedRows", null, selectedRows); changeSupport.firePropertyChange("absoluteSelectedRows", null, selectedRows); Collection selectedItems = findSelectedTableRows(selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); //Single selection binding. Object selectedItem = (selectedItems.size() > 0) ? selectedItems.toArray()[0] : null; changeSupport.firePropertyChange("selectedItem", null, selectedItem); } }); // Turn on the header and the lines baseTable.setHeaderVisible(true); baseTable.setLinesVisible(true); table.setInput(this); final Composite parentComposite = ((Composite) parentComponent.getManagedObject()); parentComposite.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { resizeColumns(); } }); table.getTable().setEnabled(!this.disabled); table.refresh(); } private Collection findSelectedTableRows(int[] selectedRows) { if (elements == null) { return Collections.emptyList(); } List selectedItems = new ArrayList(); for (int i = 0; i < selectedRows.length; i++) { if (selectedRows[i] >= 0 && selectedRows[i] < elements.size()) { selectedItems.add(elements.toArray()[selectedRows[i]]); } } return selectedItems; } private void resizeColumns() { final Composite parentComposite = ((Composite) parentComponent.getManagedObject()); Rectangle area = parentComposite.getClientArea(); Point preferredSize = table.getTable().computeSize(SWT.DEFAULT, SWT.DEFAULT); int width = area.width - 2 * table.getTable().getBorderWidth(); if (preferredSize.y > area.height + table.getTable().getHeaderHeight()) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getTable().getVerticalBar().getSize(); width -= vBarSize.x; } width -= 20; double totalFlex = 0; for (XulComponent col : getColumns().getChildNodes()) { totalFlex += ((XulTreeCol) col).getFlex(); } int colIdx = 0; for (XulComponent col : getColumns().getChildNodes()) { if (colIdx >= table.getTable().getColumnCount()) { break; } TableColumn c = table.getTable().getColumn(colIdx); int colFlex = ((XulTreeCol) col).getFlex(); if (totalFlex == 0) { c.setWidth(Math.round(width / getColumns().getColumnCount())); } else if (colFlex > 0) { c.setWidth(Integer.parseInt("" + Math.round(width * (colFlex / totalFlex)))); } colIdx++; } } private void setSelectedIndex(int idx) { this.selectedIndex = idx; changeSupport.firePropertyChange("selectedRows", null, new int[] { idx }); changeSupport.firePropertyChange("absoluteSelectedRows", null, new int[] { idx }); if (this.onSelect != null) { invoke(this.onSelect, new Object[] { new Integer(idx) }); } } private void createColumnTypesSnapshot() { if (this.columns.getChildNodes().size() > 0) { Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); currentColumnTypes = new ColumnType[xulTreeColArray.length]; for (int i = 0; i < xulTreeColArray.length; i++) { currentColumnTypes[i] = ColumnType.valueOf(((XulTreeCol) xulTreeColArray[i]).getType()); } } else { // Create an empty array to indicate that it has been processed, but contains 0 columns currentColumnTypes = new ColumnType[0]; } } private boolean columnsNeedUpdate() { // Differing number of columsn if (table.getTable().getColumnCount() != this.columns.getColumnCount()) { return true; } // First run, always update if (currentColumnTypes == null) { return true; } // Column Types have changed Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); for (int i = 0; i < xulTreeColArray.length; i++) { if (!currentColumnTypes[i].toString().equalsIgnoreCase(((XulTreeCol) xulTreeColArray[i]).getType())) { // A column has changed its type. Columns need updating return true; } } // Columns have not changed and do not need updating return false; } private void setupColumns() { if (columnsNeedUpdate()) { while (table.getTable().getColumnCount() > 0) { table.getTable().getColumn(0).dispose(); } // Add Columns for (XulComponent col : this.columns.getChildNodes()) { TableColumn tc = new TableColumn(table.getTable(), SWT.LEFT); String lbl = ((XulTreeCol) col).getLabel(); tc.setText(lbl != null ? lbl : ""); //$NON-NLS-1$ } // Pack the columns for (int i = 0; i < table.getTable().getColumnCount(); i++) { table.getTable().getColumn(i).pack(); } } if (table.getCellEditors() != null) { for (int i = 0; i < table.getCellEditors().length; i++) { table.getCellEditors()[i].dispose(); } } CellEditor[] editors = new CellEditor[this.columns.getChildNodes().size()]; String[] names = new String[getColumns().getColumnCount()]; int i = 0; for (XulComponent c : this.columns.getChildNodes()) { XulTreeCol col = (XulTreeCol) c; final int colIdx = i; CellEditor editor; ColumnType type = col.getColumnType(); switch (type) { case CHECKBOX: editor = new CheckboxCellEditor(table.getTable()); break; case COMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}, SWT.READ_ONLY); break; case EDITABLECOMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}); // final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); // editableControl.addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent arg0) { // super.keyReleased(arg0); // XulTreeCell cell = getCell(colIdx); // cell.setLabel(editableControl.getText()); break; case TEXT: default: editor = new TextCellEditor(table.getTable()); // final Text textControl = (Text) ((TextCellEditor) editor).getControl(); // textControl.addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent arg0) { // super.keyReleased(arg0); // XulTreeCell cell = getCell(colIdx); // cell.setLabel(textControl.getText()); break; } // Create selection listener for comboboxes. if (type == ColumnType.EDITABLECOMBOBOX || type == ColumnType.COMBOBOX) { final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); editableControl.addSelectionListener(new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent arg0) { // TODO Auto-generated method stub super.widgetDefaultSelected(arg0); } @Override public void widgetSelected(SelectionEvent arg0) { super.widgetSelected(arg0); XulTreeCell cell = getCell(colIdx); cell.setSelectedIndex(editableControl.getSelectionIndex()); } }); } editors[i] = editor; names[i] = "" + i; //$NON-NLS-1$ i++; } table.setCellEditors(editors); table.setColumnProperties(names); resizeColumns(); createColumnTypesSnapshot(); } private XulTreeCell getCell(int colIdx) { return ((XulTreeItem) (table.getTable().getSelection()[0]).getData()).getRow().getCell(colIdx); } public boolean isHierarchical() { return isHierarchical; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; if (this.isHierarchical() == false && table != null) { table.getTable().setEnabled(!disabled); } } public int getRows() { return rowsToDisplay; } public void setRows(int rowsToDisplay) { this.rowsToDisplay = rowsToDisplay; if (table != null && (!table.getTable().isDisposed()) && (rowsToDisplay > 0)) { int ht = rowsToDisplay * table.getTable().getItemHeight(); if (table.getTable().getLayoutData() != null) { // tree.setSize(tree.getSize().x,height); ((GridData) table.getTable().getLayoutData()).heightHint = ht; ((GridData) table.getTable().getLayoutData()).minimumHeight = ht; table.getTable().getParent().layout(true); } } } public enum SELECTION_MODE { SINGLE, CELL, MULTIPLE }; public String getSeltype() { return selType.toString(); } public void setSeltype(String selType) { if (selType.equalsIgnoreCase(getSeltype())) { return; // nothing has changed } this.selType = TableSelection.valueOf(selType.toUpperCase()); } public TableSelection getTableSelection() { return selType; } public boolean isEditable() { return editable; } public boolean isEnableColumnDrag() { return enableColumnDrag; } public void setEditable(boolean edit) { editable = edit; } public void setEnableColumnDrag(boolean drag) { enableColumnDrag = drag; } public String getOnselect() { return onSelect; } public void setOnselect(final String method) { if (method == null) { return; } onSelect = method; } public void setColumns(XulTreeCols columns) { this.columns = columns; } public XulTreeCols getColumns() { return columns; } public XulTreeChildren getRootChildren() { if (rootChildren == null) { rootChildren = (XulTreeChildren) this.getChildNodes().get(1); } return rootChildren; } public void setRootChildren(XulTreeChildren rootChildren) { this.rootChildren = rootChildren; } public int[] getActiveCellCoordinates() { return new int[] { activeRow, activeColumn }; } public void setActiveCellCoordinates(int row, int column) { activeRow = row; activeColumn = column; } public Object[][] getValues() { Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()]; int y = 0; for (XulComponent item : getRootChildren().getChildNodes()) { int x = 0; for (XulComponent tempCell : ((XulTreeItem) item).getRow().getChildNodes()) { XulTreeCell cell = (XulTreeCell) tempCell; switch (columns.getColumn(x).getColumnType()) { case CHECKBOX: Boolean flag = (Boolean) cell.getValue(); if (flag == null) { flag = Boolean.FALSE; } data[y][x] = flag; break; case COMBOBOX: Vector values = (Vector) cell.getValue(); int idx = cell.getSelectedIndex(); data[y][x] = values.get(idx); break; default: // label data[y][x] = cell.getLabel(); break; } x++; } y++; } return data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public int[] getSelectedRows() { if (selectedIndex > -1) { return new int[] { selectedIndex }; } else { return new int[] {}; } } public int[] getAbsoluteSelectedRows() { return getSelectedRows(); } public Collection getSelectedItems() { if (elements == null) { return null; } if (isHierarchical()) { List selectedItems = new ArrayList(); IStructuredSelection selection = (IStructuredSelection) tree.getSelection(); int i = 0; for (Object o : selection.toArray()) { XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), selectedItem); selectedItems.add(b.selectedItem); } return selectedItems; } else { IStructuredSelection selection = (IStructuredSelection) table.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf(selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i = 0; for (Iterator it = selection.iterator(); it.hasNext();) { Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } return findSelectedTableRows(selectedRows); } } public void addTreeRow(XulTreeRow row) { this.addChild(row); XulTreeItem item = new SwtTreeItem(this.getRootChildren()); row.setParentTreeItem(item); ((SwtTreeRow) row).layout(); } public void removeTreeRows(int[] rows) { // TODO Auto-generated method stub } public void update() { if (this.isHierarchical) { this.tree.setInput(this); this.tree.refresh(); if ("true".equals(getAttributeValue("expanded"))) { tree.expandAll(); } else if(expandBindings.size() > 0){ for(DefaultBinding expBind : expandBindings){ try { expBind.fireSourceChanged(); } catch (Exception e) { logger.error(e); } } expandBindings.clear(); } } else { setupColumns(); this.table.setInput(this); this.table.refresh(); } this.selectedIndex = -1; } public void clearSelection() { } public void setSelectedRows(int[] rows) { if (this.isHierarchical) { Object selected = getSelectedTreeItem(rows); int prevSelected = -1; if (selectedRows != null && selectedRows.length > 0) { prevSelected = selectedRows[0]; // single selection only for now } // tree.setSelection(new StructuredSelection(getSelectedTreeItems(rows))); changeSupport.firePropertyChange("selectedItem", prevSelected, selected); } else { table.getTable().setSelection(rows); } if (rows.length > 0) { this.selectedIndex = rows[0]; // single selection only for now } changeSupport.firePropertyChange("selectedRows", this.selectedRows, rows); changeSupport.firePropertyChange("absoluteSelectedRows", this.selectedRows, rows); this.selectedRows = rows; } public String getOnedit() { return onedit; } public void setOnedit(String onedit) { this.onedit = onedit; } private Collection elements; private boolean suppressEvents = false; public <T> void setElements(Collection<T> elements) { this.elements = elements; this.getRootChildren().removeAll(); if (elements == null) { update(); changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); return; } try { if (this.isHierarchical == false) { for (T o : elements) { XulTreeRow row = this.getRootChildren().addNewRow(); for (int x = 0; x < this.getColumns().getChildNodes().size(); x++) { XulComponent col = this.getColumns().getColumn(x); final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); XulTreeCol column = (XulTreeCol) col; for (InlineBindingExpression exp : ((XulTreeCol) col).getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + o + "]"); String colType = column.getType(); if (StringUtils.isEmpty(colType) == false && colType.equals("dynamic")) { colType = extractDynamicColType(o, x); } Object bob = null; if ((colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")) && column.getCombobinding() != null) { DefaultBinding binding = new DefaultBinding(o, column.getCombobinding(), cell, "value"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); binding = new DefaultBinding(o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex"); binding.setConversion(new BindingConvertor<Object, Integer>() { @Override public Integer sourceToTarget(Object value) { int index = ((Vector) cell.getValue()).indexOf(value); return index > -1 ? index : 0; } @Override public Object targetToSource(Integer value) { return ((Vector) cell.getValue()).get(value); } }); domContainer.addBinding(binding); binding.fireSourceChanged(); if (colType.equalsIgnoreCase("editablecombobox")) { binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (!this.editable) { binding.setBindingType(Binding.Type.ONE_WAY); } else { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } domContainer.addBinding(binding); } } else if (colType.equalsIgnoreCase("checkbox")) { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp.getModelAttr(), cell, "value"); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } else { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } } if (column.getDisabledbinding() != null) { String prop = column.getDisabledbinding(); DefaultBinding bind = new DefaultBinding(o, column.getDisabledbinding(), cell, "disabled"); bind.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(bind); bind.fireSourceChanged(); } Method imageMethod; String imageSrc = null; String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(x)).getImagebinding()); if (method != null) { imageMethod = o.getClass().getMethod(method); imageSrc = (String) imageMethod.invoke(o); SwtTreeItem item = (SwtTreeItem)row.getParent(); item.setXulDomContainer(this.domContainer); ((XulTreeItem) row.getParent()).setImage(imageSrc); } row.addCell(cell); } } } else {// tree for (T o : elements) { SwtTreeItem item = new SwtTreeItem(this.getRootChildren()); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); this.getRootChildren().addChild(item); addTreeChild(o, newRow); } } update(); suppressEvents = false; // treat as a selection change changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); } catch (XulException e) { logger.error("error adding elements", e); } catch (Exception e) { logger.error("error adding elements", e); } } private List<DefaultBinding> expandBindings = new ArrayList<DefaultBinding>(); private <T> void addTreeChild(T element, XulTreeRow row) { try { XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)) .getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + element + "]"); // Tree Bindings are one-way for now as you cannot edit tree nodes DefaultBinding binding = new DefaultBinding(element, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (this.isEditable()) { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } else { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } String expBind = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getExpandedbinding(); if(expBind != null){ DefaultBinding binding = new DefaultBinding(element, expBind, row.getParent(), "expanded"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); expandBindings.add(binding); } row.addCell(cell); // find children String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); Method childrenMethod = null; try{ childrenMethod = element.getClass().getMethod(method, new Class[] {}); } catch(NoSuchMethodException e){ logger.info("Could not find children binding method for object: "+element.getClass().getSimpleName()); } method = ((XulTreeCol)this.getColumns().getChildNodes().get(0)).getImagebinding(); if (method != null) { DefaultBinding binding = new DefaultBinding(element, method, row.getParent(), "image"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); } Collection<T> children = null; if(childrenMethod != null){ children = (Collection<T>) childrenMethod.invoke(element, new Object[] {}); } else if(element instanceof Collection ){ children = (Collection<T>) element; } XulTreeChildren treeChildren = null; if (children != null && children.size() > 0) { treeChildren = (XulTreeChildren) getDocument().createElement("treechildren"); row.getParent().addChild(treeChildren); } if (children == null) { return; } for (T child : children) { SwtTreeItem item = new SwtTreeItem(treeChildren); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); treeChildren.addChild(item); addTreeChild(child, newRow); } } catch (Exception e) { logger.error("error adding elements", e); } } public <T> Collection<T> getElements() { return null; } private String extractDynamicColType(Object row, int columnPos) { try { Method method = row.getClass().getMethod(this.columns.getColumn(columnPos).getColumntypebinding()); return (String) method.invoke(row, new Object[] {}); } catch (Exception e) { logger.debug("Could not extract column type from binding"); } return "text"; // default //$NON-NLS-1$ } private static String toGetter(String property) { if (property == null) { return null; } return "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); } public Object getSelectedItem() { Collection c = getSelectedItems(); if(c != null && c.size() > 0){ return c.toArray()[0]; } return null; } // private List<Object> getSelectedTreeItems(int[] currentSelection) { // if (this.isHierarchical && this.elements != null) { // int[] vals = currentSelection; // if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) { // return null; // String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); // List<Object> selection = new ArrayList<Object>(); // for(int pos : currentSelection){ // FindBoundItemTuple tuple = new FindBoundItemTuple(pos); // findBoundItem(this.elements, this, property, tuple); // selection.add(tuple.treeItem); // return selection; // return null; private Object getSelectedTreeItem(int[] currentSelection) { if (this.isHierarchical && this.elements != null) { int[] vals = currentSelection; if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) { return null; } String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); int selectedIdx = vals[0]; if (selectedIdx == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(selectedIdx)); return tuple != null ? tuple.selectedItem : null; } return null; } private void fireSelectedItem() { this.changeSupport.firePropertyChange("selectedItem", null, getSelectedItem()); } private static class FindSelectedItemTuple { Object selectedItem = null; int curpos = -1; //ignores first element (root) int selectedIndex; public FindSelectedItemTuple(int selectedIndex) { this.selectedIndex = selectedIndex; } } private void removeItemFromElements(Object item) { String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); removeItem(elements, method, item); } private void removeItem(Object parent, String childrenMethodProperty, Object toRemove) { Collection children = getChildCollection(parent, childrenMethodProperty); if (children == null) { return; } Iterator iter = children.iterator(); while (iter.hasNext()) { Object next = iter.next(); if (next == toRemove) { iter.remove(); return; } removeItem(next, childrenMethodProperty, toRemove); } } private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty, FindSelectedItemTuple tuple) { if (tuple.curpos == tuple.selectedIndex) { tuple.selectedItem = parent; return tuple; } Collection children = getChildCollection(parent, childrenMethodProperty); if (children == null || children.size() == 0) { return null; } for (Object child : children) { tuple.curpos++; findSelectedItem(child, childrenMethodProperty, tuple); if (tuple.selectedItem != null) { return tuple; } } return null; } public void registerCellEditor(String key, TreeCellEditor editor) { // TODO Auto-generated method stub } public void registerCellRenderer(String key, TreeCellRenderer renderer) { // TODO Auto-generated method stub } public void collapseAll() { if (this.isHierarchical) { tree.collapseAll(); } } public void expandAll() { if (this.isHierarchical) { tree.expandAll(); } } private static class FindBoundItemTuple { Object item = null; XulComponent treeItem; public FindBoundItemTuple(Object item) { this.item = item; } } private static Collection getChildCollection(Object obj, String childrenMethodProperty) { Collection children = null; Method childrenMethod = null; try { childrenMethod = obj.getClass().getMethod(childrenMethodProperty, new Class[] {}); } catch (NoSuchMethodException e) { if (obj instanceof Collection) { children = (Collection) obj; } } try { if (childrenMethod != null) { children = (Collection) childrenMethod.invoke(obj, new Object[] {}); } } catch (Exception e) { logger.error(e); return null; } return children; } private static XulTreeChildren getTreeChildren(XulComponent parent) { for(XulComponent c : parent.getChildNodes()) { if (c instanceof XulTreeChildren) { return (XulTreeChildren) c; } } return null; } private FindBoundItemTuple findBoundItem(Object obj, XulComponent parent, String childrenMethodProperty, FindBoundItemTuple tuple) { if (obj.equals(tuple.item)) { tuple.treeItem = parent; return tuple; } Collection children = getChildCollection(obj, childrenMethodProperty); if (children == null || children.size() == 0) { return null; } XulTreeChildren xulChildren = getTreeChildren(parent); Object[] childrenArry = children.toArray(); for (int i=0; i< children.size(); i++) { findBoundItem(childrenArry[i], xulChildren.getChildNodes().get(i), childrenMethodProperty, tuple); if (tuple.treeItem != null) { return tuple; } } return null; } public void setBoundObjectExpanded(Object o, boolean expanded) { FindBoundItemTuple tuple = new FindBoundItemTuple(o); String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); findBoundItem(this.elements, this, property, tuple); if(tuple.treeItem != null) { setTreeItemExpanded((XulTreeItem) tuple.treeItem, expanded); } } public void setTreeItemExpanded(XulTreeItem item, boolean expanded){ if (this.isHierarchical) { tree.setExpandedState(item, expanded); } } @Override public void setPopup(Menu m) { final Control control; if (isHierarchical()){ control = tree.getControl(); }else{ control = table.getControl(); } control.setMenu(m); } protected Control getDndObject() { return (Control)tree.getControl(); } protected List<Object> cachedDndItems; @Override protected List<Object> getSwtDragData() { if (!isHierarchical) { throw new UnsupportedOperationException("dnd not implemented for xul tree in table mode."); } // if bound, return a list of bound objects, otherwise return strings. // note, all of these elements must be serializable. if (elements != null) { cachedDndItems = (List<Object>)getSelectedItems(); } else { IStructuredSelection selection = (IStructuredSelection) tree.getSelection(); List<Object> list = new ArrayList<Object>(); int i = 0; for (Object o : selection.toArray()) { list.add(((XulTreeItem)o).getRow().getCell(0).getLabel()); } cachedDndItems = list; } return cachedDndItems; } @Override protected void resolveDndParentAndIndex(DropEvent xulEvent) { if (!isHierarchical) { throw new UnsupportedOperationException("dnd not implemented for xul tree in table mode."); } TreeItem parent = null; int index = -1; DropTargetEvent event = (DropTargetEvent)xulEvent.getNativeEvent(); if (event.item != null) { TreeItem item = (TreeItem) event.item; Point pt = tree.getControl().getDisplay().map(null, tree.getControl(), event.x, event.y); Rectangle bounds = item.getBounds(); parent = item.getParentItem(); if (parent != null) { TreeItem[] items = parent.getItems(); index = 0; for (int i = 0; i < items.length; i++) { if (items[i] == item) { index = i; break; } } if (pt.y < bounds.y + bounds.height / 3) { // HANDLE parent, index } else if (pt.y > bounds.y + 2 * bounds.height / 3) { // HANDLE parent, index + 1 index++; } else { parent = item; index = 0; } } else { TreeItem[] items = tree.getTree().getItems(); index = 0; for (int i = 0; i < items.length; i++) { if (items[i] == item) { index = i; break; } } if (pt.y < bounds.y + bounds.height / 3) { // HANDLE null, index } else if (pt.y > bounds.y + 2 * bounds.height / 3) { index++; } else { // item is parent parent = item; index = 0; } } } else { // ASSUME END OF LIST, null, 0 } Object parentObj = null; if (parent != null) { if (elements != null) { // swt -> xul -> element SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), (XulTreeItem)parent.getData()); parentObj = b.selectedItem; } else { parentObj = parent.getText(); } } xulEvent.setDropParent(parentObj); xulEvent.setDropIndex(index); } @Override protected void onSwtDragDropAccepted(DropEvent xulEvent) { List results = xulEvent.getDataTransfer().getData(); if (elements != null) { // place the new elements in the new location Collection insertInto = elements; if (xulEvent.getDropParent() != null) { String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); insertInto = getChildCollection(xulEvent.getDropParent(), method); } if (insertInto instanceof List) { List list = (List)insertInto; if (xulEvent.getDropIndex() == -1) { for (Object o : results) { list.add(o); } } else { for (int i = results.size() - 1; i >= 0; i list.add(xulEvent.getDropIndex(), results.get(i)); } } } // todo, can i trigger this through another mechanism? setElements(elements); } else { // non-binding path // TODO: add necessary xul dom } } @Override protected void onSwtDragFinished(DragSourceEvent event, DropEffectType effect) { if (effect == DropEffectType.MOVE) { // ISelection sel = tree.getSelection(); if (elements != null) { // remove cachedDndItems from the tree.. traverse for (Object item : cachedDndItems) { removeItemFromElements(item); } cachedDndItems = null; setElements(elements); } else { tree.remove(tree.getSelection()); } } } protected void onSwtDragOver(DropTargetEvent event) { event.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL; if (event.item != null) { TreeItem item = (TreeItem) event.item; Point pt = tree.getControl().getDisplay().map(null, tree.getControl(), event.x, event.y); Rectangle bounds = item.getBounds(); if (pt.y < bounds.y + bounds.height / 3) { event.feedback |= DND.FEEDBACK_INSERT_BEFORE; } else if (pt.y > bounds.y + 2 * bounds.height / 3) { event.feedback |= DND.FEEDBACK_INSERT_AFTER; } else { event.feedback |= DND.FEEDBACK_SELECT; } } } public <T> void setSelectedItems(Collection<T> items) { int[] selIndexes= new int[items.size()]; if (this.isHierarchical && this.elements != null) { List<Object> selection = new ArrayList<Object>(); String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); for(T t : items){ FindBoundItemTuple tuple = new FindBoundItemTuple(t); findBoundItem(this.elements, this, property, tuple); selection.add(tuple.treeItem); } tree.setSelection(new StructuredSelection(selection)); } else { int pos = 0; for(T t : items){ selIndexes[pos++] = findIndexOfItem(t); } this.setSelectedRows(selIndexes); } } public int findIndexOfItem(Object o){ String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); property = "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); Method childrenMethod = null; try { childrenMethod = elements.getClass().getMethod(property, new Class[] {}); } catch (NoSuchMethodException e) { // Since this tree is built recursively, when at a leaf it will throw this exception. logger.debug(e); } FindSelectedIndexTuple tuple = findSelectedItem(this.elements, childrenMethod, new FindSelectedIndexTuple(o)); return tuple.selectedIndex; } private static class FindSelectedIndexTuple { Object selectedItem = null; Object currentItem = null; // ignores first element (root) int curpos = -1; // ignores first element (root) int selectedIndex = -1; public FindSelectedIndexTuple(Object selectedItem) { this.selectedItem = selectedItem; } } private FindSelectedIndexTuple findSelectedItem(Object parent, Method childrenMethod, FindSelectedIndexTuple tuple) { if (tuple.selectedItem == parent) { tuple.selectedIndex = tuple.curpos; return tuple; } Collection children = null; if(childrenMethod != null){ try { children = (Collection) childrenMethod.invoke(parent, new Object[] {}); } catch (Exception e) { logger.error(e); return tuple; } } else if(parent instanceof List){ children = (List) parent; } if (children == null || children.size() == 0) { return null; } for (Object child : children) { tuple.curpos++; findSelectedItem(child, childrenMethod, tuple); if (tuple.selectedIndex > -1) { return tuple; } } return tuple; } }
package com.jme.renderer.lwjgl; import java.nio.ByteBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; /** * <code>Font2D</code> maintains display lists for each ASCII character * defined by an image. <code>Font2D</code> assumes that the texture is * 256x256 and that the characters are 16 pixels high by 16 pixels wide. The * order of the characters is also important: <br> * * <img src ="fonttable.gif"> <br> * * After the font is loaded, it can be used with a call to <code>print</code>. * The <code>Font2D</code> class is also printed in Ortho mode and * billboarded, as well as depth buffering turned off. This means that the font * will be placed at a two dimensional coordinate that corresponds to screen * coordinates. * * The users is assumed to set a TextureState to the Text Geometry calling this * class. * * @see com.jme.scene.Text * @see com.jme.scene.state.TextureState * @author Mark Powell * @version $Id: LWJGLFont.java,v 1.17 2007-02-26 00:09:51 renanse Exp $ */ public class LWJGLFont { /** * Sets the style of the font to normal. */ public static final int NORMAL = 0; /** * Sets the style of the font to italics. */ public static final int ITALICS = 1; //display list offset. private int base; //buffer that holds the text. private ByteBuffer scratch; //Color to render the font. private ColorRGBA fontColor; /** * Constructor instantiates a new <code>LWJGLFont</code> object. The * initial color is set to white. * */ public LWJGLFont() { fontColor = new ColorRGBA(1, 1, 1, 1); scratch = BufferUtils.createByteBuffer(1); buildDisplayList(); } /** * <code>deleteFont</code> deletes the current display list of font * objects. The font will be useless until a call to * <code>buildDisplayLists</code> is made. */ public void deleteFont() { GL11.glDeleteLists(base, 256); } /** * <code>setColor</code> sets the RGBA values to render the font as. By * default the color is white with no transparency. * * @param color * the color to set. */ public void setColor(ColorRGBA color) { fontColor.set(color); } /** * <code>print</code> renders the specified string to a given (x,y) * location. The x, y location is in terms of screen coordinates. There are * currently two sets of fonts supported: NORMAL and ITALICS. * @param renderer * * @param x * the x screen location to start the string render. * @param y * the y screen location to start the string render. * @param text * the String to render. * @param set * the mode of font: NORMAL or ITALICS. */ public void print(LWJGLRenderer r, int x, int y, Vector3f scale, StringBuffer text, int set) { if (set > 1) { set = 1; } else if (set < 0) { set = 0; } boolean alreadyOrtho = r.isInOrthoMode(); if (!alreadyOrtho) r.setOrtho(); else { GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); } GL11.glTranslatef(x, y, 0); GL11.glScalef(scale.x, scale.y, scale.z); GL11.glListBase(base - 32 + (128 * set)); //Put the string into a "pointer" if (text.length() > scratch.capacity()) { scratch = BufferUtils.createByteBuffer(text.length()); } else { scratch.clear(); } int charLen = text.length(); for (int z = 0; z < charLen; z++) scratch.put((byte) text.charAt(z)); scratch.flip(); GL11.glColor4f(fontColor.r, fontColor.g, fontColor.b, fontColor.a); //call the list for each letter in the string. GL11.glCallLists(scratch); //set color back to white GL11.glColor4f(1,1,1,1); if (!alreadyOrtho) { r.unsetOrtho(); } else { GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPopMatrix(); } } /** * <code>buildDisplayList</code> sets up the 256 display lists that are * used to render each font character. Each list quad is 16x16, as defined * by the font image size. */ public void buildDisplayList() { float cx; float cy; base = GL11.glGenLists(256); for (int loop = 0; loop < 256; loop++) { cx = (loop % 16) / 16.0f; cy = (loop / 16) / 16.0f; GL11.glNewList(base + loop, GL11.GL_COMPILE); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(cx, 1 - cy - 0.0625f); GL11.glVertex2i(0, 0); GL11.glTexCoord2f(cx + 0.0625f, 1 - cy - 0.0625f); GL11.glVertex2i(16, 0); GL11.glTexCoord2f(cx + 0.0625f, 1 - cy); GL11.glVertex2i(16, 16); GL11.glTexCoord2f(cx, 1 - cy); GL11.glVertex2i(0, 16); GL11.glEnd(); GL11.glTranslatef(10, 0, 0); GL11.glEndList(); } } /** * <code>toString</code> returns the string representation of this font * object in the Format: <br> * <br> * jme.geometry.hud.text.Font2D@1c282a1 <br> * Color: {RGBA COLOR} <br> * * @return the string representation of this object. */ public String toString() { String string = super.toString(); string += "\nColor: " + fontColor.toString(); return string; } }
package com.jme.sound; /** * @author Arman Ozcelik * */ public class SoundAPIController { private static String api; private static ISoundSystem soundSystem = null; private static ISoundRenderer renderer = null; public SoundAPIController() {} public static ISoundSystem getSoundSystem(String apiName) { api= apiName; if (api.equals("LWJGL")) { soundSystem= new com.jme.sound.lwjgl.SoundSystem(); renderer= new com.jme.sound.lwjgl.SoundRenderer(); } if (api.equals("JOAL")) { soundSystem= new com.jme.sound.joal.SoundSystem(); renderer= new com.jme.sound.joal.SoundRenderer(); } return soundSystem; } public static ISoundRenderer getRenderer() { if (renderer == null) throw new IllegalArgumentException("Must first call getSoundSystem(String) to specify the sound API!"); return renderer; } public static ISoundSystem getSoundSystem() { if (renderer == null) throw new IllegalArgumentException("Must first call getSoundSystem(String) to specify the sound API!"); return soundSystem; } public static void plugExternal(ISoundSystem externalAPI, ISoundRenderer externalRenderer) { if (externalAPI != null) { soundSystem= externalAPI; renderer= externalRenderer; api= soundSystem.getAPIName(); } } }
package com.jme.sound.openAL; import java.util.logging.Level; import org.lwjgl.openal.AL; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.sound.openAL.objects.Listener; import com.jme.sound.openAL.objects.MusicStream; import com.jme.sound.openAL.objects.Sample3D; import com.jme.sound.openAL.scene.Configuration; import com.jme.sound.openAL.scene.SoundNode; import com.jme.util.LoggingSystem; public class SoundSystem { private static Listener listener; private static Camera camera; public static final int OUTPUT_DEFAULT=0; //WINDOZE public static final int OUTPUT_DSOUND =1; public static final int OUTPUT_WINMM =2; public static final int OUTPUT_ASIO =3; //LINUZ public static final int OUTPUT_OSS =5; public static final int OUTPUT_ESD =6; public static final int OUTPUT_ALSA =7; //MAC public static final int OUTPUT_MAC = 8; private static int OS_DETECTED; private static final int OS_LINUX=1; private static final int OS_WINDOWS=2; private static final int OS_MAC = 3; private static SoundNode[] nodes; private static Sample3D[] sample3D; private static MusicStream[] stream; static{ LoggingSystem.getLogger().log(Level.INFO,"DETECT OPERATING SYSTEM"); detectOS(); LoggingSystem.getLogger().log(Level.INFO,"CREATE OPENAL"); initializeOpenAL(); LoggingSystem.getLogger().log(Level.INFO,"CREATE LISTENER"); listener=new Listener(); } private static void initializeOpenAL() { try { AL.create(); LoggingSystem.getLogger().log(Level.INFO, "OpenAL initalized!"); } catch (Exception e) { LoggingSystem.getLogger().log(Level.SEVERE, "Failed to Initialize OpenAL..."); e.printStackTrace(); } } private static void detectOS() { String osName=System.getProperty("os.name"); osName=osName.toUpperCase(); if(osName.startsWith("LINUX")) OS_DETECTED=OS_LINUX; if(osName.startsWith("WINDOWS")) OS_DETECTED=OS_WINDOWS; if(osName.startsWith("MAC")) OS_DETECTED=OS_MAC; } /** * init the sound system by setting it's listener's position to the cameras position * * @param cam * @param outputMethod */ public static void init(Camera cam, int outputMethod){ camera=cam; if(outputMethod==OUTPUT_DEFAULT){ outputMethod=OS_DETECTED; } switch(outputMethod){ case OS_LINUX : break; case OS_WINDOWS : break; case OS_MAC : break; } } private static void updateListener(){ if(camera !=null){ listener.setPosition(camera.getLocation()); } float[] orientation = listener.getOrientation(); Vector3f dir=null; Vector3f up=null; if(camera !=null){ dir = camera.getDirection(); up = camera.getUp(); }else if(dir==null){ dir=new Vector3f(0, 0, -1); up=new Vector3f(0, 1, 0); } orientation[0] = -dir.x; orientation[1] = dir.y; orientation[2] = dir.z; orientation[3] = up.x; orientation[4] = up.y; orientation[5] = up.z; listener.update(); } /** * Updates the geometric states of all nodes in the scene * @param time currently not used */ public static void update(float time){ if(nodes==null) return; for(int a=0; a<nodes.length; a++){ nodes[a].updateWorldData(time); } updateListener(); } /** * Updates the geometric states of the given node in the scene * @param nodeName the node to update * @param time currently not used */ public static void update(int nodeName, float time){ if(nodes==null) return; if(nodeName<0 || nodeName>=nodes.length) return; nodes[nodeName].updateWorldData(time); updateListener(); } /** * Draws all nodes in the scene * @param time currently not used */ public static void draw(){ if(nodes==null) return; for(int a=0; a<nodes.length; a++){ nodes[a].draw(); } } /** * Draws the given node in the scene * @param nodeName the node to update * @param time currently not used */ public static void draw(int nodeName){ if(nodes==null) return; if(nodeName<0 || nodeName>=nodes.length) return; nodes[nodeName].draw(); } /** * Creates a node ans return an integer as it's identifier. * @return the node identifier */ public static int createSoundNode(){ if(nodes==null){ nodes=new SoundNode[1]; nodes[0]=new SoundNode(); return 0; }else{ SoundNode[] tmp=new SoundNode[nodes.length]; System.arraycopy(nodes, 0, tmp, 0, tmp.length); nodes=new SoundNode[tmp.length+1]; System.arraycopy(tmp, 0, nodes, 0, tmp.length); nodes[tmp.length]=new SoundNode(); return tmp.length; } } /** * Creates a 3D sample and returns an identifier for it * @param file the sample file name * @return the 3D sample identifier */ public static int create3DSample(String file){ if(sample3D==null){ sample3D=new Sample3D[1]; sample3D[0]=new Sample3D(listener, file); return 0; }else{ Sample3D[] tmp=new Sample3D[sample3D.length]; System.arraycopy(sample3D, 0, tmp, 0, tmp.length); sample3D=new Sample3D[tmp.length+1]; System.arraycopy(tmp, 0, sample3D, 0, tmp.length); sample3D[tmp.length]=new Sample3D(listener, file); return tmp.length; } } /** * Creates a Music stream and returns an identifier for it * @param file streaming file name * @param loadIntoMemory * @return the stream identifier */ public static int createStream(String file, boolean loadIntoMemory){ if(stream==null){ stream=new MusicStream[1]; stream[0]=new MusicStream(file, loadIntoMemory); return 0; }else{ MusicStream[] tmp=new MusicStream[stream.length]; System.arraycopy(stream, 0, tmp, 0, tmp.length); stream=new MusicStream[tmp.length+1]; System.arraycopy(tmp, 0, stream, 0, tmp.length); stream[tmp.length]=new MusicStream(file, loadIntoMemory); return tmp.length; } } /** * Checks if a stream is opened. If it is, this can be used to know * that the file is really a audio file * @param streamName * @return true if the stream is opened */ public static boolean isStreamOpened(int streamName){ if(stream==null){ return false; }else if(streamName<0 || streamName>=stream.length){ return false; }else{ return stream[streamName].isOpened(); } } /** * Get the length of the given stream in milliseconds * @param streamName * @return the stream length in millis */ public static int getStreamLength(int streamName){ if(stream==null){ return -1; }else if(streamName<0 || streamName>=stream.length){ return -1; }else{ return stream[streamName].length(); } } public static boolean playStream(int streamName){ if(stream==null){ return false; }else if(streamName<0 || streamName>=stream.length){ return false; }else{ return stream[streamName].play(); } } public static boolean pauseStream(int streamName){ if(stream==null){ return false; }else if(streamName<0 || streamName>=stream.length){ return false; }else{ return stream[streamName].pause(); } } public static void stopStream(int streamName){ if(stream==null){ return ; }else if(streamName<0 || streamName>=stream.length){ return ; }else{ stream[streamName].stop(); } } /** * Sets the spatial position of a given sample * @param sample the sample identifier * @param x the x position of the sample * @param y the y position of the sample * @param z the z position of the sample */ public static void setSamplePosition(int sample, float x, float y, float z){ if(sample3D==null){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ sample3D[sample].setPosition(x, y, z); } } /** * Sets the velocity of a given sample * @param sample the sample identifier * @param x the x velocity of the sample * @param y the y velocity of the sample * @param z the z velocity of the sample */ public static void setSampleVelocity(int sample, float x, float y, float z){ if(sample3D==null){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ sample3D[sample].setVelocity(x, y, z); } } /** * Set the FX configuration of the given sample * @param sample sample the sample identifier * @param conf the config */ public static void setSampleConfig(int sample, Configuration conf){ if(sample3D==null){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ sample3D[sample].setConfiguration(conf); } } /** * Set the FX configuration of the given stream * @param sample stream the sample identifier * @param conf the config */ public static void setStreamConfig(int streamName, Configuration conf){ if(stream==null){ return; }else if(streamName<0 || streamName>=stream.length){ return; }else{ stream[streamName].setConfiguration(conf); } } /** * Sets the units from which the sample will stop playing * @param sample the sample identifier * @param dist the distance unit from which the sample will stop playing */ public static void setSampleMaxAudibleDistance(int sample, int dist){ if(sample3D==null){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ sample3D[sample].setMaxAudibleDistance(dist); } } public static void setSampleMinAudibleDistance(int sample, int dist){ if(sample3D==null){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ sample3D[sample].setMinDistance(dist); } } /** * Adds a sample to the given node identifier * @param destNode * @param sample */ public static void addSampleToNode(int sample, int destNode){ if(nodes==null){ return; }else if(sample3D==null){ return; }else if(destNode<0 || destNode>=nodes.length){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ nodes[destNode].attachChild(sample3D[sample]); } } public static void setRolloffFactor(float rolloff){ } /** * Set the volume of the given sample * @param sample * @param volume */ public static void setSampleVolume(int sample, float volume){ if(sample3D==null){ return; }else if(sample<0 || sample>=sample3D.length){ return; }else{ sample3D[sample].setVolume(volume); } } }
package com.michaldabski.utils; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Locale; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Environment; import android.webkit.MimeTypeMap; import com.michaldabski.fileexplorer.R; public class FileUtils { @SuppressLint("SdCardPath") private static final String SDCARD_DISPLAY_NAME = "/sdcard"; private static final double FILE_APP_ICON_SCALE = 0.2; public final static int KILOBYTE = 1024, MEGABYTE = KILOBYTE * 1024, GIGABYTE = MEGABYTE * 1024, MAX_BYTE_SIZE = KILOBYTE / 2, MAX_KILOBYTE_SIZE = MEGABYTE / 2, MAX_MEGABYTE_SIZE = GIGABYTE / 2; public static final String MIME_TYPE_ANY = "*/*"; public static final FileFilter DEFAULT_FILE_FILTER = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isHidden() == false; } }; /** * Compares files by name, where directories come always first */ public static class FileNameComparator implements Comparator<File> { protected final static int FIRST = -1, SECOND = 1; @Override public int compare(File lhs, File rhs) { if (lhs.isDirectory() || rhs.isDirectory()) { if (lhs.isDirectory() == rhs.isDirectory()) return lhs.getName().compareToIgnoreCase(rhs.getName()); else if (lhs.isDirectory()) return FIRST; else return SECOND; } return lhs.getName().compareToIgnoreCase(rhs.getName()); } } /** * Compares files by extension. * Falls back to sort by name if extensions are the same or one of the objects is a Directory * @author Michal * */ public static class FileExtensionComparator extends FileNameComparator { @Override public int compare(File lhs, File rhs) { if (lhs.isDirectory() || rhs.isDirectory()) return super.compare(lhs, rhs); String ext1 = getFileExtension(lhs), ext2 = getFileExtension(rhs); if (ext1.equals(ext2)) return super.compare(lhs, rhs); else return ext1.compareToIgnoreCase(ext2); } } public static class FileSizeComparator extends FileNameComparator { private final boolean ascending = false; @Override public int compare(File lhs, File rhs) { if (lhs.isDirectory() || rhs.isDirectory()) return super.compare(lhs, rhs); if (lhs.length() > rhs.length()) return ascending ? SECOND : FIRST; else if (lhs.length() < rhs.length()) return ascending ? FIRST : SECOND; else return super.compare(lhs, rhs); } } public static String formatFileSize(File file) { return formatFileSize(file.length()); } public static String formatFileSize(long size) { if (size < MAX_BYTE_SIZE) return String.format(Locale.ENGLISH, "%d bytes", size); else if (size < MAX_KILOBYTE_SIZE) return String.format(Locale.ENGLISH, "%.2f kb", (float)size / KILOBYTE); else if (size < MAX_MEGABYTE_SIZE) return String.format(Locale.ENGLISH, "%.2f mb", (float)size / MEGABYTE); else return String.format(Locale.ENGLISH, "%.2f gb", (float)size / GIGABYTE); } public static String getFileExtension(File file) { return getFileExtension(file.getName()); } /** * Gets extension of the file name excluding the . character */ public static String getFileExtension(String fileName) { if (fileName.contains(".")) return fileName.substring(fileName.lastIndexOf('.')+1); else return ""; } public static String getFileMimeType(File file) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtension(file)); } public static int getNumFilesInFolder(File folder) { if (folder.isDirectory() == false) return 0; File [] files = folder.listFiles(DEFAULT_FILE_FILTER); if (files == null) return 0; return files.length; } /** * Attempts to get common mime type for a collection of assorted files */ public static String getCollectiveMimeType(Collection<File> files) { String typeStart=null; String type=null; for (File file : files) if (file.isDirectory() == false) { String thisType = getFileMimeType(file); if (thisType == null) continue; if (type == null) { type = thisType; try { typeStart = thisType.substring(0, thisType.indexOf('/')); } catch(Exception e) { return MIME_TYPE_ANY; } } else if (type.equalsIgnoreCase(thisType)) continue; else if (thisType.startsWith(typeStart)) type = typeStart + "*"; else return MIME_TYPE_ANY; } if (type == null) return MIME_TYPE_ANY; return type; } public static StringBuilder combineFileNames(Collection<File> files) { StringBuilder fileNamesStringBuilder = new StringBuilder(); boolean first=true; for (File file : files) { if (first == false) fileNamesStringBuilder.append(", "); fileNamesStringBuilder.append(file.getName()); first=false; } return fileNamesStringBuilder; } public static void flattenDirectory(File directory, List<File> result) { if (directory.isDirectory()) { for (File file : directory.listFiles(DEFAULT_FILE_FILTER)) { if (file.isDirectory()) flattenDirectory(file, result); else result.add(file); } } else result.add(directory); } public static void validateCopyMoveDirectory(File file, File toFolder) throws IOException { if (toFolder.equals(file)) throw new IOException("Folder cannot be copied to itself"); else if (toFolder.equals(file.getParentFile())) throw new IOException("Source and target directory are the same"); else if (toFolder.getAbsolutePath().startsWith(file.getAbsolutePath())) throw new IOException("Folder cannot be copied to its child folder"); } public static void copyFile(File src, File dst) throws IOException { if (src.isDirectory()) throw new IOException("Source is a directory"); InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } public static void deleteEmptyFolders(Collection<File> directories) { for (File file : directories) if (file.isDirectory()) { deleteFiles(Arrays.asList(file.listFiles())); file.delete(); } } public static int deleteFiles(Collection<File> files) { int n=0; for (File file : files) { if (file.isDirectory()) { n += deleteFiles(Arrays.asList(file.listFiles())); } if (file.delete()) n++; } return n; } /** * gets icon for this file type */ public static int getFileIconResource(File file) { if (file.isDirectory()) { if (file.equals(Environment.getExternalStorageDirectory())) return R.drawable.icon_sdcard; else if (file.equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))) return R.drawable.icon_pictures; else if (file.equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))) return R.drawable.icon_downloads; else if (file.equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES))) return R.drawable.icon_movies; else if (file.equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))) return R.drawable.icon_music; else if (file.equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))) return R.drawable.icon_pictures; return R.drawable.icon_folder; } else { return R.drawable.icon_file; } } public static Bitmap createFileIcon(File file, Context context, boolean homescreen) { final Bitmap bitmap; final Canvas canvas; if (file.isDirectory()) { // load Folder bitmap Bitmap folderBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_home_folder); bitmap = Bitmap.createBitmap(folderBitmap.getWidth(), folderBitmap.getHeight(), Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); canvas.drawBitmap(folderBitmap, 0, 0, null); } else { Bitmap folderBitmap = BitmapFactory.decodeResource(context.getResources(), homescreen?R.drawable.icon_home_file:R.drawable.icon_file); bitmap = Bitmap.createBitmap(folderBitmap.getWidth(), folderBitmap.getHeight(), Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); canvas.drawBitmap(folderBitmap, 0, 0, null); Drawable appIcon = IntentUtils.getAppIconForFile(file, context); if (appIcon != null) { Rect bounds = canvas.getClipBounds(); int shrinkage = (int)(bounds.width() * FILE_APP_ICON_SCALE); bounds.left += shrinkage; bounds.right -= shrinkage; bounds.top += shrinkage * 1.5; bounds.bottom -= shrinkage * 0.5; appIcon.setBounds(bounds); appIcon.draw(canvas); } } // add shortcut symbol if (homescreen) canvas.drawBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.shortcut), 0, 0, null); return bitmap; } public static int countFilesIn(Collection<File> roots) { int result=0; for (File file : roots) result += countFilesIn(file); return result; } public static int countFilesIn(File root) { if (root.isDirectory() == false) return 1; File[] files = root.listFiles(DEFAULT_FILE_FILTER); if (files == null) return 0; int n = 0; for (File file : files) { if (file.isDirectory()) n += countFilesIn(file); else n ++; } return n; } public static String getUserFriendlySdcardPath(File file) { String path; try { path = file.getCanonicalPath(); } catch (IOException e) { path = file.getAbsolutePath(); } return path .replace(Environment.getExternalStorageDirectory().getAbsolutePath(), SDCARD_DISPLAY_NAME); } public static boolean isMediaDirectory(File file) { try { String path = file.getCanonicalPath(); for (String directory : new String[]{Environment.DIRECTORY_DCIM, Environment.DIRECTORY_MOVIES, Environment.DIRECTORY_PICTURES, Environment.DIRECTORY_MUSIC}) { if (path.startsWith(Environment.getExternalStoragePublicDirectory(directory) .getAbsolutePath())) return true; } return false; } catch (IOException e) { e.printStackTrace(); return false; } } }
package com.rabenauge.parandroid; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.rabenauge.demo.*; import com.rabenauge.gl.*; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; public class Credits extends EffectManager { private Texture2D[] textures; private class Cubes extends Effect { private long WAIT=5000; private long startTime; private int effectState=0; public void onStart(GL11 gl) { cubeVertexBfr = new FloatBuffer[6]; cubeTextureBfr = new FloatBuffer[6]; for (int i = 0; i < 6; i++) { cubeVertexBfr[i] = FloatBuffer.wrap(cubeVertexCoords[i]); cubeTextureBfr[i] = FloatBuffer.wrap(cubeTextureCoords[i]); } gl.glShadeModel(GL10.GL_SMOOTH); gl.glClearColor(0, 0, 0, 0); gl.glClearDepthf(1.0f); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glDepthFunc(GL10.GL_LEQUAL); gl.glEnable(GL10.GL_CULL_FACE); gl.glCullFace(GL10.GL_BACK); gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); startTime=System.currentTimeMillis(); } private final static int MAX_X=5; private final static int MAX_Y=3; private float[][] cubeVertexCoords = new float[][] { new float[] { // top 1, 1,-1, -1, 1,-1, -1, 1, 1, 1, 1, 1 }, new float[] { // bottom 1,-1, 1, -1,-1, 1, -1,-1,-1, 1,-1,-1 }, new float[] { // front 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1 }, new float[] { // back 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 }, new float[] { // left -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1 }, new float[] { // right 1, 1,-1, 1, 1, 1, 1,-1, 1, 1,-1,-1 }, }; private float[][] cubeTextureCoords = new float[6][8]; private FloatBuffer[] cubeVertexBfr; private FloatBuffer[] cubeTextureBfr; private float cubeRotX; private float cubeRotY; private float cubeRotZ; private float ypos; private float xpos; @Override public void onRender(GL11 gl, long t, long e, float s) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); xpos=-6f; // draw the cubes for(int x=0;x<MAX_X;x++) { xpos+=2f; ypos=-4f; for(int y=0;y<MAX_Y;y++) { gl.glLoadIdentity(); ypos+=2f; setCubeSpace(gl,x, y); //gl.glTranslatef(xpos, ypos, -8); gl.glRotatef(cubeRotX, 1, 0, 0); gl.glRotatef(cubeRotY, 0, 1, 0); gl.glRotatef(cubeRotZ, 0, 0, 1); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); for (int i = 0; i < 6; i++) // draw each face { switch (i) { case 0: textures[1].makeCurrent(); break; // top case 1: textures[3].makeCurrent(); break; // bottom case 2: textures[0].makeCurrent(); break; // front case 3: textures[2].makeCurrent(); break; // back } setTextureCoords(0,x, y); cubeTextureBfr[i] = FloatBuffer.wrap(cubeTextureCoords[0]); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, cubeVertexBfr[i]); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, cubeTextureBfr[i]); gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, 4); } gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } } if(System.currentTimeMillis()-startTime>WAIT&&effectState==0) { effectState=1; } if(effectState==1) { cubeRotX += 1.0f; if(cubeRotX%90==0) { effectState=3; startTime=System.currentTimeMillis(); } } } float xspace=0; float yspace=0; private void setCubeSpace(GL11 gl,int x, int y) { float xpos2=0; float ypos2=0; if(effectState==0) { xspace=0; yspace=0; } if(effectState==1) { xspace-=0.001f; yspace-=0.0015f; //if(xspace<=-0.8f) // x space // effectState=2; } if(effectState==3) { xspace+=0.001f; yspace+=0.0015f; if(xspace>=0.0f) effectState=0; } switch(x) { case 0: xpos2=xpos+(xspace*2); break; case 1: xpos2=xpos+xspace; break; case 3: xpos2=xpos+(xspace*-1); break; case 4: xpos2=xpos+(xspace*-1*2); break; } switch(y) { case 0: ypos2=ypos+yspace; break; case 2: ypos2=ypos-yspace; break; } // if(effectState==2) // cubeRotX += 1.0f; // if(cubeRotX%90==0) // effectState=3; // startTime=System.currentTimeMillis(); gl.glTranslatef(xpos2, ypos2, -8); } private void setTextureCoords (int i,int x,int y) // TODO remove i { float y2=2; y2=y2-y; float W=1024; // TODO why does it work ? float H=512; // TODO why does it work ? float xOL=(W/MAX_X)*x; float xOR=(W/MAX_X)*(x+1); float yO=(H/MAX_Y)*y2; float yU=(H/MAX_Y)*(y2+1); cubeTextureCoords[i][0]=(xOR)/W; cubeTextureCoords[i][1]=(yO)/H ; cubeTextureCoords[i][2]=(xOL)/W; cubeTextureCoords[i][3]=(yO)/H; cubeTextureCoords[i][4]=(xOL)/W ; cubeTextureCoords[i][5]=(yU)/H; cubeTextureCoords[i][6]=(xOR)/W; cubeTextureCoords[i][7]=(yU)/H; } } public Credits(Demo demo, GL11 gl) { super(gl); // Load the end screens. int[] ids={R.drawable.credits_names, R.drawable.credits_rab, R.drawable.credits_trsi, R.drawable.credits_final}; textures=new Texture2D[ids.length]; for (int i=0; i<ids.length; ++i) { Bitmap bitmap=BitmapFactory.decodeResource(demo.getActivity().getResources(), ids[i]); textures[i]=new Texture2D(gl); textures[i].setData(bitmap); bitmap.recycle(); } // Schedule the effects in this part. add(new Cubes(), 160*1000); } }
package com.sproutlife.panel; import java.awt.Component; import java.awt.Dimension; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; public class GameToolbar extends JPanel { PanelController panelController; private JSlider zoomSlider; private JButton startPauseButton; private JSlider speedSlider; private Component horizontalStrut; private Component horizontalStrut_1; private JButton stepButton; private JButton resetButton; private JButton reloadButton; private JButton gifStopRecordingButton; public GameToolbar(PanelController panelController) { setMinimumSize(new Dimension(220, 0)); this.panelController = panelController; buildPanel(); } /** * Create the panel. */ public void buildPanel() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); horizontalStrut = Box.createHorizontalStrut(20); add(horizontalStrut); JLabel lblZoom = new JLabel("Zoom"); add(lblZoom); zoomSlider = new JSlider(); zoomSlider.setPreferredSize(new Dimension(100, 29)); add(zoomSlider); zoomSlider.setMinorTickSpacing(1); zoomSlider.setMinimum(-5); zoomSlider.setValue(-2); zoomSlider.setMaximum(5); JLabel speedLabel = new JLabel("Speed"); add(speedLabel); speedSlider = new JSlider(); speedSlider.setPreferredSize(new Dimension(100, 29)); speedSlider.setSnapToTicks(true); add(speedSlider); speedSlider.setMinimum(-5); speedSlider.setMaximum(4); speedSlider.setValue(-2); gifStopRecordingButton = new JButton("GIF - Stop Rec."); gifStopRecordingButton.setVisible(false); add(gifStopRecordingButton); startPauseButton = new JButton("Start"); add(startPauseButton); startPauseButton.setMaximumSize(new Dimension(200, 23)); startPauseButton.setPreferredSize(new Dimension(80, 29)); stepButton = new JButton("Step"); stepButton.setPreferredSize(new Dimension(80, 29)); add(stepButton); reloadButton = new JButton("Reload"); reloadButton.setPreferredSize(new Dimension(80, 29)); add(reloadButton); resetButton = new JButton("Reset"); resetButton.setPreferredSize(new Dimension(80, 29)); add(resetButton); horizontalStrut_1 = Box.createHorizontalStrut(20); add(horizontalStrut_1); } public int getInt(String s) { return panelController.getGameController().getSettings().getInt(s); } public JSlider getZoomSlider() { return zoomSlider; } public JButton getStartPauseButton() { return startPauseButton; } public JSlider getSpeedSlider() { return speedSlider; } public JButton getStepButton() { return stepButton; } public JButton getResetButton() { return resetButton; } public JButton getReloadButton() { return reloadButton; } public JButton getGifStopRecordingButton() { return gifStopRecordingButton; } }
package com.techjar.ledcm; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import static org.lwjgl.opengl.GL13.*; import static org.lwjgl.opengl.GL14.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; import static org.lwjgl.opengl.GL31.*; import static org.lwjgl.opengl.GL32.*; import static org.lwjgl.opengl.GL33.*; import static org.lwjgl.opengl.GL40.*; import static org.lwjgl.util.glu.GLU.*; import com.hackoeur.jglm.Mat3; import com.hackoeur.jglm.Mat4; import com.hackoeur.jglm.Matrices; import com.obj.WavefrontObject; import com.techjar.ledcm.gui.GUICallback; import com.techjar.ledcm.gui.screen.Screen; import com.techjar.ledcm.gui.screen.ScreenMainControl; import com.techjar.ledcm.hardware.LEDManager; import com.techjar.ledcm.hardware.ArduinoLEDManager; import com.techjar.ledcm.hardware.CommThread; import com.techjar.ledcm.hardware.LEDUtil; import com.techjar.ledcm.hardware.SpectrumAnalyzer; import com.techjar.ledcm.hardware.TLC5940LEDManager; import com.techjar.ledcm.hardware.TestHugeLEDManager; import com.techjar.ledcm.hardware.animation.*; import com.techjar.ledcm.hardware.tcp.TCPServer; import com.techjar.ledcm.hardware.tcp.packet.Packet; import com.techjar.ledcm.util.Angle; import com.techjar.ledcm.util.ArgumentParser; import com.techjar.ledcm.util.Axis; import com.techjar.ledcm.util.AxisAlignedBB; import com.techjar.ledcm.util.ConfigManager; import com.techjar.ledcm.util.Constants; import com.techjar.ledcm.util.Dimension3D; import com.techjar.ledcm.util.Direction; import com.techjar.ledcm.util.LEDCubeOctreeNode; import com.techjar.ledcm.util.LightSource; import com.techjar.ledcm.util.MathHelper; import com.techjar.ledcm.util.Model; import com.techjar.ledcm.util.ModelMesh; import com.techjar.ledcm.util.OperatingSystem; import com.techjar.ledcm.util.Quaternion; import com.techjar.ledcm.util.ShaderProgram; import com.techjar.ledcm.util.Util; import com.techjar.ledcm.util.Vector2; import com.techjar.ledcm.util.Vector3; import com.techjar.ledcm.util.logging.LogHelper; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Frame; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.MemoryCacheImageOutputStream; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.UIManager; import javax.swing.filechooser.FileNameExtensionFilter; import lombok.Getter; import lombok.Setter; import lombok.SneakyThrows; import lombok.Value; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; import org.lwjgl.Sys; import org.lwjgl.input.Controller; import org.lwjgl.input.Controllers; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.Pbuffer; import org.lwjgl.opengl.PixelFormat; import org.lwjgl.util.Color; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import org.newdawn.slick.UnicodeFont; /** * * @author Techjar */ public class LEDCubeManager { //public static final int SCREEN_WIDTH = 1024; //public static final int SCREEN_HEIGHT = 768; @Getter private static LEDCubeManager instance; @Getter private static DisplayMode displayMode /*= new DisplayMode(1024, 768)*/; private DisplayMode newDisplayMode; private DisplayMode configDisplayMode; private boolean fullscreen; private boolean newFullscreen; @Getter private static ConfigManager config; @Getter private static JFrame frame; @Getter private List<DisplayMode> displayModeList; private Canvas canvas; private boolean closeRequested = false; private boolean running = false; @Getter private static TextureManager textureManager; @Getter private static ModelManager modelManager; @Getter private static FontManager fontManager; @Getter private static SoundManager soundManager; @Getter private static Camera camera; @Getter private static Frustum frustum; @Getter private static JFileChooser fileChooser; @Getter private static String serialPortName = "COM3"; @Getter private static int serverPort = 7545; @Getter private static ControlUtil controlServer; @Getter private static FrameServer frameServer; @Getter private static SystemTray systemTray; @Getter @Setter private static boolean convertingAudio; private static LEDCube ledCube; private List<Screen> screenList = new ArrayList<>(); private List<ScreenHolder> screensToAdd = new ArrayList<>(); private List<GUICallback> resizeHandlers = new ArrayList<>(); private Map<String, Integer> validControllers = new HashMap<>(); private Queue<Packet> packetProcessQueue = new ConcurrentLinkedQueue<>(); private FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(4); private FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16); private int fpsCounter; private int fpsRender; private long timeCounter; private long deltaTime; private long renderStart; private long faceCount; private boolean screenshot; private boolean regrab; public boolean renderFPS; public boolean debugMode; public boolean wireframe; public final boolean antiAliasingSupported; public final int antiAliasingMaxSamples; @Getter private boolean antiAliasing = true; @Getter private int antiAliasingSamples = 4; private float fieldOfView; private float viewDistance; private int multisampleFBO; private int multisampleTexture; private int multisampleDepthTexture; private int shadowMapSize = 1024; private int depthFBO; private int depthTexture; // Screens @Getter private ScreenMainControl screenMainControl; // Really import OpenGL matrix stuff private Mat4 projectionMatrix; private Matrix4f viewMatrix; public Matrix4f modelMatrix; @Getter private LightingHandler lightingHandler; private ShaderProgram spMain; private ShaderProgram spDepthDraw; // TODO public LEDCubeManager(String[] args) throws LWJGLException { instance = this; System.setProperty("sun.java2d.noddraw", "true"); LogHelper.init(new File(Constants.DATA_DIRECTORY, "logs")); LongSleeperThread.startSleeper(); ArgumentParser.parse(args, new ArgumentParser.Argument(true, "--loglevel") { @Override public void runAction(String parameter) { LogHelper.setLevel(Level.parse(parameter)); } }, new ArgumentParser.Argument(false, "--showfps") { @Override public void runAction(String parameter) { renderFPS = true; } }, new ArgumentParser.Argument(false, "--debug") { @Override public void runAction(String parameter) { debugMode = true; } }, new ArgumentParser.Argument(false, "--wireframe") { @Override public void runAction(String parameter) { wireframe = true; } }, new ArgumentParser.Argument(true, "--serialport") { @Override public void runAction(String parameter) { serialPortName = parameter; } }, new ArgumentParser.Argument(true, "--serverport") { @Override public void runAction(String parameter) { serverPort = Integer.parseInt(parameter); } }); Pbuffer pb = new Pbuffer(800, 600, new PixelFormat(32, 0, 24, 8, 0), null); pb.makeCurrent(); antiAliasingMaxSamples = glGetInteger(GL_MAX_SAMPLES); antiAliasingSupported = antiAliasingMaxSamples > 0; pb.destroy(); LogHelper.config("AA Supported: %s / Max Samples: %d", antiAliasingSupported ? "yes" : "no", antiAliasingMaxSamples); } public void start() throws LWJGLException, IOException, AWTException { if (running) throw new IllegalStateException("Client already running!"); running = true; Runtime.getRuntime().addShutdownHook(new ShutdownThread()); initDisplayModes(); initConfig(); File musicDir = new File("resampled"); if (!musicDir.exists()) musicDir.mkdirs(); Display.setDisplayMode(displayMode); makeFrame(); setupSystemTray(); Display.create(); Keyboard.create(); Mouse.create(); Controllers.create(); String defaultController = ""; for (int i = 0; i < Controllers.getControllerCount(); i++) { Controller con = Controllers.getController(i); if (con.getAxisCount() >= 2) { validControllers.put(con.getName(), i); config.defaultProperty("controls.controller", con.getName()); if (defaultController.isEmpty()) defaultController = con.getName(); LogHelper.config("Found controller: %s (%d Rumblers)", con.getName(), con.getRumblerCount()); } } if (validControllers.size() < 1) config.setProperty("controls.controller", ""); else if (!validControllers.containsKey(config.getString("controls.controller"))) config.setProperty("controls.controller", defaultController); if (config.hasChanged()) config.save(); textureManager = new TextureManager(); modelManager = new ModelManager(textureManager); fontManager = new FontManager(); soundManager = new SoundManager(); lightingHandler = new LightingHandler(); camera = new Camera(); frustum = new Frustum(); fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter("Audio Files (*.wav, *.mp3, *.ogg, *.flac)", "wav", "mp3", "ogg", "flac")); fileChooser.setMultiSelectionEnabled(false); if (OperatingSystem.isWindows() && new File(System.getProperty("user.home"), "Music").exists()) fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"), "Music")); init(); InstancedRenderer.init(); LightSource light = new LightSource(); light.position = new Vector4f(0, 0, 0, 1); lightingHandler.addLight(light); ledCube = new LEDCube(); ledCube.postInit(); frameServer = new FrameServer(); timeCounter = getTime(); deltaTime = System.nanoTime(); screenList.add(screenMainControl = new ScreenMainControl()); ledCube.loadAnimations(); run(); } public static LEDCube getLEDCube() { return ledCube; } /** * * @return * @deprecated Get the LEDManager from the LEDCube instance. */ @Deprecated public static LEDManager getLEDManager() { return ledCube.getLEDManager(); } private void makeFrame() throws LWJGLException { if (frame != null) frame.dispose(); frame = new JFrame(Constants.APP_TITLE); frame.setLayout(new BorderLayout()); frame.setResizable(false); frame.setAlwaysOnTop(false); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); List<Image> images = new ArrayList<>(); images.add(Toolkit.getDefaultToolkit().getImage("resources/textures/icon16.png")); images.add(Toolkit.getDefaultToolkit().getImage("resources/textures/icon32.png")); images.add(Toolkit.getDefaultToolkit().getImage("resources/textures/icon64.png")); images.add(Toolkit.getDefaultToolkit().getImage("resources/textures/icon128.png")); frame.setIconImages(images); canvas = new Canvas(); /*canvas.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { newCanvasSize.set(canvas.getSize()); } });*/ frame.addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e) { canvas.requestFocusInWindow(); } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (systemTray == null) { closeRequested = true; } else { frame.setVisible(false); } } }); frame.add(canvas, BorderLayout.CENTER); resizeFrame(false); } private void resizeFrame(boolean fullscreen) throws LWJGLException { Display.setParent(null); frame.dispose(); frame.setUndecorated(fullscreen); if (fullscreen) GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame); else GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(null); canvas.setPreferredSize(new java.awt.Dimension(displayMode.getWidth(), displayMode.getHeight())); frame.pack(); java.awt.Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((dim.width - frame.getSize().width) / 2, (dim.height - frame.getSize().height) / 2); frame.setVisible(true); Display.setParent(canvas); } public void shutdown() { closeRequested = true; } private void shutdownInternal() throws LWJGLException { running = false; //if (config != null && config.hasChanged()) config.save(); if (soundManager != null) soundManager.getSoundSystem().cleanup(); if (textureManager != null) textureManager.cleanup(); if (fontManager != null) fontManager.cleanup(); if (modelManager != null) modelManager.cleanup(); ShaderProgram.cleanup(); Keyboard.destroy(); Mouse.destroy(); Display.destroy(); ledCube.getSpectrumAnalyzer().close(); File musicDir = new File("resampled"); for (File file : musicDir.listFiles()) { file.delete(); } } private long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } private float getDelta() { long time = System.nanoTime(); float delta = (time - deltaTime) / 1000000000F; deltaTime = time; return delta; } public void run() throws LWJGLException { while (!Display.isCloseRequested() && !closeRequested) { try { runGameLoop(); } catch (Exception ex) { ex.printStackTrace(); closeRequested = true; } } shutdownInternal(); } private void runGameLoop() throws LWJGLException, InterruptedException { if (fullscreen && !frame.isFocused()) setFullscreen(false); if (newDisplayMode != null || newFullscreen != fullscreen) { if (newDisplayMode != null) { displayMode = newDisplayMode; configDisplayMode = newDisplayMode; config.setProperty("display.width", configDisplayMode.getWidth()); config.setProperty("display.height", configDisplayMode.getHeight()); config.setProperty("display.antialiasing", antiAliasing); config.setProperty("display.antialiasingsamples", antiAliasingSamples); } fullscreen = newFullscreen; newDisplayMode = null; useDisplayMode(); } if (getTime() - timeCounter >= 1000) { fpsRender = fpsCounter; fpsCounter = 0; timeCounter += 1000; } fpsCounter++; soundManager.update(); this.processKeyboard(); this.processMouse(); this.processController(); this.update(); if ((frame.isVisible() && frame.getState() != Frame.ICONIFIED) || frameServer.numClients > 0) this.render(); else Thread.sleep(20); Display.update(); } private void setupAntiAliasing() { if (multisampleFBO != 0) { glDeleteTextures(multisampleTexture); glDeleteTextures(multisampleDepthTexture); glDeleteFramebuffers(multisampleFBO); multisampleTexture = 0; multisampleDepthTexture = 0; multisampleFBO = 0; } if (antiAliasing) { multisampleTexture = glGenTextures(); multisampleDepthTexture = glGenTextures(); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, antiAliasingSamples, GL_RGBA8, displayMode.getWidth(), displayMode.getHeight(), false); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisampleDepthTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, antiAliasingSamples, GL_DEPTH_STENCIL, displayMode.getWidth(), displayMode.getHeight(), false); multisampleFBO = glGenFramebuffers(); glBindFramebuffer(GL_FRAMEBUFFER, multisampleFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, multisampleDepthTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { throw new RuntimeException("Anti-aliasing framebuffer is invalid."); } glBindFramebuffer(GL_FRAMEBUFFER, 0); } } private void setupDepthTexture() { if (depthFBO != 0) { glDeleteFramebuffers(depthFBO); glDeleteTextures(depthTexture); depthFBO = 0; depthTexture = 0; } depthTexture = glGenTextures(); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, shadowMapSize, shadowMapSize, 0, GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); depthFBO = glGenFramebuffers(); glBindFramebuffer(GL_FRAMEBUFFER, depthFBO); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { throw new RuntimeException("Depth texture framebuffer is invalid."); } glBindFramebuffer(GL_FRAMEBUFFER, 0); } private void setupSystemTray() throws AWTException { if (!SystemTray.isSupported()) { LogHelper.warning("System tray is not supported."); return; } systemTray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage("resources/textures/icon16.png"); PopupMenu menu = new PopupMenu(); MenuItem item = new MenuItem("Exit"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shutdown(); } }); menu.add(item); TrayIcon trayIcon = new TrayIcon(image, Constants.APP_TITLE, menu); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() >= 2) { frame.setVisible(true); e.consume(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); systemTray.add(trayIcon); LogHelper.info("System tray icon initialized."); } private void initDisplayModes() throws LWJGLException { displayModeList = new ArrayList<>(); DisplayMode desktop = Display.getDesktopDisplayMode(); for (DisplayMode mode : Display.getAvailableDisplayModes()) { if(mode.getBitsPerPixel() == desktop.getBitsPerPixel() && mode.getFrequency() == desktop.getFrequency()) { displayModeList.add(mode); if (mode.getWidth() == 1024 && mode.getHeight() == 768) displayMode = mode; } } Collections.sort(displayModeList, new ResolutionSorter()); } private void initConfig() { if (displayMode == null) displayMode = new DisplayMode(1024, 768); config = new ConfigManager(new File(Constants.DATA_DIRECTORY, "options.yml"), true); config.load(); config.defaultProperty("display.width", displayMode.getWidth()); config.defaultProperty("display.height", displayMode.getHeight()); config.defaultProperty("display.fieldofview", 45F); config.defaultProperty("display.viewdistance", 1000F); config.defaultProperty("display.antialiasing", true); config.defaultProperty("display.antialiasingsamples", 4); //config.defaultProperty("display.fullscreen", false); config.defaultProperty("sound.effectvolume", 1.0F); config.defaultProperty("sound.musicvolume", 1.0F); config.defaultProperty("sound.inputdevice", ""); if (!internalSetDisplayMode(config.getInteger("display.width"), config.getInteger("display.height"))) { config.setProperty("display.width", displayMode.getWidth()); config.setProperty("display.height", displayMode.getHeight()); } antiAliasing = config.getBoolean("display.antialiasing"); antiAliasingSamples = config.getInteger("display.antialiasingsamples"); fieldOfView = config.getFloat("display.fieldofview"); viewDistance = config.getFloat("display.viewdistance"); //fullscreen = config.getBoolean("display.fullscreen"); if (!antiAliasingSupported) { antiAliasing = false; config.setProperty("display.antialiasing", false); } else if (antiAliasingSamples < 2 || antiAliasingSamples > antiAliasingMaxSamples || !Util.isPowerOfTwo(antiAliasingSamples)) { antiAliasingSamples = 4; config.setProperty("display.antialiasingsamples", 4); } if (fieldOfView < 10 || fieldOfView > 179) { fieldOfView = 45; config.setProperty("display.fieldofview", 45F); } /*if (config.getInteger("version") < Constants.VERSION) { config.setProperty("version", Constants.VERSION); }*/ if (config.hasChanged()) config.save(); } private void init() { initGL(); resizeGL(displayMode.getWidth(), displayMode.getHeight()); setupAntiAliasing(); } @SneakyThrows(LWJGLException.class) private void initGL() { // 3D Initialization glClearColor(0.08F, 0.08F, 0.08F, 1); glClearDepth(1); glDepthFunc(GL_LEQUAL); glDepthMask(true); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glStencilMask(0x00); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glEnable(GL_BLEND); glAlphaFunc(GL_GREATER, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // Shader init, catch errors and exit try { initShaders(); } catch (Exception ex) { ex.printStackTrace(); shutdownInternal(); System.exit(0); } } private void initShaders() { spMain = new ShaderProgram().loadShader("main").link(); } public void resizeGL(int width, int height) { // Viewport setup glViewport(0, 0, width, height); } private void processKeyboard() { toploop: while (Keyboard.next()) { for (Screen screen : screenList) if (screen.isVisible() && screen.isEnabled() && !screen.processKeyboardEvent()) continue toploop; //if (world != null && !world.processKeyboardEvent()) continue; if (Keyboard.getEventKeyState()) { // TODO: Implement key binding system if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { Mouse.setGrabbed(!Mouse.isGrabbed()); if (Mouse.isGrabbed()) Mouse.setCursorPosition(displayMode.getWidth() / 2, displayMode.getHeight() / 2); continue; } else if (Keyboard.getEventKey() == Keyboard.KEY_F2) { screenshot = true; continue; } else if (Keyboard.getEventKey() == Keyboard.KEY_F5) { ShaderProgram.cleanup(); initShaders(); continue; } else if (Keyboard.getEventKey() == Keyboard.KEY_F6) { wireframe = !wireframe; continue; } } if (!ledCube.processKeyboardEvent()) continue; if (!camera.processKeyboardEvent()) continue; /*float moveSpeed = 0.01F; if (Keyboard.getEventKey() == Keyboard.KEY_W) { if (Keyboard.getEventKeyState()) camera.setVelocity(camera.getVelocity().add(camera.getAngle().forward().multiply(moveSpeed))); else camera.setVelocity(camera.getVelocity().subtract(camera.getAngle().forward().multiply(moveSpeed))); } if (Keyboard.getEventKey() == Keyboard.KEY_S) { if (Keyboard.getEventKeyState()) camera.setVelocity(camera.getVelocity().subtract(camera.getAngle().forward().multiply(moveSpeed))); else camera.setVelocity(camera.getVelocity().add(camera.getAngle().forward().multiply(moveSpeed))); }*/ } } private void processMouse() { toploop: while (Mouse.next()) { for (Screen screen : screenList) if (screen.isVisible() && screen.isEnabled() && !screen.processMouseEvent()) continue toploop; //if (world != null && !world.processMouseEvent()) continue; //if (Mouse.getEventButton() == 0 && Mouse.getEventButtonState() && !asteroids.containsKey(getMousePos())) asteroids.put(getMousePos(), AsteroidGenerator.generate()); if (!ledCube.processMouseEvent()) continue; } } private void processController() { toploop: while (Controllers.next()) { Controller con = Controllers.getEventSource(); if (con.getName().equals(config.getString("controls.controller"))) { for (Screen screen : screenList) if (screen.isVisible() && screen.isEnabled() && !screen.processControllerEvent(con)) continue toploop; //if (world != null && !world.processControllerEvent(con)) continue; if (!ledCube.processControllerEvent(con)) continue; } } } public void update() { long time = System.nanoTime(); float delta = getDelta(); if (!packetProcessQueue.isEmpty()) { Packet packet; while ((packet = packetProcessQueue.poll()) != null) { packet.process(); } } camera.update(delta); textureManager.update(delta); ledCube.update(delta); lightingHandler.getLight(0).position = new Vector4f(camera.getPosition().getX(), camera.getPosition().getY(), camera.getPosition().getZ(), 1); Iterator<Screen> it = screenList.iterator(); while (it.hasNext()) { Screen screen = it.next(); if (screen.isRemoveRequested()) it.remove(); else if (screen.isVisible() && screen.isEnabled()) screen.update(delta); } for (ScreenHolder holder : screensToAdd) { if (holder.getIndex() < 0) { screenList.add(holder.getScreen()); } else { screenList.add(holder.getIndex(), holder.getScreen()); } } screensToAdd.clear(); if (regrab) { Mouse.setGrabbed(true); regrab = false; } } @SneakyThrows(IOException.class) public void render() { renderStart = System.nanoTime(); if (antiAliasing) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, multisampleFBO); // Setup and render 3D /*glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45, (float)displayMode.getWidth() / (float)displayMode.getHeight(), 0.1F, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity();*/ glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Setup projection matrix projectionMatrix = Matrices.perspective(fieldOfView, (float)displayMode.getWidth() / (float)displayMode.getHeight(), 0.1F, viewDistance); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, 0); //wireframe = true; if (wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); checkGLError("Pre render 3D"); render3D(); checkGLError("Post render 3D"); // Setup and render 2D glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, displayMode.getWidth(), displayMode.getHeight(), 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glClear(GL_DEPTH_BUFFER_BIT); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, 0); if (wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); checkGLError("Pre render 2D"); render2D(); checkGLError("Post render 2D"); if (antiAliasing) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampleFBO); glBlitFramebuffer(0, 0, displayMode.getWidth(), displayMode.getHeight(), 0, 0, displayMode.getWidth(), displayMode.getHeight(), GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST); } if (screenshot || frameServer.numClients > 0) { ByteBuffer buffer = BufferUtils.createByteBuffer(displayMode.getWidth() * displayMode.getHeight() * 3); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glReadPixels(0, 0, displayMode.getWidth(), displayMode.getHeight(), GL_RGB, GL_UNSIGNED_BYTE, buffer); BufferedImage image = new BufferedImage(displayMode.getWidth(), displayMode.getHeight(), BufferedImage.TYPE_INT_RGB); int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData(); buffer.rewind(); for (int y = displayMode.getHeight() - 1; y >= 0; y for (int x = 0; x < displayMode.getWidth(); x++) { pixels[x + (y * displayMode.getWidth())] = (buffer.get() & 0xFF) << 16 | (buffer.get() & 0xFF) << 8 | (buffer.get() & 0xFF); } } if (screenshot) { screenshot = false; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); File screenshotDir = new File(Constants.DATA_DIRECTORY, "screenshots"); screenshotDir.mkdirs(); File file = new File(screenshotDir, dateFormat.format(Calendar.getInstance().getTime()) + ".png"); for (int i = 2; file.exists(); i++) { file = new File(screenshotDir, dateFormat.format(Calendar.getInstance().getTime()) + "_" + i + ".png"); } ImageIO.write(image, "png", file); } if (frameServer.numClients > 0) { frameServer.queueFrame(image); } } } public void render3D() { glPushMatrix(); spMain.use(); setupView(camera.getPosition(), camera.getAngle()); sendMatrixToProgram(); lightingHandler.sendToShader(); faceCount = ledCube.render(); InstancedRenderer.prepareItems(); InstancedRenderer.renderAll(); InstancedRenderer.resetItems(); ShaderProgram.useNone(); glPopMatrix(); } public void render2D() { glPushMatrix(); for (Screen screen : screenList) if (screen.isVisible()) screen.render(); long renderTime = System.nanoTime() - renderStart; if (/*renderFPS || renderDebug ||*/ true) { UnicodeFont debugFont = fontManager.getFont("chemrea", 20, false, false).getUnicodeFont(); org.newdawn.slick.Color debugColor = org.newdawn.slick.Color.yellow; int y = 0; if (renderFPS || debugMode) debugFont.drawString(5, 5 + y++ * 25, "FPS: " + fpsRender, debugColor); debugFont.drawString(5, 5 + y++ * 25, "Serial port: " + (ledCube.getCommThread().isPortOpen() ? "open" : "closed"), debugColor); debugFont.drawString(5, 5 + y++ * 25, "TCP clients: " + ledCube.getCommThread().getNumTCPClients(), debugColor); debugFont.drawString(5, 5 + y++ * 25, "Current music: " + ledCube.getSpectrumAnalyzer().getCurrentTrack(), debugColor); debugFont.drawString(5, 5 + y++ * 25, "Music time: " + ledCube.getSpectrumAnalyzer().getPositionMillis(), debugColor); if (ledCube.getLEDManager().getResolution() < 255) debugFont.drawString(5, 5 + y++ * 25, "Color mode: " + (ledCube.isTrueColor() ? "true" : "full"), debugColor); if (convertingAudio) debugFont.drawString(5, 5 + y++ * 25, "Converting audio...", debugColor); if (debugMode) { Runtime runtime = Runtime.getRuntime(); debugFont.drawString(5, 5 + y++ * 25, "Memory: " + Util.bytesToMBString(runtime.totalMemory() - runtime.freeMemory()) + " / " + Util.bytesToMBString(runtime.maxMemory()), debugColor); //debugFont.drawString(5, 5 + y++ * 25, "Update time: " + (updateTime / 1000000D), debugColor); //debugFont.drawString(5, 5 + y++ * 25, "Render time: " + (renderTime / 1000000D), debugColor); Vector3 vector = camera.getAngle().forward(); debugFont.drawString(5, 5 + y++ * 25, "Camera vector: " + vector.getX() + ", " + vector.getY() + ", " + vector.getZ(), debugColor); vector = camera.getPosition(); debugFont.drawString(5, 5 + y++ * 25, "Camera position: " + vector.getX() + ", " + vector.getY() + ", " + vector.getZ(), debugColor); //debugFont.drawString(5, 5 + y++ * 25, "Cursor position: " + Util.getMouseX() + ", " + Util.getMouseY(), debugColor); //debugFont.drawString(5, 5 + y++ * 25, "Cursor offset: " + (Util.getMouseX() - getWidth() / 2) + ", " + (Util.getMouseY() - getHeight() / 2 + 1), debugColor); debugFont.drawString(5, 5 + y++ * 25, "Rendered faces: " + faceCount, debugColor); //debugFont.drawString(5, 5 + y++ * 25, "Entities: " + (world != null ? world.getEntityCount() : 0), debugColor); } } glPopMatrix(); } private void checkGLError(String stage) { if (debugMode) { for (int error = glGetError(); error != GL_NO_ERROR; error = glGetError()) { LogHelper.severe(" LogHelper.severe("@ %s", stage); LogHelper.severe("%d: %s", error, gluErrorString(error)); } } } private void setupView(Vector3 position, Quaternion rotation) { viewMatrix = new Matrix4f(); modelMatrix = new Matrix4f(); Matrix4f.mul(viewMatrix, rotation.getMatrix(), viewMatrix); viewMatrix.translate(Util.convertVector(position.negate())); frustum.update(Util.matrixToArray(projectionMatrix), Util.matrixToArray(viewMatrix)); } private void setupView(Vector3 position, Angle angle) { viewMatrix = new Matrix4f(); modelMatrix = new Matrix4f(); viewMatrix.rotate((float)Math.toRadians(angle.getRoll()), new Vector3f(0, 0, -1)); viewMatrix.rotate((float)Math.toRadians(angle.getPitch()), new Vector3f(-1, 0, 0)); viewMatrix.rotate((float)Math.toRadians(angle.getYaw()), new Vector3f(0, -1, 0)); viewMatrix.translate(Util.convertVector(position.negate())); frustum.update(Util.matrixToArray(projectionMatrix), Util.matrixToArray(viewMatrix)); } private void sendMatrixToProgram() { ShaderProgram program = ShaderProgram.getCurrent(); if (program == null) return; int projectionMatrixLoc = program.getUniformLocation("projection_matrix"); int viewMatrixLoc = program.getUniformLocation("view_matrix"); matrixBuffer.rewind(); Util.storeMatrixInBuffer(projectionMatrix, matrixBuffer); matrixBuffer.rewind(); glUniformMatrix4(projectionMatrixLoc, false, matrixBuffer); matrixBuffer.rewind(); viewMatrix.store(matrixBuffer); matrixBuffer.rewind(); glUniformMatrix4(viewMatrixLoc, false, matrixBuffer); } public Vector3[] getCursorRay() { float nearClip = 0.1F; Vector3 look = camera.getAngle().forward(); Vector3 lookH = camera.getAngle().right(); Vector3 lookV = camera.getAngle().up().negate(); float fovRad = (float)Math.toRadians(fieldOfView); float vLength = (float)Math.tan(fovRad / 2) * nearClip; float hLength = vLength * ((float)displayMode.getWidth() / (float)displayMode.getHeight()); lookH = lookH.multiply(hLength); lookV = lookV.multiply(vLength); float mouseX = (Util.getMouseX() - displayMode.getWidth() / 2F) / (displayMode.getWidth() / 2F); float mouseY = (Util.getMouseY() - displayMode.getHeight() / 2F) / (displayMode.getHeight() / 2F); Vector3 position = camera.getPosition().add(look.multiply(nearClip)).add(lookH.multiply(mouseX)).add(lookV.multiply(mouseY)); Vector3 direction = position.subtract(camera.getPosition()).normalized(); return new Vector3[]{position, direction}; } public static Color getPaintColor() { return ledCube.getPaintColor(); } public static void setPaintColor(Color color) { ledCube.setPaintColor(color); } public Controller getController(String name) { Integer index = validControllers.get(name); return index != null ? Controllers.getController(index) : null; } public DisplayMode findDisplayMode(int width, int height) { for (DisplayMode mode : displayModeList) { if(mode.getWidth() == width && mode.getHeight() == height) { return mode; } } return null; } public void useDisplayMode() throws LWJGLException { try { regrab = Mouse.isGrabbed(); Mouse.setGrabbed(false); DisplayMode desktopMode = Display.getDesktopDisplayMode(); if (fullscreen) { if (!desktopMode.equals(displayMode)) displayMode = desktopMode; } else displayMode = configDisplayMode; resizeFrame(fullscreen); Display.setDisplayMode(displayMode); resizeGL(displayMode.getWidth(), displayMode.getHeight()); setupAntiAliasing(); for (GUICallback callback : resizeHandlers) { callback.run(); } } catch (LWJGLException ex) { ex.printStackTrace(); shutdownInternal(); } } public void setDisplayMode(DisplayMode displayMode) { this.newDisplayMode = displayMode; } public boolean setDisplayMode(int width, int height) { DisplayMode mode = findDisplayMode(width, height); if (mode != null) { setDisplayMode(mode); return true; } return false; } private boolean internalSetDisplayMode(int width, int height) { DisplayMode mode = findDisplayMode(width, height); if (mode != null) { displayMode = mode; configDisplayMode = mode; return true; } return false; } public boolean isFullscreen() { return fullscreen; } public void setFullscreen(boolean fullscreen) { this.newFullscreen = fullscreen; } public void setAntiAliasing(boolean enabled, int samples) { antiAliasing = enabled; antiAliasingSamples = samples; } public int addResizeHandler(GUICallback resizeHandler) { if (resizeHandlers.add(resizeHandler)) return resizeHandlers.indexOf(resizeHandler); return -1; } public boolean removeResizeHandler(GUICallback resizeHandler) { return resizeHandlers.remove(resizeHandler); } public GUICallback removeResizeHandler(int index) { return resizeHandlers.remove(index); } public void clearResizeHandlers() { resizeHandlers.clear(); } public List<Screen> getScreenList() { return Collections.unmodifiableList(screenList); } public void addScreen(Screen screen) { screensToAdd.add(new ScreenHolder(-1, screen)); } public void addScreen(int index, Screen screen) { screensToAdd.add(new ScreenHolder(index, screen)); } public boolean removeScreen(Screen screen) { boolean ret = screenList.remove(screen); if (ret) screen.remove(); return ret; } public Screen removeScreen(int index) { Screen screen = screenList.get(index); screen.remove(); return screen; } public void clearScreens() { for (Screen screen : screenList) screen.remove(); screenList.clear(); } public static int getWidth() { return displayMode.getWidth(); } public static int getHeight() { return displayMode.getHeight(); } public static void queuePacketForProcessing(Packet packet) { instance.packetProcessQueue.add(packet); } @Value private class ScreenHolder { private int index; private Screen screen; } }
package au.gov.amsa.animator; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import javax.swing.Timer; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.wms.WebMapServer; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.DirectPosition2D; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.map.MapContent; import org.geotools.map.WMSLayer; import org.geotools.ows.ServiceException; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.styling.SLD; import org.geotools.styling.Style; import org.geotools.swing.JMapFrame; import org.geotools.swing.event.MapMouseAdapter; import org.geotools.swing.event.MapMouseEvent; import org.geotools.swing.wms.WMSLayerChooser; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; public class Animator { volatile Timer timer; public void start() { // Create a map context and add our shapefile to it final MapContent map = createMap(); // Now display the map using the custom renderer display(map); } private MapContent createMap() { final MapContent map = new MapContent(); map.setTitle("Animator"); map.addLayer(createCoastlineLayer()); map.addLayer(createExtraFeatures()); // addWms(map); return map; } private void display(final MapContent map) { EventQueue.invokeLater(() -> { // setup custom rendering over the top of the map VesselMovementRenderer renderer = new VesselMovementRenderer(); final JMapFrame frame = new JMapFrame(map); frame.getMapPane().setRenderer(renderer); frame.enableStatusBar(true); frame.enableToolBar(true); frame.initComponents(); frame.setSize(800, 600); FramePreferences.restoreLocationAndSize(frame, 100, 100, 800, 600, Animator.class); frame.getMapPane().addMouseListener(new MapMouseAdapter() { @Override public void onMouseClicked(MapMouseEvent event) { DirectPosition2D p = event.getWorldPos(); System.out.println(p); } }); frame.setVisible(true); timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("timer"); renderer.next(); frame.getMapPane().repaint(); } }); timer.start(); }); } private Layer createCoastlineLayer() { try { File file = new File( "/home/dxm/Downloads/shapefile-australia-coastline-polygon/cstauscd_r.shp"); FileDataStore store = FileDataStoreFinder.getDataStore(file); SimpleFeatureSource featureSource = store.getFeatureSource(); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(featureSource, style); return layer; } catch (IOException e) { throw new RuntimeException(e); } } private static Layer createExtraFeatures() { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName("Location"); b.setCRS(DefaultGeographicCRS.WGS84); // picture location b.add("geom", Point.class); final SimpleFeatureType TYPE = b.buildFeatureType(); GeometryFactory gf = JTSFactoryFinder.getGeometryFactory(); Point point = gf.createPoint(new Coordinate(149.1244, -35.3075)); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(TYPE); builder.add(point); SimpleFeature feature = builder.buildFeature("Canberra"); DefaultFeatureCollection features = new DefaultFeatureCollection(null, null); features.add(feature); Style style = SLD.createPointStyle("Star", Color.BLUE, Color.BLUE, 0.3f, 10); return new FeatureLayer(features, style); } static void addWms(MapContent map) { // URL wmsUrl = WMSChooser.showChooseWMS(); WebMapServer wms; try { wms = new WebMapServer(new URL("http://sarapps.amsa.gov.au:8080/cts-gis/wms")); } catch (ServiceException | IOException e) { throw new RuntimeException(e); } List<org.geotools.data.ows.Layer> wmsLayers = WMSLayerChooser.showSelectLayer(wms); for (org.geotools.data.ows.Layer wmsLayer : wmsLayers) { System.out.println("adding " + wmsLayer.getTitle()); WMSLayer displayLayer = new WMSLayer(wms, wmsLayer); map.addLayer(displayLayer); } } public static void main(String[] args) throws Exception { // System.setProperty("http.proxyHost", "proxy.amsa.gov.au"); // System.setProperty("http.proxyPort", "8080"); // System.setProperty("https.proxyHost", "proxy.amsa.gov.au"); // System.setProperty("https.proxyPort", "8080"); new Animator().start(); } }
package com.valkryst.VTerminal; import com.valkryst.VTerminal.misc.ColoredImageCache; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.util.Objects; public class AsciiTile extends AsciiCharacter { /** * Constructs a new AsciiTile. * * @param character * The character. */ public AsciiTile(final char character) { super(character); } /** * Constructs a new AsciiTile by copying the data * of an AsciiCharacter. * * Does not copy the blinkTimer. * * @param character * The AsciiCharacter. * * @throws NullPointerException * If the character is null. */ public AsciiTile(final AsciiCharacter character) { super(character.getCharacter()); super.setHidden(character.isHidden()); super.setBackgroundColor(character.getBackgroundColor()); super.setForegroundColor(character.getForegroundColor()); final Rectangle boundingBox = character.getBoundingBox(); super.getBoundingBox().setSize(boundingBox.width, boundingBox.height); super.getBoundingBox().setLocation(boundingBox.x, boundingBox.y); super.setUnderlined(character.isUnderlined()); super.setUnderlineThickness(character.getUnderlineThickness()); super.setFlippedHorizontally(character.isFlippedHorizontally()); super.setFlippedVertically(character.isFlippedVertically()); } /** * Draws the tile onto the specified context. * * @param gc * The graphics context to draw with. * * @param imageCache * The image cache to retrieve character images from. * * @param columnIndex * The x-axis (column) coordinate where the character is to be drawn. * * @param rowIndex * The y-axis (row) coordinate where the character is to be drawn. * * @throws NullPointerException * If the gc or image cache are null. */ @Override public void draw(final Graphics2D gc, final ColoredImageCache imageCache, int columnIndex, int rowIndex) { Objects.requireNonNull(gc); Objects.requireNonNull(imageCache); final int fontWidth = imageCache.getFont().getWidth(); final int fontHeight = imageCache.getFont().getHeight(); columnIndex *= fontWidth; rowIndex *= fontHeight; BufferedImage image = null; // Handle hidden state: if (super.isHidden()) { gc.setColor(super.getBackgroundColor()); gc.fillRect(columnIndex, rowIndex, fontWidth, fontHeight); } else { image = imageCache.retrieveFromCache(this); } if (image != null) { // Handle Horizontal/Vertical Flipping: if (super.isFlippedHorizontally() || super.isFlippedVertically()) { AffineTransform tx; tx = AffineTransform.getScaleInstance((super.isFlippedHorizontally() ? -1 : 1), (super.isFlippedVertically() ? -1 : 1)); tx.translate((super.isFlippedHorizontally() ? -fontWidth : 0), (super.isFlippedVertically() ? -fontHeight : 0)); final BufferedImageOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC); image = op.filter(image, null); } // Draw character: gc.drawImage(image, columnIndex, rowIndex, null); } super.getBoundingBox().setLocation(columnIndex, rowIndex); super.getBoundingBox().setSize(fontWidth, fontHeight); // Draw underline: if (super.isUnderlined()) { gc.setColor(super.getForegroundColor()); final int y = rowIndex + fontHeight - super.getUnderlineThickness(); gc.fillRect(columnIndex, y, fontWidth, super.getUnderlineThickness()); } } }
package org.eddy.controller; import org.eddy.captcha.CaptchaUtil; import org.eddy.pipeline.Pipeline; import org.eddy.pipeline.command.Command; import org.eddy.pipeline.command.CommandNotify; import org.eddy.service.TaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Objects; @RestController @RequestMapping("/task") public class TaskController { @Autowired private TaskService taskService; @RequestMapping(path = "/begin", method = RequestMethod.GET) public ResponseEntity<String> begin() { String group = taskService.submit(); return ResponseEntity.ok(group); } @RequestMapping(path = "/login", method = RequestMethod.POST) public ResponseEntity<Void> loginCaptcha(String pipeline, Integer[] numbers) { Objects.requireNonNull(pipeline); Objects.requireNonNull(numbers); CommandNotify notify = new CommandNotify(); notify.setPipeline(pipeline); notify.setArg(numbers); notify.setCommand(Command.LOGIN); Pipeline.putNotify(notify); return ResponseEntity.ok().build(); } @RequestMapping(path = "/refresh", method = RequestMethod.GET) public ResponseEntity<Void> refreshLoginCaptcha(String pipeline) { return refreshCaptcha(pipeline, Command.REFRESH_LOGIN_CAPTCHA); } @RequestMapping(path = "/confirmRefresh", method = RequestMethod.GET) public ResponseEntity<Void> refreshTicketCaptcha(String pipeline) { return refreshCaptcha(pipeline, Command.TICKET_CAPTCHA); } private ResponseEntity<Void> refreshCaptcha(String pipeline, Command command) { Objects.requireNonNull(pipeline); Objects.requireNonNull(command); CommandNotify notify = new CommandNotify(); notify.setPipeline(pipeline); notify.setArg(CaptchaUtil.imageFileName()); notify.setCommand(command); Pipeline.putNotify(notify); return ResponseEntity.ok().build(); } @RequestMapping(path = "/confirmTicket", method = RequestMethod.POST) public ResponseEntity<Void> ticketCaptcha(String pipeline, Integer[] numbers) { Objects.requireNonNull(pipeline); Objects.requireNonNull(numbers); CommandNotify notify = new CommandNotify(); notify.setPipeline(pipeline); notify.setArg(numbers); notify.setCommand(Command.TICKET_CAPTCHA_VERIFY); Pipeline.putNotify(notify); return ResponseEntity.ok().build(); } @RequestMapping(path = "/confirmOrder", method = RequestMethod.GET) public ResponseEntity<Void> confirmOrder(String pipeline) { Objects.requireNonNull(pipeline); CommandNotify notify = new CommandNotify(); notify.setPipeline(pipeline); notify.setArg(null); notify.setCommand(Command.CONFIRM); Pipeline.putNotify(notify); return ResponseEntity.ok().build(); } }
package com.yox89.ld32.screens; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.MapObjects; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.objects.PolylineMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.math.Polyline; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction; import com.badlogic.gdx.scenes.scene2d.actions.RotateToAction; import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction; import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.yox89.ld32.CollisionManager; import com.yox89.ld32.CollisionManager.CollisionManagerListener; import com.yox89.ld32.Gajm; import com.yox89.ld32.Physics; import com.yox89.ld32.actors.GhostActor; import com.yox89.ld32.actors.LightSource; import com.yox89.ld32.actors.Mirror; import com.yox89.ld32.actors.PhysicsActor; import com.yox89.ld32.actors.PlayerActor; import com.yox89.ld32.actors.Torch; import com.yox89.ld32.actors.Wall; import com.yox89.ld32.raytracing.Direction; import com.yox89.ld32.raytracing.LightColor; import com.yox89.ld32.util.Ui; public class TiledLevelScreen extends BaseScreen implements CollisionManagerListener { private static final String WALL = "Wall"; private static final String RED_LASER = "RedLaser"; private static final String GREEN_LASER = "GreenLaser"; private static final String MIRROR = "Mirror"; private static final String GHOST = "Ghost"; private static final String TORCH = "Torch"; public static boolean stopUserInput; private final MapLayer mObjectLayer; private boolean[][] mLightNotAllowed; private CollisionManager mCollisionManager; private ShapeRenderer mFocusRenderer; private Actor mFocus; final Vector2 mLastHoverCoords = new Vector2(-1f, -1f); protected int mNumberRemainingMirrors; protected int mNumberTotalMirrors; private Physics mPhysics; private PlayerActor mPlayer; private final Gajm mGajm; private final int mLevelId; private Ui ui; public TiledLevelScreen(Gajm gajm, int level) { mGajm = gajm; mLevelId = level; mFocusRenderer = manage(new ShapeRenderer()); mNumberRemainingMirrors = 5; mNumberTotalMirrors = 5; final TiledMap levelMap = new TmxMapLoader().load("levels/level" + level + ".tmx"); TiledMapTileLayer levelMapLayer = (TiledMapTileLayer) levelMap .getLayers().get("Tile Layer"); GAME_WORLD_HEIGHT = levelMapLayer.getHeight(); GAME_WORLD_WIDTH = levelMapLayer.getWidth(); this.mLightNotAllowed = new boolean[GAME_WORLD_WIDTH][GAME_WORLD_HEIGHT]; MapLayer objectLayer = (MapLayer) levelMap.getLayers().get( "Object Layer"); this.mObjectLayer = objectLayer; levelMap.dispose(); } @Override protected void init(Stage game, Stage uiStage, Physics physics) { ui = new Ui(this,uiStage, mNumberTotalMirrors); mPhysics = physics; mCollisionManager = new CollisionManager(physics.world); mCollisionManager.mCollisionManagerListener = this; mPlayer = new PlayerActor(physics); game.addActor(mPlayer); mPlayer.setPosition(GAME_WORLD_WIDTH / 2 - mPlayer.getWidth() / 2, GAME_WORLD_HEIGHT / 2); MapObjects mapObjects = this.mObjectLayer.getObjects(); for (MapObject mapObject : mapObjects) { MapProperties mapProperties = mapObject.getProperties(); float x = mapProperties.get("x", Float.class); float y = mapProperties.get("y", Float.class); float width = mapProperties.get("width", Float.class); float height = mapProperties.get("height", Float.class); String type = mapProperties.get("type", String.class); if (type == null) { System.err.println("Null type on " + mapProperties); continue; } if (type.equals(WALL)) { for (int i = (int) x; i < x + width; i++) { for (int j = (int) y; j < y + height; j++) { this.mLightNotAllowed[i][j] = true; } } add(game, new Wall(physics.world, width, height), x, y); } else if (type.equalsIgnoreCase(TORCH)) { add(game, new Torch(physics), x, y); } else if (type.equals(RED_LASER)) { add(game, new LightSource(this, physics, LightColor.RED, parseLightDirection((int) x, (int) y)), x, y); } else if (type.equals(GREEN_LASER)) { add(game, new LightSource(this, physics, LightColor.GREEN, parseLightDirection((int) x, (int) y)), x, y); } else if (type.equals(GHOST)) { if (mapObject instanceof PolylineMapObject) { PolylineMapObject ghostObject = (PolylineMapObject) mapObject; ArrayList<Vector2> path = getPathForGhost(ghostObject); Vector2 startPosition = path.get(0); GhostActor ghostActor = new GhostActor(physics, path); add(game, ghostActor, startPosition.x, startPosition.y); } else { assert false : "The ghost must be a PolylineMapObject"; } } else if (type.equals(MIRROR)) { add(game, new Mirror(physics), x, y); } } } @Override public boolean mouseMoved(int screenX, int screenY) { mGameStage.screenToStageCoordinates(mLastHoverCoords.set(screenX, screenY)); if (mouseIsInRangeOfPlayer()) { mFocus = mGameStage.hit(mLastHoverCoords.x, mLastHoverCoords.y, true); } return false; } public boolean mouseIsInRangeOfPlayer() { return new Vector2(mPlayer.getX(), mPlayer.getY()) .sub(mLastHoverCoords).len() < 5; } @Override public boolean keyDown(int keycode) { if (keycode == Keys.R) { mGajm.setScreen(new TiledLevelScreen(mGajm, mLevelId)); return true; } else if (keycode == Keys.E) { if (mFocus instanceof Mirror) { mFocus.remove(); mNumberRemainingMirrors++; updateMirrorsLabel(); return true; } return true; }else if (keycode == Keys.Q) { mGajm.setScreen(new StartScreen(mGajm)); return true; } return super.keyDown(keycode); } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { mouseMoved(screenX, screenY); if (mouseIsInRangeOfPlayer()) { if (mFocus == null && mNumberRemainingMirrors > 0) { mNumberRemainingMirrors updateMirrorsLabel(); final Mirror mirror = new Mirror(mPhysics); add(mGameStage, mirror, (int) mLastHoverCoords.x, (int) mLastHoverCoords.y); mFocus = mirror; return true; } else if (mFocus instanceof Mirror) { mFocus.rotateBy(45f); return true; } } return false; } private void updateMirrorsLabel() { ui.setMirrorsLeftText(mNumberRemainingMirrors + ""); } @Override public void render(float delta) { super.render(delta); if (mouseIsInRangeOfPlayer() && (mFocus instanceof Mirror || mFocus instanceof LightSource || mNumberRemainingMirrors > 0)) { Gdx.gl.glEnable(GL20.GL_BLEND); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); mFocusRenderer.setProjectionMatrix(mGameStage.getCamera().combined); mFocusRenderer.begin(ShapeType.Filled); mFocusRenderer.setColor(1f, 1f, 1f, .15f); mFocusRenderer.rect((int) mLastHoverCoords.x, (int) mLastHoverCoords.y, 1f, 1f); mFocusRenderer.end(); Gdx.gl.glDisable(GL20.GL_BLEND); } } private ArrayList<Vector2> getPathForGhost(PolylineMapObject ghostObject) { Polyline polyline = ghostObject.getPolyline(); ArrayList<Vector2> positions = new ArrayList<Vector2>(); float vertices[] = polyline.getTransformedVertices(); for (int i = 0; i < vertices.length; i = i + 2) { Vector2 position = new Vector2(vertices[i], vertices[i + 1]); positions.add(position); } return positions; } private boolean lightAllowedAtTile(int x, int y) { if (x >= 0 && y >= 0 && x < GAME_WORLD_WIDTH && y < GAME_WORLD_HEIGHT) { return !this.mLightNotAllowed[x][y]; } return false; } private Direction[] parseLightDirection(int x, int y) { Array<Direction> dirs = new Array<Direction>(4); if (this.lightAllowedAtTile(x + 1, y)) { dirs.add(Direction.EAST); } if (this.lightAllowedAtTile(x - 1, y)) { dirs.add(Direction.WEST); } if (this.lightAllowedAtTile(x, y + 1)) { dirs.add(Direction.NORTH); } if (this.lightAllowedAtTile(x, y - 1)) { dirs.add(Direction.SOUTH); } return dirs.toArray(Direction.class); } private void add(Stage game, Actor actor, float x, float y) { if (actor instanceof Disposable) { manage((Disposable) actor); } actor.setPosition(x, y); game.addActor(actor); } @Override public void playerDiscoveredByGhost(PhysicsActor ghost) { ghost.clearActions(); Vector2 diff = new Vector2(ghost.getX() - mPlayer.getX(), ghost.getY() - mPlayer.getY()); float length = diff.len(); float duration = length / 5f; stopUserInput = true; RotateToAction rotateAction = Actions.rotateTo(diff.angle()); MoveToAction moveAction = Actions.moveTo(mPlayer.getX(), mPlayer.getY(), duration); RunnableAction runnableAction = Actions.run(new Runnable() { @Override public void run() { loseGame(); } }); SequenceAction sequenceAction = Actions.sequence(rotateAction, moveAction, runnableAction); ghost.addAction(sequenceAction); } public void loseGame() { stopUserInput = false; mGajm.setScreen(new TiledLevelScreen(mGajm, mLevelId)); } }
package com.rgi.geopackage.tiles; import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import utility.DatabaseUtility; import com.rgi.common.BoundingBox; import com.rgi.common.util.jdbc.ResultSetStream; import com.rgi.geopackage.core.GeoPackageCore; import com.rgi.geopackage.verification.Assert; import com.rgi.geopackage.verification.AssertionError; import com.rgi.geopackage.verification.ColumnDefinition; import com.rgi.geopackage.verification.ForeignKeyDefinition; import com.rgi.geopackage.verification.Requirement; import com.rgi.geopackage.verification.Severity; import com.rgi.geopackage.verification.TableDefinition; import com.rgi.geopackage.verification.VerificationLevel; import com.rgi.geopackage.verification.Verifier; /** * @author Jenifer Cochran * */ public class TilesVerifier extends Verifier { /** * This Epsilon is the greatest difference we allow when comparing doubles */ public static final double EPSILON = 0.0001; /** * @param sqliteConnection * the connection to the database * @param verificationLevel * Controls the level of verification testing performed * @throws SQLException * throws if the method {@link DatabaseUtility#tableOrViewExists(Connection, String) tableOrViewExists} throws */ public TilesVerifier(final Connection sqliteConnection, final VerificationLevel verificationLevel) throws SQLException { super(sqliteConnection, verificationLevel); final String queryTables = "SELECT tbl_name FROM sqlite_master " + "WHERE tbl_name NOT LIKE 'gpkg_%' " + "AND (type = 'table' OR type = 'view');"; try(PreparedStatement createStmt = this.getSqliteConnection().prepareStatement(queryTables); ResultSet possiblePyramidTables = createStmt.executeQuery();) { this.allPyramidUserDataTables = ResultSetStream.getStream(possiblePyramidTables) .map(resultSet -> { try { final TableDefinition possiblePyramidTable = new TilePyramidUserDataTableDefinition(resultSet.getString("tbl_name")); this.verifyTable(possiblePyramidTable); return possiblePyramidTable.getName(); } catch(final SQLException | AssertionError ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch(final SQLException ex) { this.allPyramidUserDataTables = Collections.emptySet(); } final String query2 = String.format("SELECT table_name FROM %s WHERE data_type = 'tiles';", GeoPackageCore.ContentsTableName); try(PreparedStatement createStmt2 = this.getSqliteConnection().prepareStatement(query2); ResultSet contentsPyramidTables = createStmt2.executeQuery()) { this.pyramidTablesInContents = ResultSetStream.getStream(contentsPyramidTables) .map(resultSet -> { try { return resultSet.getString("table_name"); } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch(final SQLException ex) { this.pyramidTablesInContents = Collections.emptySet(); } final String query3 = String.format("SELECT DISTINCT table_name FROM %s;", GeoPackageTiles.MatrixTableName); try(PreparedStatement createStmt3 = this.getSqliteConnection().prepareStatement(query3); ResultSet tileMatrixPyramidTables = createStmt3.executeQuery()) { this.pyramidTablesInTileMatrix = ResultSetStream.getStream(tileMatrixPyramidTables) .map(resultSet -> { try { final String pyramidName = resultSet.getString("table_name"); return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), pyramidName) ? pyramidName : null; } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch(final SQLException ex) { this.pyramidTablesInTileMatrix = Collections.emptySet(); } this.hasTileMatrixSetTable = this.tileMatrixSetTableExists(); this.hasTileMatrixTable = this.tileMatrixTableExists(); } /** * Requirement 33 * * <blockquote> * The <code>gpkg_contents</code> table SHALL contain a row with * a <code>data_type</code> column value of 'tiles' for each * tile pyramid user data table or view. * </blockquote> * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement(number = 33, text = "The gpkg_contents table SHALL contain a row with a " + "data_type column value of \"tiles\" for each " + "tile pyramid user data table or view.", severity = Severity.Warning) public void Requirement33() throws AssertionError { for(final String tableName: this.allPyramidUserDataTables) { Assert.assertTrue(String.format("The Tile Pyramid User Data table that is not refrenced in %2$s table is: %1$s. " + "This table needs to be referenced in the %2$s table.", tableName, GeoPackageCore.ContentsTableName), this.pyramidTablesInContents.contains(tableName)); } } /** * Requirement 34 * * <blockquote> * In a GeoPackage that contains a tile pyramid user data table * that contains tile data, by default, zoom level pixel sizes * for that table SHALL vary by a factor of 2 between adjacent * zoom levels in the tile matrix metadata table. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement * @throws SQLException throws if an SQLException occurs */ @Requirement(number = 34, text = "In a GeoPackage that contains a tile pyramid user data table " + "that contains tile data, by default, zoom level pixel sizes for that " + "table SHALL vary by a factor of 2 between zoom levels in tile matrix metadata table.", severity = Severity.Warning) public void Requirement34() throws AssertionError, SQLException { if(this.hasTileMatrixTable) { for (final String tableName : this.allPyramidUserDataTables) { final String query1 = String.format("SELECT table_name, " + "zoom_level, " + "pixel_x_size, " + "pixel_y_size," + "matrix_width," + "matrix_height," + "tile_width," + "tile_height " + "FROM %s " + "WHERE table_name = ? " + "ORDER BY zoom_level ASC;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query1)) { stmt.setString(1, tableName); try(ResultSet pixelInfo = stmt.executeQuery()) { final List<TileData> tileDataSet = ResultSetStream.getStream(pixelInfo) .map(resultSet -> { try { final TileData tileData = new TileData(); tileData.pixelXSize = resultSet.getDouble("pixel_x_size"); tileData.pixelYSize = resultSet.getDouble("pixel_y_size"); tileData.zoomLevel = resultSet.getInt("zoom_level"); tileData.matrixHeight = resultSet.getInt("matrix_height"); tileData.matrixWidth = resultSet.getInt("matrix_width"); tileData.tileHeight = resultSet.getInt("tile_height"); tileData.tileWidth = resultSet.getInt("tile_width"); return tileData; } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); for(int index = 0; index < tileDataSet.size()-1; ++index) { final TileData current = tileDataSet.get(index); final TileData next = tileDataSet.get(index + 1); if(current.zoomLevel == next.zoomLevel - 1) { Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not vary by factors of 2" + " between adjacent zoom levels in the tile matrix metadata table: %f, %f", next.pixelXSize, next.pixelYSize), TilesVerifier.isEqual((current.pixelXSize / 2.0), next.pixelXSize) && TilesVerifier.isEqual((current.pixelYSize / 2.0), next.pixelYSize)); } } //TODO Test will be moved on later release//This tests if the pixel x values and pixel y values are valid based on their bounding box in the tile matrix set if(this.hasTileMatrixSetTable) { final String query2 = String.format("SELECT min_x, min_y, max_x, max_y FROM %s WHERE table_name = ?", GeoPackageTiles.MatrixSetTableName); try(PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2)) { stmt2.setString(1, tableName); try( ResultSet boundingBoxRS = stmt2.executeQuery()) { if(boundingBoxRS.next()) { final double minX = boundingBoxRS.getDouble("min_x"); final double minY = boundingBoxRS.getDouble("min_y"); final double maxX = boundingBoxRS.getDouble("max_x"); final double maxY = boundingBoxRS.getDouble("max_y"); final BoundingBox boundingBox = new BoundingBox(minX, minY, maxX, maxY); final List<TileData> invalidPixelValues = tileDataSet.stream() .filter(tileData -> !validPixelValues(tileData, boundingBox)) .collect(Collectors.toList()); Assert.assertTrue(String.format("\nNote: This next message is an additional concern that is related to this requirement but not the requirement itself."+ "\nThe pixel_x_size and pixel_y_size should satisfy these two equations:" + "\n\tpixel_x_size = (bounding box width / matrix_width) / tile_width " + "AND \n\tpixel_y_size = (bounding box height / matrix_height)/ tile_height. " + "\nBased on these two equations, the following pixel values are invalid for the table '%s'.:\n%s ", tableName, invalidPixelValues.stream() .map(tileData -> String.format("\tInvalid pixel_x_size: %f, Invalid pixel_y_size: %f at zoom_level %d", tileData.pixelXSize, tileData.pixelYSize, tileData.zoomLevel)) .collect(Collectors.joining("\n"))), invalidPixelValues.isEmpty()); } } } } } } } } } @Requirement(number = 35, text = "In a GeoPackage that contains a tile pyramid user data table that contains tile data SHALL store that tile data in MIME type image/jpeg or image/png", severity = Severity.Warning) public void Requirement35() throws AssertionError { Assert.assertTrue("Test skipped when verification level is not set to " + VerificationLevel.Full, this.verificationLevel == VerificationLevel.Full); for (final String tableName : this.allPyramidUserDataTables) { final String selectTileDataQuery = String.format("SELECT tile_data, id FROM %s;", tableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(selectTileDataQuery); ResultSet tileDataResultSet = stmt.executeQuery()) { List<String> errorMessage = ResultSetStream.getStream(tileDataResultSet) .map(resultSet -> { try { final int tileId = resultSet.getInt("id"); final byte[] tileData = resultSet.getBytes("tile_data"); return TilesVerifier.verifyData(tileId, tileData); } catch (final SQLException ex1) { return ex1.getMessage(); } }) .filter(Objects::nonNull) .collect(Collectors.toList()); Assert.assertTrue(String.format("The following columns named \"id\" in table '%s' are not in the correct image format:\n\t\t%s.", tableName, errorMessage.stream().collect(Collectors.joining("\n"))), errorMessage.isEmpty()); } catch (final SQLException ex) { Assert.fail(ex.getMessage()); } } } private static String verifyData(final int tileId, final byte[] tileData) { if(tileData == null) { return String.format("column id %d", tileId); } try(ByteArrayInputStream byteArray = new ByteArrayInputStream(tileData); MemoryCacheImageInputStream cacheImage = new MemoryCacheImageInputStream(byteArray)) { if(TilesVerifier.canReadImage(pngImageReaders, cacheImage) ||TilesVerifier.canReadImage(jpegImageReaders, cacheImage)) { return null; } return String.format("column id: %d", tileId); } catch(final IOException ex) { return ex.getMessage(); } } @Requirement(number = 36, text = "In a GeoPackage that contains a tile pyramid user data table that " + "contains tile data that is not MIME type image png, " + "by default SHALL store that tile data in MIME type image jpeg", severity = Severity.Warning) public void Requirement36() { // This requirement is tested through Requirement 35 test in TilesVerifier. } @Requirement(number = 37, text = "A GeoPackage that contains a tile pyramid user data table SHALL " + "contain gpkg_tile_matrix_set table or view per Table Definition, " + "Tile Matrix Set Table or View Definition and gpkg_tile_matrix_set Table Creation SQL. ", severity = Severity.Error) public void Requirement37() throws AssertionError, SQLException { if(!this.allPyramidUserDataTables.isEmpty()) { Assert.assertTrue(String.format("The GeoPackage does not contain a %1$s. Every GeoPackage with a Pyramid User " + "Data Table must also have a %1$s table.", GeoPackageTiles.MatrixSetTableName), this.hasTileMatrixSetTable); this.verifyTable(TilesVerifier.TileMatrixSetTableDefinition); } } /** * Requirement 38 * * <blockquote> * Values of the <code>gpkg_tile_matrix_set</code> <code>table_name</code> * column SHALL reference values in the gpkg_contents table_name column * for rows with a data type of "tiles". * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement(number = 38, text = "Values of the gpkg_tile_matrix_set table_name column " + "SHALL reference values in the gpkg_contents table_name " + "column for rows with a data type of \"tiles\".", severity = Severity.Warning) public void Requirement38() throws AssertionError { if(this.hasTileMatrixSetTable) { final String queryMatrixSetPyramid = String.format("SELECT table_name FROM %s;", GeoPackageTiles.MatrixSetTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(queryMatrixSetPyramid); ResultSet tileTablesInTileMatrixSet = stmt.executeQuery()) { final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet) .map(resultSet -> { try { return resultSet.getString("table_name"); } catch (final SQLException ex1) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); for(final String table: this.pyramidTablesInContents) { Assert.assertTrue(String.format("The table_name %1$s in the %2$s is not referenced in the gpkg_contents table. Either delete the table %1$s " + "or create a record for that table in the %3$s table", table, GeoPackageTiles.MatrixSetTableName, GeoPackageCore.ContentsTableName), tileMatrixSetTables.contains(table)); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 39 * * <blockquote> * The gpkg_tile_matrix_set table or view SHALL contain one row record for each tile pyramid user data table. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement(number = 39, text = "The gpkg_tile_matrix_set table or view SHALL " + "contain one row record for each tile " + "pyramid user data table. ", severity = Severity.Error) public void Requirement39() throws AssertionError { if (this.hasTileMatrixSetTable) { final String queryMatrixSet = String.format("SELECT table_name FROM %s;", GeoPackageTiles.MatrixSetTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(queryMatrixSet); ResultSet tileTablesInTileMatrixSet = stmt.executeQuery()) { final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet) .map(resultSet -> { try { return resultSet.getString("table_name"); } catch (final SQLException ex1) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); for(final String table: this.allPyramidUserDataTables) { Assert.assertTrue(String.format("The Pyramid User Data Table %s is not referenced in the %s.", table, GeoPackageTiles.MatrixSetTableName), tileMatrixSetTables.contains(table)); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 40 * * <blockquote> * Values of the <code>gpkg_tile_matrix_set </code> <code> srs_id</code> column * SHALL reference values in the <code>gpkg_spatial_ref_sys </code> <code> srs_id</code> column. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 40, text = "Values of the gpkg_tile_matrix_set srs_id column " + "SHALL reference values in the gpkg_spatial_ref_sys srs_id column. ", severity = Severity.Error) public void Requirement40() throws AssertionError { if(this.hasTileMatrixSetTable) { final String query1 = String.format("SELECT srs_id from %s AS tms " + "WHERE srs_id NOT IN" + "(SELECT srs_id " + "FROM %s);", GeoPackageTiles.MatrixSetTableName, GeoPackageCore.SpatialRefSysTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query1); ResultSet unreferencedSRS = stmt.executeQuery()) { if (unreferencedSRS.next()) { Assert.fail(String.format("The %s table contains a reference to an srs_id that is not defined in the %s Table. " + "Unreferenced srs_id: %s", GeoPackageTiles.MatrixSetTableName, GeoPackageCore.SpatialRefSysTableName, unreferencedSRS.getInt("srs_id"))); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } @Requirement (number = 41, text = "A GeoPackage that contains a tile pyramid user data table " + "SHALL contain a gpkg_tile_matrix table or view per clause " + "2.2.7.1.1 Table Definition, Table Tile Matrix Metadata Table " + "or View Definition and Table gpkg_tile_matrix Table Creation SQL. ", severity = Severity.Error) public void Requirement41() throws AssertionError, SQLException { if(!this.allPyramidUserDataTables.isEmpty()) { Assert.assertTrue(String.format("The GeoPackage does not contain a %1$s table. Every GeoPackage with a Pyramid User " + "Data Table must also have a %1$s table.", GeoPackageTiles.MatrixTableName), this.hasTileMatrixTable); this.verifyTable(TilesVerifier.TileMatrixTableDefinition); } } /** * Requirement 42 * * <blockquote> * Values of the <code>gpkg_tile_matrix</code> * <code>table_name</code> column SHALL reference * values in the <code>gpkg_contents</code> <code> * table_name</code> column for rows with a <code> * data_type</code> of 'tiles'. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 42, text = "Values of the gpkg_tile_matrix table_name column " + "SHALL reference values in the gpkg_contents table_name " + "column for rows with a data_type of 'tiles'. ", severity = Severity.Warning) public void Requirement42() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT table_name FROM %s AS tm " + "WHERE table_name NOT IN" + "(SELECT table_name " + "FROM %s AS gc " + "WHERE tm.table_name = gc.table_name AND gc.data_type = 'tiles');", GeoPackageTiles.MatrixTableName, GeoPackageCore.ContentsTableName); try(PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet unreferencedTables = stmt.executeQuery()) { if (unreferencedTables.next()) { Assert.fail(String.format("There are Pyramid user data tables in %s table_name field such that the table_name does not" + " reference values in the %s table_name column for rows with a data type of 'tiles'." + " Unreferenced table: %s", GeoPackageTiles.MatrixTableName, GeoPackageCore.ContentsTableName, unreferencedTables.getString("table_name"))); } } catch (final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 43 * * <blockquote> * The <code>gpkg_tile_matrix</code> table or view SHALL contain one row record for * each zoom level that contains one or more tiles in each tile pyramid user data table or view. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 43, text = "The gpkg_tile_matrix table or view SHALL contain " + "one row record for each zoom level that contains " + "one or more tiles in each tile pyramid user data table or view. ", severity = Severity.Error) public void Requirement43() throws AssertionError { if(this.hasTileMatrixTable) { for (final String tableName : this.allPyramidUserDataTables) { final String query1 = String.format("SELECT DISTINCT zoom_level FROM %s WHERE table_name = ? ORDER BY zoom_level;", GeoPackageTiles.MatrixTableName); final String query2 = String.format("SELECT DISTINCT zoom_level FROM %s ORDER BY zoom_level;", tableName); try (PreparedStatement stmt1 = this.getSqliteConnection().prepareStatement(query1)) { stmt1.setString(1, tableName); try(ResultSet gm_zoomLevels = stmt1.executeQuery(); PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2); ResultSet py_zoomLevels = stmt2.executeQuery()) { final Set<Integer> tileMatrixZooms = ResultSetStream.getStream(gm_zoomLevels) .map(resultSet -> { try { return resultSet.getInt("zoom_level"); } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); final Set<Integer> tilePyramidZooms = ResultSetStream.getStream(py_zoomLevels) .map(resultSet -> { try { return resultSet.getInt("zoom_level"); } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); for(final Integer zoom: tilePyramidZooms) { Assert.assertTrue(String.format("The %s does not contain a row record for zoom level %d in the Pyramid User Data Table %s.", GeoPackageTiles.MatrixTableName, zoom, tableName), tileMatrixZooms.contains(zoom)); } } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } } /** * Requirement 44 * * <blockquote> * The <code>zoom_level</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL not be negative. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 44, text = "The zoom_level column value in a gpkg_tile_matrix table row SHALL not be negative." , severity = Severity.Error) public void Requirement44() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(zoom_level) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minZoom = stmt.executeQuery()) { final int minZoomLevel = minZoom.getInt("min(zoom_level)"); if(!minZoom.wasNull()) { Assert.assertTrue(String.format("The zoom_level in %s must be greater than 0. Invalid zoom_level: %d", GeoPackageTiles.MatrixTableName, minZoomLevel), minZoomLevel >= 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 45 * * <blockquote> * <code>matrix_width</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 45, text = "The matrix_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement45() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(matrix_width) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minMatrixWidthRS = stmt.executeQuery();) { final int minMatrixWidth = minMatrixWidthRS.getInt("min(matrix_width)"); if(!minMatrixWidthRS.wasNull()) { Assert.assertTrue(String.format("The matrix_width in %s must be greater than 0. Invalid matrix_width: %d", GeoPackageTiles.MatrixTableName, minMatrixWidth), minMatrixWidth > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 46 * * <blockquote> * <code>matrix_height</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 46, text = "The matrix_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement46() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(matrix_height) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minMatrixHeightRS = stmt.executeQuery();) { final int minMatrixHeight = minMatrixHeightRS.getInt("min(matrix_height)"); if(!minMatrixHeightRS.wasNull()) { Assert.assertTrue(String.format("The matrix_height in %s must be greater than 0. Invalid matrix_height: %d", GeoPackageTiles.MatrixTableName, minMatrixHeight), minMatrixHeight > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 47 * * <blockquote> * <code>tile_width</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 47, text = "The tile_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement47() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(tile_width) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minTileWidthRS = stmt.executeQuery();) { final int minTileWidth = minTileWidthRS.getInt("min(tile_width)"); if (!minTileWidthRS.wasNull()) { Assert.assertTrue(String.format("The tile_width in %s must be greater than 0. Invalid tile_width: %d", GeoPackageTiles.MatrixTableName, minTileWidth), minTileWidth > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 47 * * <blockquote> * <code>tile_height</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement(number = 48, text = "The tile_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement48() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(tile_height) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minTileHeightRS = stmt.executeQuery();) { final int testMinTileHeight = minTileHeightRS.getInt("min(tile_height)"); if (!minTileHeightRS.wasNull()) { Assert.assertTrue(String.format("The tile_height in %s must be greater than 0. Invalid tile_height: %d", GeoPackageTiles.MatrixTableName, testMinTileHeight), testMinTileHeight > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 49 * * <blockquote> * <code>pixel_x_size</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 49, text = "The pixel_x_size column value in a gpkg_tile_matrix table row SHALL be greater than 0." , severity = Severity.Error) public void Requirement49() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(pixel_x_size) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minPixelXSizeRS = stmt.executeQuery();) { final double minPixelXSize = minPixelXSizeRS.getDouble("min(pixel_x_size)"); if (!minPixelXSizeRS.wasNull()) { Assert.assertTrue(String.format("The pixel_x_size in %s must be greater than 0. Invalid pixel_x_size: %f", GeoPackageTiles.MatrixTableName, minPixelXSize), minPixelXSize > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 50 * * <blockquote> * <code>pixel_y_size</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 50, text = "The pixel_y_size column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement50() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(pixel_y_size) FROM %s;", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query); ResultSet minPixelYSizeRS = stmt.executeQuery();) { final double minPixelYSize = minPixelYSizeRS.getDouble("min(pixel_y_size)"); if (!minPixelYSizeRS.wasNull()) { Assert.assertTrue(String.format("The pixel_y_size in %s must be greater than 0. Invalid pixel_y_size: %f", GeoPackageTiles.MatrixTableName, minPixelYSize), minPixelYSize > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 51 * * <blockquote> * The <code>pixel_x_size</code> and <code>pixel_y_size</code> * column values for <code>zoom_level</code> column values in a * <code>gpkg_tile_matrix</code> table sorted in ascending order * SHALL be sorted in descending order. * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement */ @Requirement (number = 51, text = "The pixel_x_size and pixel_y_size column values for zoom_level " + "column values in a gpkg_tile_matrix table sorted in ascending " + "order SHALL be sorted in descending order.", severity = Severity.Error) public void Requirement51() throws AssertionError { if(this.hasTileMatrixTable) { for (final String pyramidTable : this.allPyramidUserDataTables) { final String query2 = String.format("SELECT pixel_x_size, pixel_y_size " + "FROM %s WHERE table_name = ? ORDER BY zoom_level ASC;", GeoPackageTiles.MatrixTableName); Double pixelX2 = null; Double pixelY2 = null; try (PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2)) { stmt2.setString(1, pyramidTable); try(ResultSet zoomPixxPixy = stmt2.executeQuery()) { while (zoomPixxPixy.next()) { final Double pixelX = zoomPixxPixy.getDouble("pixel_x_size"); final Double pixelY = zoomPixxPixy.getDouble("pixel_y_size"); if (pixelX2 != null && pixelY2 != null) { Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while " + "the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.", pixelX.toString(), pixelY.toString()), pixelX2 > pixelX && pixelY2 > pixelY); pixelX2 = pixelX; pixelY2 = pixelY; } else if (zoomPixxPixy.next()) { pixelX2 = zoomPixxPixy.getDouble("pixel_x_size"); pixelY2 = zoomPixxPixy.getDouble("pixel_y_size"); Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while " + "the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.", pixelX2.toString(), pixelY2.toString()), pixelX > pixelX2 && pixelY > pixelY2); } } } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } } @Requirement (number = 52, text = "Each tile matrix set in a GeoPackage SHALL " + "be stored in a different tile pyramid user " + "data table or updateable view with a unique " + "name that SHALL have a column named \"id\" with" + " column type INTEGER and PRIMARY KEY AUTOINCREMENT" + " column constraints per Clause 2.2.8.1.1 Table Definition," + " Tiles Table or View Definition and EXAMPLE: tiles table " + "Insert Statement (Informative). ", severity = Severity.Error) public void Requirement52() throws AssertionError, SQLException { //verify the tables are defined correctly for(final String table: this.pyramidTablesInContents) { if(DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), table)) { this.verifyTable(new TilePyramidUserDataTableDefinition(table)); } else { throw new AssertionError(String.format("The tiles table %1$s does not exist even though it is defined in the %2$s table. " + "Either create the table %1$s or delete the record in %2$s table referring to table %1$s.", table, GeoPackageCore.ContentsTableName)); } } //Ensure that the pyramid tables are referenced in tile matrix set if(this.hasTileMatrixSetTable) { final String query2 = String.format("SELECT DISTINCT table_name " + "FROM %s WHERE data_type = 'tiles' " + "AND table_name NOT IN" + " (SELECT DISTINCT table_name " + " FROM %s);", GeoPackageCore.ContentsTableName, GeoPackageTiles.MatrixSetTableName); try(PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2); ResultSet unreferencedPyramidTableInTMS = stmt2.executeQuery()) { //verify that all the pyramid user data tables are referenced in the Tile Matrix Set table if(unreferencedPyramidTableInTMS.next()) { Assert.fail(String.format("There are Pyramid User Data Tables that do not contain a record in the %s." + " Unreferenced Pyramid table: %s", GeoPackageTiles.MatrixSetTableName, unreferencedPyramidTableInTMS.getString("table_name"))); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * Requirement 53 * * <blockquote> * For each distinct <code>table_name</code> from the <code>gpkg_tile_matrix</code> * (tm) table, the tile pyramid (tp) user data table <code>zoom_level</code> * column value in a GeoPackage SHALL be in the range min(tm.zoom_level) <= tp.zoom_level <= max(tm.zoom_level). * </blockquote> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement * @throws SQLException throws if an SQLException occurs */ @Requirement (number = 53, text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, " + "the tile pyramid (tp) user data table zoom_level column value in a " + "GeoPackage SHALL be in the range min(tm.zoom_level) less than or equal " + "to tp.zoom_level less than or equal to max(tm.zoom_level).", severity = Severity.Error) public void Requirement53() throws AssertionError, SQLException { if(this.hasTileMatrixTable) { for(final String pyramidName: this.pyramidTablesInTileMatrix) { final String query2 = String.format("SELECT MIN(zoom_level) AS min_gtm_zoom, MAX(zoom_level) " + "AS max_gtm_zoom FROM %s WHERE table_name = ?", GeoPackageTiles.MatrixTableName); try (PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2)) { stmt2.setString(1, pyramidName); try(ResultSet minMaxZoom = stmt2.executeQuery()) { final int minZoom = minMaxZoom.getInt("min_gtm_zoom"); final int maxZoom = minMaxZoom.getInt("max_gtm_zoom"); if (!minMaxZoom.wasNull()) { final String query3 = String.format("SELECT id FROM %s WHERE zoom_level < ? OR zoom_level > ?", pyramidName); try (PreparedStatement stmt3 = this.getSqliteConnection().prepareStatement(query3)) { stmt3.setInt(1, minZoom); stmt3.setInt(2, maxZoom); try(ResultSet invalidZooms = stmt3.executeQuery()) { if (invalidZooms.next()) { Assert.fail(String.format("There are zoom_levels in the Pyramid User Data Table: %1$s such that the zoom level " + "is bigger than the maximum zoom level: %2$d or smaller than the minimum zoom_level: %3$d" + " that was determined by the %4$s Table. Invalid tile with an id of %5$d from table %6$s", pyramidName, maxZoom, minZoom, GeoPackageTiles.MatrixTableName, invalidZooms.getInt("id"), pyramidName)); } } } } } } } } } /** * Requirement 54 * * <blockquote> For each distinct * <code>table_name</code> from the <code>gpkg_tile_matrix</code> (tm) * table, the tile pyramid (tp) user data table <code>tile_column</code> * column value in a GeoPackage SHALL be in the range 0 <= tp.tile_column <= * tm.matrix_width 1 where the tm and tp <code>zoom_level</code> column * values are equal. </blockquote> </div> * * @throws AssertionError throws if the GeoPackage fails to meet the requirement * @throws SQLException throws if an SQLException occurs */ @Requirement(number = 54, text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, " + "the tile pyramid (tp) user data table tile_column column value in a " + "GeoPackage SHALL be in the range 0 <= tp.tile_column <= tm.matrix_width - 1 " + "where the tm and tp zoom_level column values are equal. ", severity = Severity.Warning) public void Requirement54() throws AssertionError, SQLException { if (this.hasTileMatrixTable) { for(final String pyramidName : this.pyramidTablesInTileMatrix) { // this query will only pull the incorrect values for the // pyramid user data table's column width, the value // of the tile_column value for the pyramid user data table // SHOULD be null otherwise those fields are in violation // of the range final String query2 = String.format("SELECT zoom_level as zl, " + "matrix_width as width " + "FROM %1$s " + "WHERE table_name = ? " + "AND" + "(" + "zoom_level in (SELECT zoom_level FROM %2$s WHERE tile_column < 0) " + "OR " + "(" + "EXISTS(SELECT NULL FROM %2$s WHERE zoom_level = zl AND tile_column > width - 1)" + " )" + " );", GeoPackageTiles.MatrixTableName, pyramidName); try (PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2)) { stmt2.setString(1, pyramidName); try(ResultSet incorrectColumns = stmt2.executeQuery()) { final List<TileData> incorrectColumnSet = ResultSetStream.getStream(incorrectColumns) .map(resultSet -> { try { final TileData tileData = new TileData(); tileData.matrixWidth = resultSet.getInt("width"); tileData.zoomLevel = resultSet.getInt("zl"); return tileData; } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); Assert.assertTrue(String.format("The table '%s' there are tiles with a tile_column values oustide the ranges for a particular zoom_level. \n%s", pyramidName, incorrectColumnSet.stream() .map(tileData -> String.format("\tZoom level %d Expected Range tile_column: [0, %d].", tileData.zoomLevel, tileData.matrixWidth -1)) .collect(Collectors.joining("\n"))), incorrectColumnSet.isEmpty()); } } } //TODO this test will be moved in a later release to its own individual test, this is not necessarily part of this requirement (wording is below requirement 37 but this is closest to what we are checking). for(final String pyramidTable: this.allPyramidUserDataTables) { final String query1 = String.format("SELECT MIN(tile_column), MIN(tile_row), MAX(tile_row), MAX(tile_column) FROM %s WHERE zoom_level = (SELECT MIN(zoom_level) FROM %s);", pyramidTable, pyramidTable); try(PreparedStatement stmt1 = this.getSqliteConnection().prepareStatement(query1); ResultSet minXMaxXMinYMaxYRS = stmt1.executeQuery()) { final int minX = minXMaxXMinYMaxYRS.getInt("MIN(tile_column)");//this should always be 0 final int minY = minXMaxXMinYMaxYRS.getInt("MIN(tile_row)"); //this should always be 0 final int maxX = minXMaxXMinYMaxYRS.getInt("MAX(tile_column)"); final int maxY = minXMaxXMinYMaxYRS.getInt("MAX(tile_row)"); final String query2 = String.format("SELECT matrix_width, matrix_height, zoom_level FROM %s WHERE table_name = ? AND zoom_level = (SELECT MIN(zoom_level) FROM %s)", GeoPackageTiles.MatrixTableName, pyramidTable, pyramidTable); try(PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2)) { stmt2.setString(1, pyramidTable); try(ResultSet dimensionsRS = stmt2.executeQuery()) { while(dimensionsRS.next()) { final int matrixWidth = dimensionsRS.getInt("matrix_width"); final int matrixHeight = dimensionsRS.getInt("matrix_height"); final int zoomLevel = dimensionsRS.getInt("zoom_level"); Assert.assertTrue(String.format("\nNote: This next message is an additional concern that is related to this requirement but not the requirement itself. "+ "The BoundingBox in %s does not define the minimum bounding box for all content in the table %s.\n" + "\tActual Values:\n\t\tMIN(tile_column): %4d,\n\t\tMIN(tile_row): %4d,\n\t\tMAX(tile_column): %4d,\n\t\tMAX(tile_row): %4d.\n\n" + "\tExpected values:\n\t\tMIN(tile_column): 0,\n\t\tMIN(tile_row): 0,\n\t\tMAX(tile_column): %4d (matrix_width -1),\n\t\tMAX(tile_row): %4d (matrix_height -1)." + "\n\n\tExpected values based on the Tile Matrix given at the MIN(zoom_level) %d.", GeoPackageTiles.MatrixSetTableName, pyramidTable, minX, minY, maxX, maxY, matrixWidth - 1, matrixHeight - 1, zoomLevel), minX == 0 && minY == 0 && maxX == (matrixWidth - 1) && maxY == (matrixHeight - 1)); } } } } } } } @Requirement (number = 55, text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, the tile pyramid (tp) " + "user data table tile_row column value in a GeoPackage SHALL be in the range 0 <= tp.tile_row <= tm.matrix_height - 1 " + "where the tm and tp zoom_level column values are equal. ", severity = Severity.Warning) public void Requirement55() throws AssertionError, SQLException { if (this.hasTileMatrixTable) { for(final String pyramidName: this.pyramidTablesInTileMatrix) { // this query will only pull the incorrect values for the // pyramid user data table's column height, the value // of the tile_row value for the pyramid user data table // SHOULD be null otherwise those fields are in violation // of the range final String query2 = String.format("SELECT zoom_level as zl, " + "matrix_height as height " + "FROM %1$s " + "WHERE table_name = ? " + "AND" + "(" + "zoom_level in (SELECT zoom_level FROM %2$s WHERE tile_row < 0) " + "OR " + "(" + "EXISTS(SELECT NULL FROM %2$s WHERE zoom_level = zl AND tile_row > height - 1)" + " )" + " );", GeoPackageTiles.MatrixTableName, pyramidName); try (PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2)) { stmt2.setString(1, pyramidName); try(ResultSet incorrectTileRow = stmt2.executeQuery()) { final List<TileData> incorrectTileRowSet = ResultSetStream.getStream(incorrectTileRow) .map(resultSet -> { try { final TileData tileData = new TileData(); tileData.matrixHeight = resultSet.getInt("height"); tileData.zoomLevel = resultSet.getInt("zl"); return tileData; } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); Assert.assertTrue(String.format("The table '%s' there are tiles with a tile_row values oustide the ranges for a particular zoom_level. \n%s", pyramidName, incorrectTileRowSet.stream() .map(tileData -> String.format("\tZoom level %d Expected Range tile_row: [0, %d].", tileData.zoomLevel, tileData.matrixHeight -1)) .collect(Collectors.joining("\n"))), incorrectTileRowSet.isEmpty()); } } } } } private static boolean validPixelValues(final TileData tileData, final BoundingBox boundingBox) { return isEqual(tileData.pixelXSize, (boundingBox.getWidth() / tileData.matrixWidth) / tileData.tileWidth) && isEqual(tileData.pixelYSize, (boundingBox.getHeight() / tileData.matrixHeight) / tileData.tileHeight); } /** * This method determines if the two doubles are * equal based upon the maximum level of allowable * differenced determined by the Epsilon value 0.001 * @param first * @param second * @return */ private static boolean isEqual(final double first, final double second) { return Math.abs(first - second) < TilesVerifier.EPSILON; } private static <T> Collection<T> iteratorToCollection(final Iterator<T> iterator) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) .collect(Collectors.toCollection(ArrayList::new)); } /** * This Verifies if the Tile Matrix Table exists. * @return true if the gpkg_tile_matrix table exists * @throws AssertionError throws an assertion error if the gpkg_tile_matrix table * doesn't exist and the GeoPackage contains a tiles table */ private boolean tileMatrixTableExists() throws SQLException { return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixTableName); } /** * This Verifies if the Tile Matrix Set Table exists in the * GeoPackage. * @return true if the gpkg_tile_matrix Set table exists * @throws AssertionError throws an assertion error if the gpkg_tile_matrix_set table * doesn't exist and the GeoPackage contains a tiles table * @throws SQLException */ private boolean tileMatrixSetTableExists() throws SQLException { return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixSetTableName); } private static boolean canReadImage(final Collection<ImageReader> imageReaders, final ImageInputStream image) { return imageReaders.stream() .anyMatch(imageReader -> { try { image.mark(); return imageReader.getOriginatingProvider().canDecodeInput(image); } catch(final Exception ex) { return false; } finally { try { image.reset(); } catch (final Exception e) { e.printStackTrace(); } } }); } private class TileData implements Comparable<TileData> { int matrixWidth; int matrixHeight; int zoomLevel; Integer tileID; double pixelXSize; double pixelYSize; int tileWidth; int tileHeight; @Override public int compareTo(final TileData other) { return this.tileID.compareTo(other.tileID); } } private Set<String> allPyramidUserDataTables; private Set<String> pyramidTablesInContents; private Set<String> pyramidTablesInTileMatrix; private boolean hasTileMatrixTable; private boolean hasTileMatrixSetTable; private static final TableDefinition TileMatrixSetTableDefinition; private static final TableDefinition TileMatrixTableDefinition; private static final Collection<ImageReader> jpegImageReaders; private static final Collection<ImageReader> pngImageReaders; static { jpegImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/jpeg")); pngImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/png")); final Map<String, ColumnDefinition> tileMatrixSetColumns = new HashMap<>(); tileMatrixSetColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null)); tileMatrixSetColumns.put("srs_id", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixSetColumns.put("min_x", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixSetColumns.put("min_y", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixSetColumns.put("max_x", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixSetColumns.put("max_y", new ColumnDefinition("DOUBLE", true, false, false, null)); TileMatrixSetTableDefinition = new TableDefinition(GeoPackageTiles.MatrixSetTableName, tileMatrixSetColumns, new HashSet<>(Arrays.asList(new ForeignKeyDefinition(GeoPackageCore.SpatialRefSysTableName, "srs_id", "srs_id"), new ForeignKeyDefinition(GeoPackageCore.ContentsTableName, "table_name", "table_name")))); final Map<String, ColumnDefinition> tileMatrixColumns = new HashMap<>(); tileMatrixColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null)); tileMatrixColumns.put("zoom_level", new ColumnDefinition("INTEGER", true, true, true, null)); tileMatrixColumns.put("matrix_width", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("matrix_height", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("tile_width", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("tile_height", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("pixel_x_size", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixColumns.put("pixel_y_size", new ColumnDefinition("DOUBLE", true, false, false, null)); TileMatrixTableDefinition = new TableDefinition(GeoPackageTiles.MatrixTableName, tileMatrixColumns, new HashSet<>(Arrays.asList(new ForeignKeyDefinition(GeoPackageCore.ContentsTableName, "table_name", "table_name")))); } }
package com.intellij.psi.util; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.PsiElementProcessor.CollectElements; import com.intellij.psi.search.PsiElementProcessor.CollectFilteredElements; import com.intellij.psi.search.PsiElementProcessor.FindElement; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.templateLanguages.OuterLanguageElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.PairProcessor; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Predicate; public class PsiTreeUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.util.PsiTreeUtil"); private static final Key<Object> MARKER = Key.create("PsiTreeUtil.copyElements.MARKER"); @SuppressWarnings("unchecked") private static final Class<? extends PsiElement>[] WS = new Class[]{PsiWhiteSpace.class}; @SuppressWarnings("unchecked") private static final Class<? extends PsiElement>[] WS_COMMENTS = new Class[]{PsiWhiteSpace.class, PsiComment.class}; /** * Checks whether one element in the psi tree is under another. * * @param ancestor parent candidate. {@code false} will be returned if ancestor is null. * @param element child candidate * @param strict whether return true if ancestor and parent are the same. * @return true if element has ancestor as its parent somewhere in the hierarchy and false otherwise. */ @Contract("null, _, _ -> false") public static boolean isAncestor(@Nullable PsiElement ancestor, @NotNull PsiElement element, boolean strict) { if (ancestor == null) return false; // fast path to avoid loading tree if (ancestor instanceof StubBasedPsiElement && ((StubBasedPsiElement)ancestor).getStub() != null || element instanceof StubBasedPsiElement && ((StubBasedPsiElement)element).getStub() != null) { if (ancestor.getContainingFile() != element.getContainingFile()) return false; } boolean stopAtFileLevel = !(ancestor instanceof PsiFile || ancestor instanceof PsiDirectory); PsiElement parent = strict ? element.getParent() : element; while (true) { if (parent == null) return false; if (parent.equals(ancestor)) return true; if (stopAtFileLevel && parent instanceof PsiFile) return false; parent = parent.getParent(); } } /** * Checks whether one element in the psi tree is under another in {@link PsiElement#getContext()} hierarchy. * * @param ancestor parent candidate. {@code false} will be returned if ancestor is null. * @param element child candidate * @param strict whether return true if ancestor and parent are the same. * @return true if element has ancestor as its parent somewhere in the hierarchy and false otherwise. */ @Contract("null, _, _ -> false") public static boolean isContextAncestor(@Nullable PsiElement ancestor, @NotNull PsiElement element, boolean strict) { if (ancestor == null) return false; boolean stopAtFileLevel = !(ancestor instanceof PsiFile || ancestor instanceof PsiDirectory); PsiElement parent = strict ? element.getContext() : element; while (true) { if (parent == null) return false; if (parent.equals(ancestor)) return true; if (stopAtFileLevel && parent instanceof PsiFile) { final PsiElement context = parent.getContext(); if (context == null) return false; } parent = parent.getContext(); } } @Nullable public static PsiElement findCommonParent(@NotNull List<? extends PsiElement> elements) { if (elements.isEmpty()) return null; PsiElement toReturn = null; for (PsiElement element : elements) { if (element == null) continue; toReturn = toReturn == null ? element : findCommonParent(toReturn, element); if (toReturn == null) return null; } return toReturn; } @Nullable public static PsiElement findCommonParent(@NotNull PsiElement... elements) { if (elements.length == 0) return null; PsiElement toReturn = null; for (PsiElement element : elements) { if (element == null) continue; toReturn = toReturn == null ? element : findCommonParent(toReturn, element); if (toReturn == null) return null; } return toReturn; } @Nullable public static PsiElement findCommonParent(@NotNull PsiElement element1, @NotNull PsiElement element2) { // optimization if (element1 == element2) return element1; PsiFile file1 = element1.getContainingFile(); PsiFile file2 = element2.getContainingFile(); PsiElement topLevel = file1 == file2 ? file1 : null; int depth1 = getDepth(element1, topLevel); int depth2 = getDepth(element2, topLevel); PsiElement parent1 = element1; PsiElement parent2 = element2; while (depth1 > depth2) { parent1 = parent1.getParent(); depth1 } while (depth2 > depth1) { parent2 = parent2.getParent(); depth2 } while (parent1 != null && parent2 != null && !parent1.equals(parent2)) { parent1 = parent1.getParent(); parent2 = parent2.getParent(); } return parent1; } @Contract(pure = true) private static int getDepth(@NotNull PsiElement element, @Nullable PsiElement topLevel) { int depth=0; PsiElement parent = element; while (parent != topLevel && parent != null) { depth++; parent = parent.getParent(); } return depth; } @Nullable public static PsiElement findCommonContext(@NotNull Collection<? extends PsiElement> elements) { if (elements.isEmpty()) return null; PsiElement toReturn = null; for (PsiElement element : elements) { if (element == null) continue; toReturn = toReturn == null ? element : findCommonContext(toReturn, element); if (toReturn == null) return null; } return toReturn; } @Nullable public static PsiElement findCommonContext(@NotNull PsiElement element1, @NotNull PsiElement element2) { // optimization if (element1 == element2) return element1; final PsiFile containingFile = element1.getContainingFile(); final PsiElement topLevel = containingFile == element2.getContainingFile() ? containingFile : null; int depth1 = getContextDepth(element1, topLevel); int depth2 = getContextDepth(element2, topLevel); PsiElement parent1 = element1; PsiElement parent2 = element2; while(depth1 > depth2 && parent1 != null) { parent1 = parent1.getContext(); depth1 } while(depth2 > depth1 && parent2 != null) { parent2 = parent2.getContext(); depth2 } while(parent1 != null && parent2 != null && !parent1.equals(parent2)) { parent1 = parent1.getContext(); parent2 = parent2.getContext(); } return parent1; } private static int getContextDepth(@NotNull PsiElement element, @Nullable PsiElement topLevel) { int depth=0; PsiElement parent = element; while (parent != topLevel && parent != null) { depth++; parent = parent.getContext(); } return depth; } /** See {@link #findChildOfType(PsiElement, Class, boolean, Class)}. */ @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T findChildOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) { return findChildOfType(element, aClass, true, null); } /** See {@link #findChildOfType(PsiElement, Class, boolean, Class)}. */ @Nullable @Contract("null, _, _ -> null") public static <T extends PsiElement> T findChildOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, boolean strict) { return findChildOfType(element, aClass, strict, null); } /** * Recursive (depth first) search for first element of a given class. * * @param element a PSI element to start search from * @param strict if false the {@code element} is also included in the search * @param aClass element type to search for * @param stopAt element type to abort the search at * @param <T> type to cast found element to * @return first found element, or {@code null} if nothing found */ @Nullable @Contract("null, _, _, _ -> null") public static <T extends PsiElement> T findChildOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, boolean strict, @Nullable Class<? extends PsiElement> stopAt) { if (element == null) return null; FindElement<PsiElement> processor = new PsiElementProcessor.FindElement<PsiElement>() { @Override public boolean execute(@NotNull PsiElement each) { if (strict && each == element) return true; if (aClass.isInstance(each)) return setFound(each); return stopAt == null || !stopAt.isInstance(each); } }; processElements(element, processor); return aClass.cast(processor.getFoundElement()); } /** See {@link #findChildOfAnyType(PsiElement, boolean, Class[])}. */ @SafeVarargs @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T findChildOfAnyType(@Nullable PsiElement element, @NotNull Class<? extends T>... classes) { return findChildOfAnyType(element, true, classes); } /** * Recursive (depth first) search for first element of any of given {@code classes}. * * @param element a PSI element to start search from. * @param strict if false the {@code element} is also included in the search. * @param classes element types to search for. * @param <T> type to cast found element to. * @return first found element, or {@code null} if nothing found. */ @SafeVarargs @Nullable @Contract("null, _, _ -> null") public static <T extends PsiElement> T findChildOfAnyType(@Nullable PsiElement element, boolean strict, @NotNull Class<? extends T>... classes) { if (element == null) return null; FindElement<PsiElement> processor = new FindElement<PsiElement>() { @Override public boolean execute(@NotNull PsiElement each) { if (strict && each == element) return true; if (instanceOf(each, classes)) { return setFound(each); } return true; } }; processElements(element, processor); @SuppressWarnings("unchecked") T t = (T)processor.getFoundElement(); return t; } /** See {@link #findChildrenOfAnyType(PsiElement, boolean, Class[])}. */ @NotNull public static <T extends PsiElement> Collection<T> findChildrenOfType(@Nullable PsiElement element, @NotNull Class<? extends T> aClass) { return findChildrenOfAnyType(element, true, aClass); } /** See {@link #findChildrenOfAnyType(PsiElement, boolean, Class[])}. */ @SafeVarargs @NotNull public static <T extends PsiElement> Collection<T> findChildrenOfAnyType(@Nullable PsiElement element, @NotNull Class<? extends T>... classes) { return findChildrenOfAnyType(element, true, classes); } /** * Recursive (depth first) search for all elements of any of given {@code classes}. * * @param element a PSI element to start search from. * @param strict if false the {@code element} is also included in the search. * @param classes element types to search for. * @param <T> type to cast found elements to. * @return {@code Collection<T>} of all found elements, or empty {@code List<T>} if nothing found. */ @SafeVarargs @NotNull public static <T extends PsiElement> Collection<T> findChildrenOfAnyType(@Nullable PsiElement element, boolean strict, @NotNull Class<? extends T>... classes) { if (element == null) return ContainerUtil.emptyList(); CollectElements<T> processor = new CollectElements<T>() { @Override public boolean execute(@NotNull T each) { if (strict && each == element) return true; if (instanceOf(each, classes)) { return super.execute(each); } return true; } }; processElements(element, processor); return processor.getCollection(); } /** * Non-recursive search for element of type T amongst given {@code element} children. * * @param element a PSI element to start search from. * @param aClass element type to search for. * @param <T> element type to search for. * @return first found element, or null if nothing found. */ @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getChildOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) { if (element == null) return null; for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (aClass.isInstance(child)) { return aClass.cast(child); } } return null; } @Nullable public static PsiElement findFirstParent(@Nullable PsiElement element, Condition<? super PsiElement> condition) { return findFirstParent(element, false, condition); } @Nullable public static PsiElement findFirstParent(@Nullable PsiElement element, boolean strict, Condition<? super PsiElement> condition) { if (strict && element != null) { element = element.getParent(); } while (element != null) { if (condition.value(element)) { return element; } element = element.getParent(); } return null; } @Nullable public static PsiElement findFirstContext(@Nullable PsiElement element, boolean strict, Condition<? super PsiElement> condition) { if (strict && element != null) { element = element.getContext(); } while (element != null) { if (condition.value(element)) { return element; } element = element.getContext(); } return null; } @NotNull public static <T extends PsiElement> T getRequiredChildOfType(@NotNull PsiElement element, @NotNull Class<T> aClass) { final T child = getChildOfType(element, aClass); assert child != null : "Missing required child of type " + aClass.getName(); return child; } public static int countChildrenOfType(@NotNull PsiElement element, @NotNull Class<? extends PsiElement> clazz) { int result = 0; for (PsiElement cur = element.getFirstChild(); cur != null; cur = cur.getNextSibling()) { if (clazz.isInstance(cur)) { result++; } } return result; } @Nullable public static <T extends PsiElement> T[] getChildrenOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) { if (element == null) return null; List<T> result = getChildrenOfTypeAsList(element, aClass); return result.isEmpty() ? null : ArrayUtil.toObjectArray(result, aClass); } @SafeVarargs @NotNull public static <T extends PsiElement> List<T> getChildrenOfAnyType(@Nullable PsiElement element, @NotNull Class<? extends T>... classes) { if (element == null) return ContainerUtil.emptyList(); List<T> result = null; for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (instanceOf(child, classes)) { if (result == null) result = ContainerUtil.newSmartList(); @SuppressWarnings("unchecked") T t = (T)child; result.add(t); } } if (result == null) { return ContainerUtil.emptyList(); } return result; } @NotNull public static <T extends PsiElement> List<T> getChildrenOfTypeAsList(@Nullable PsiElement element, @NotNull Class<? extends T> aClass) { if (element == null) return Collections.emptyList(); List<T> result = null; for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (aClass.isInstance(child)) { if (result == null) result = new SmartList<>(); result.add(aClass.cast(child)); } } return result == null ? Collections.emptyList() : result; } @NotNull public static List<PsiElement> getElementsOfRange(@NotNull PsiElement start, @NotNull PsiElement end) { List<PsiElement> result = new ArrayList<>(); for (PsiElement e = start; e != end; e = e.getNextSibling()) { if (e == null) throw new IllegalArgumentException("Invalid range: " + start + ".." + end); result.add(e); } result.add(end); return result; } @Nullable public static <T extends PsiElement> T getStubChildOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) { if (element == null) return null; StubElement<?> stub = element instanceof StubBasedPsiElement ? ((StubBasedPsiElement)element).getStub() : null; if (stub == null) { return getChildOfType(element, aClass); } for (StubElement childStub : stub.getChildrenStubs()) { PsiElement child = childStub.getPsi(); if (aClass.isInstance(child)) { return aClass.cast(child); } } return null; } @NotNull public static <T extends PsiElement> List<T> getStubChildrenOfTypeAsList(@Nullable PsiElement element, @NotNull Class<? extends T> aClass) { if (element == null) return Collections.emptyList(); StubElement<?> stub = element instanceof StubBasedPsiElement ? ((StubBasedPsiElement)element).getStub() : null; if (stub == null) { return getChildrenOfTypeAsList(element, aClass); } List<T> result = new SmartList<>(); for (StubElement childStub : stub.getChildrenStubs()) { PsiElement child = childStub.getPsi(); if (aClass.isInstance(child)) { result.add(aClass.cast(child)); } } return result; } public static boolean instanceOf(Object object, Class<?>... classes) { if (object != null && classes != null) { for (Class<?> c : classes) { if (c.isInstance(object)) return true; } } return false; } /** * Returns a direct child of the specified element which has any of the specified classes. * * @param element the element to get the child for. * @param classes the array of classes. * @return the element, or null if none was found. */ @SafeVarargs @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getChildOfAnyType(@Nullable PsiElement element, @NotNull Class<? extends T>... classes) { if (element == null) return null; for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { for (Class<? extends T> aClass : classes) { if (aClass.isInstance(child)) { return aClass.cast(child); } } } return null; } @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getNextSiblingOfType(@Nullable PsiElement sibling, @NotNull Class<T> aClass) { if (sibling == null) return null; for (PsiElement child = sibling.getNextSibling(); child != null; child = child.getNextSibling()) { if (aClass.isInstance(child)) { return aClass.cast(child); } } return null; } @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getPrevSiblingOfType(@Nullable PsiElement sibling, @NotNull Class<T> aClass) { if (sibling == null) return null; for (PsiElement child = sibling.getPrevSibling(); child != null; child = child.getPrevSibling()) { if (aClass.isInstance(child)) { return aClass.cast(child); } } return null; } @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getTopmostParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) { T answer = getParentOfType(element, aClass); do { T next = getParentOfType(answer, aClass); if (next == null) break; answer = next; } while (true); return answer; } @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass) { return getParentOfType(element, aClass, true); } @Nullable @Contract("null -> null") public static PsiElement getStubOrPsiParent(@Nullable PsiElement element) { if (element instanceof StubBasedPsiElement) { StubElement stub = ((StubBasedPsiElement<?>)element).getStub(); if (stub != null) { final StubElement parentStub = stub.getParentStub(); return parentStub != null ? parentStub.getPsi() : null; } } return element != null ? element.getParent() : null; } @Nullable @Contract("null, _ -> null") public static <E extends PsiElement> E getStubOrPsiParentOfType(@Nullable PsiElement element, @NotNull Class<E> parentClass) { if (element instanceof StubBasedPsiElement) { StubElement<?> stub = ((StubBasedPsiElement<?>)element).getStub(); if (stub != null) { return stub.getParentStubOfType(parentClass); } } return getParentOfType(element, parentClass); } @SafeVarargs @Nullable @Contract("null, _, _, _ -> null") public static <T extends PsiElement> T getContextOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, boolean strict, Class<? extends PsiElement>... stopAt) { if (element == null) return null; if (strict) { element = element.getContext(); } while (element != null && !aClass.isInstance(element)) { if (instanceOf(element, stopAt)) return null; element = element.getContext(); } return aClass.cast(element); } @Nullable @Contract("null, _, _ -> null") public static <T extends PsiElement> T getContextOfType(@Nullable PsiElement element, @NotNull Class<? extends T> aClass, boolean strict) { return getContextOfType(element, strict, aClass); } @SafeVarargs @Nullable public static <T extends PsiElement> T getContextOfType(@Nullable PsiElement element, @NotNull Class<? extends T>... classes) { return getContextOfType(element, true, classes); } @SafeVarargs @Nullable @Contract("null, _, _ -> null") public static <T extends PsiElement> T getContextOfType(@Nullable PsiElement element, boolean strict, @NotNull Class<? extends T>... classes) { if (element == null) return null; if (strict) { element = element.getContext(); } while (element != null && !instanceOf(element, classes)) { element = element.getContext(); } @SuppressWarnings("unchecked") T t = (T)element; return t; } @Nullable @Contract("null, _, _ -> null") public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, boolean strict) { return getParentOfType(element, aClass, strict, -1); } @Contract("null, _, _, _ -> null") public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, boolean strict, int minStartOffset) { if (element == null) { return null; } if (strict) { if (element instanceof PsiFile) { return null; } element = element.getParent(); } while (element != null && (minStartOffset == -1 || element.getNode().getStartOffset() >= minStartOffset)) { if (aClass.isInstance(element)) { return aClass.cast(element); } if (element instanceof PsiFile) { return null; } element = element.getParent(); } return null; } @SafeVarargs @Nullable @Contract("null, _, _, _ -> null") public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, boolean strict, @NotNull Class<? extends PsiElement>... stopAt) { if (element == null) return null; if (strict) { if (element instanceof PsiFile) return null; element = element.getParent(); } while (element != null && !aClass.isInstance(element)) { if (instanceOf(element, stopAt)) return null; if (element instanceof PsiFile) return null; element = element.getParent(); } return aClass.cast(element); } @NotNull public static <T extends PsiElement> List<T> collectParents(@NotNull PsiElement element, @NotNull Class<? extends T> parent, boolean includeMyself, @NotNull Predicate<? super PsiElement> stopCondition) { if (!includeMyself) { element = element.getParent(); } List<T> parents = new SmartList<>(); while (element != null) { if (stopCondition.test(element)) break; if (parent.isInstance(element)) { parents.add(parent.cast(element)); } element = element.getParent(); } return parents; } @Nullable public static PsiElement findSiblingForward(@NotNull final PsiElement element, @NotNull final IElementType elementType, @Nullable final Consumer<? super PsiElement> consumer) { return findSiblingForward(element, elementType, true, consumer); } @Nullable public static PsiElement findSiblingForward(@NotNull final PsiElement element, @NotNull final IElementType elementType, boolean strict, @Nullable final Consumer<? super PsiElement> consumer) { for (PsiElement e = strict ? element.getNextSibling() : element; e != null; e = e.getNextSibling()) { if (elementType.equals(e.getNode().getElementType())) { return e; } if (consumer != null) consumer.consume(e); } return null; } @Nullable public static PsiElement findSiblingBackward(@NotNull final PsiElement element, @NotNull final IElementType elementType, @Nullable final Consumer<? super PsiElement> consumer) { return findSiblingBackward(element, elementType, true, consumer); } @Nullable public static PsiElement findSiblingBackward(@NotNull final PsiElement element, @NotNull final IElementType elementType, boolean strict, @Nullable final Consumer<? super PsiElement> consumer) { for (PsiElement e = strict ? element.getPrevSibling() : element; e != null; e = e.getPrevSibling()) { if (elementType.equals(e.getNode().getElementType())) { return e; } if (consumer != null) consumer.consume(e); } return null; } @SafeVarargs @Nullable @Contract("null, _ -> null") public static PsiElement skipSiblingsForward(@Nullable PsiElement element, @NotNull Class<? extends PsiElement>... elementClasses) { if (element == null) return null; for (PsiElement e = element.getNextSibling(); e != null; e = e.getNextSibling()) { if (!instanceOf(e, elementClasses)) { return e; } } return null; } @Nullable @Contract("null -> null") public static PsiElement skipWhitespacesForward(@Nullable PsiElement element) { return skipSiblingsForward(element, WS); } @Nullable @Contract("null -> null") public static PsiElement skipWhitespacesAndCommentsForward(@Nullable PsiElement element) { return skipSiblingsForward(element, WS_COMMENTS); } @SafeVarargs @Nullable @Contract("null, _ -> null") public static PsiElement skipSiblingsBackward(@Nullable PsiElement element, @NotNull Class<? extends PsiElement>... elementClasses) { if (element == null) return null; for (PsiElement e = element.getPrevSibling(); e != null; e = e.getPrevSibling()) { if (!instanceOf(e, elementClasses)) { return e; } } return null; } @Nullable @Contract("null -> null") public static PsiElement skipWhitespacesBackward(@Nullable PsiElement element) { return skipSiblingsBackward(element, WS); } @Nullable @Contract("null -> null") public static PsiElement skipWhitespacesAndCommentsBackward(@Nullable PsiElement element) { return skipSiblingsBackward(element, WS_COMMENTS); } @SafeVarargs @Nullable @Contract("null, _ -> null") public static PsiElement skipParentsOfType(@Nullable PsiElement element, @NotNull Class<? extends PsiElement>... parentClasses) { if (element == null) return null; for (PsiElement e = element.getParent(); e != null; e = e.getParent()) { if (!instanceOf(e, parentClasses)) { return e; } } return null; } @SafeVarargs @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getParentOfType(@Nullable final PsiElement element, @NotNull final Class<? extends T>... classes) { if (element == null || element instanceof PsiFile) return null; PsiElement parent = element.getParent(); if (parent == null) return null; return getNonStrictParentOfType(parent, classes); } @SafeVarargs @Nullable @Contract("null, _ -> null") public static <T extends PsiElement> T getNonStrictParentOfType(@Nullable final PsiElement element, @NotNull final Class<? extends T>... classes) { PsiElement run = element; while (run != null) { if (instanceOf(run, classes)) { @SuppressWarnings("unchecked") T t = (T)run; return t; } if (run instanceof PsiFile) break; run = run.getParent(); } return null; } @NotNull @Contract(pure=true) public static PsiElement[] collectElements(@Nullable PsiElement element, @NotNull PsiElementFilter filter) { CollectFilteredElements<PsiElement> processor = new CollectFilteredElements<>(filter); processElements(element, processor); return processor.toArray(); } @SafeVarargs @NotNull @Contract(pure=true) public static <T extends PsiElement> Collection<T> collectElementsOfType(@Nullable PsiElement element, @NotNull Class<T>... classes) { return findChildrenOfAnyType(element, false, classes); } @Contract("null, _ -> true") public static boolean processElements(@Nullable PsiElement element, @NotNull PsiElementProcessor processor) { if (element == null) return true; if (element instanceof PsiCompiledElement || !element.isPhysical()) { // DummyHolders cannot be visited by walking visitors because children/parent relationship is broken there //noinspection unchecked if (!processor.execute(element)) return false; for (PsiElement child : element.getChildren()) { if (!processElements(child, processor)) return false; } return true; } final boolean[] result = {true}; element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { //noinspection unchecked if (processor.execute(element)) { super.visitElement(element); } else { stopWalking(); result[0] = false; } } }); return result[0]; } public static boolean processElements(@NotNull PsiElementProcessor processor, @Nullable PsiElement... elements) { if (elements == null || elements.length == 0) return true; for (PsiElement element : elements) { if (!processElements(element, processor)) return false; } return true; } public static void mark(@NotNull PsiElement element, @NotNull Object marker) { element.getNode().putCopyableUserData(MARKER, marker); } @Nullable public static PsiElement releaseMark(@NotNull PsiElement root, @NotNull Object marker) { ASTNode node = root.getNode(); if (marker.equals(node.getCopyableUserData(MARKER))) { node.putCopyableUserData(MARKER, null); return root; } else { PsiElement child = root.getFirstChild(); while (child != null) { final PsiElement result = releaseMark(child, marker); if (result != null) return result; child = child.getNextSibling(); } return null; } } @Nullable @Contract(pure=true) public static <T extends PsiElement> T findElementOfClassAtOffset(@NotNull PsiFile file, int offset, @NotNull Class<T> clazz, boolean strictStart) { final List<PsiFile> psiRoots = file.getViewProvider().getAllFiles(); T result = null; for (PsiElement root : psiRoots) { final PsiElement elementAt = root.findElementAt(offset); if (elementAt != null) { final T parent = getParentOfType(elementAt, clazz, strictStart); if (parent != null) { final TextRange range = parent.getTextRange(); if (!strictStart || range.getStartOffset() == offset) { if (result == null || result.getTextRange().getEndOffset() > range.getEndOffset()) { result = parent; } } } } } return result; } @SafeVarargs @Nullable @Contract(pure=true) public static <T extends PsiElement> T findElementOfClassAtOffsetWithStopSet(@NotNull PsiFile file, int offset, @NotNull Class<T> clazz, boolean strictStart, @NotNull Class<? extends PsiElement>... stopAt) { final List<PsiFile> psiRoots = file.getViewProvider().getAllFiles(); T result = null; for (PsiElement root : psiRoots) { final PsiElement elementAt = root.findElementAt(offset); if (elementAt != null) { final T parent = getParentOfType(elementAt, clazz, strictStart, stopAt); if (parent != null) { final TextRange range = parent.getTextRange(); if (!strictStart || range.getStartOffset() == offset) { if (result == null || result.getTextRange().getEndOffset() > range.getEndOffset()) { result = parent; } } } } } return result; } /** * @return maximal element of specified Class starting at startOffset exactly and ending not farther than endOffset */ @Nullable @Contract(pure=true) public static <T extends PsiElement> T findElementOfClassAtRange(@NotNull PsiFile file, int startOffset, int endOffset, @NotNull Class<T> clazz) { final FileViewProvider viewProvider = file.getViewProvider(); T result = null; for (Language lang : viewProvider.getLanguages()) { PsiElement elementAt = viewProvider.findElementAt(startOffset, lang); T run = getParentOfType(elementAt, clazz, false); T prev = run; while (run != null && run.getTextRange().getStartOffset() == startOffset && run.getTextRange().getEndOffset() <= endOffset) { prev = run; run = getParentOfType(run, clazz); } if (prev == null) continue; final int elementStartOffset = prev.getTextRange().getStartOffset(); final int elementEndOffset = prev.getTextRange().getEndOffset(); if (elementStartOffset != startOffset || elementEndOffset > endOffset) continue; if (result == null || result.getTextRange().getEndOffset() < elementEndOffset) { result = prev; } } return result; } @NotNull public static PsiElement getDeepestFirst(@NotNull PsiElement elt) { @NotNull PsiElement res = elt; do { final PsiElement firstChild = res.getFirstChild(); if (firstChild == null) return res; res = firstChild; } while (true); } @NotNull public static PsiElement getDeepestLast(@NotNull PsiElement elt) { @NotNull PsiElement res = elt; do { final PsiElement lastChild = res.getLastChild(); if (lastChild == null) return res; res = lastChild; } while (true); } @Nullable public static PsiElement prevLeaf(@NotNull PsiElement current) { if (current instanceof PsiFileSystemItem) return null; final PsiElement prevSibling = current.getPrevSibling(); if (prevSibling != null) return lastChild(prevSibling); final PsiElement parent = current.getParent(); if (parent == null || parent instanceof PsiFile) return null; return prevLeaf(parent); } @Nullable public static PsiElement nextLeaf(@NotNull PsiElement current) { if (current instanceof PsiFileSystemItem) return null; final PsiElement nextSibling = current.getNextSibling(); if (nextSibling != null) return firstChild(nextSibling); final PsiElement parent = current.getParent(); if (parent == null || parent instanceof PsiFile) return null; return nextLeaf(parent); } @NotNull public static PsiElement lastChild(@NotNull PsiElement element) { PsiElement lastChild = element.getLastChild(); if (lastChild != null) return lastChild(lastChild); return element; } @NotNull public static PsiElement firstChild(@NotNull final PsiElement element) { PsiElement child = element.getFirstChild(); if (child != null) return firstChild(child); return element; } @Nullable public static PsiElement prevLeaf(@NotNull final PsiElement element, final boolean skipEmptyElements) { PsiElement prevLeaf = prevLeaf(element); while (skipEmptyElements && prevLeaf != null && prevLeaf.getTextLength() == 0) prevLeaf = prevLeaf(prevLeaf); return prevLeaf; } @Nullable public static PsiElement prevVisibleLeaf(@NotNull final PsiElement element) { PsiElement prevLeaf = prevLeaf(element, true); while (prevLeaf != null && StringUtil.isEmptyOrSpaces(prevLeaf.getText())) prevLeaf = prevLeaf(prevLeaf, true); return prevLeaf; } @Nullable public static PsiElement nextVisibleLeaf(@NotNull final PsiElement element) { PsiElement nextLeaf = nextLeaf(element, true); while (nextLeaf != null && StringUtil.isEmptyOrSpaces(nextLeaf.getText())) nextLeaf = nextLeaf(nextLeaf, true); return nextLeaf; } @Nullable public static PsiElement nextLeaf(@NotNull PsiElement element, final boolean skipEmptyElements) { PsiElement nextLeaf = nextLeaf(element); while (skipEmptyElements && nextLeaf != null && nextLeaf.getTextLength() == 0) nextLeaf = nextLeaf(nextLeaf); return nextLeaf; } public static boolean hasErrorElements(@NotNull PsiElement element) { return !SyntaxTraverser.psiTraverser(element).traverse().filter(PsiErrorElement.class).isEmpty(); } @NotNull public static PsiElement[] filterAncestors(@NotNull PsiElement[] elements) { if (LOG.isDebugEnabled()) { for (PsiElement element : elements) { LOG.debug("element = " + element); } } ArrayList<PsiElement> filteredElements = new ArrayList<>(); ContainerUtil.addAll(filteredElements, elements); int previousSize; do { previousSize = filteredElements.size(); outer: for (PsiElement element : filteredElements) { for (PsiElement element2 : filteredElements) { if (element == element2) continue; if (isAncestor(element, element2, false)) { if (LOG.isDebugEnabled()) { LOG.debug("removing " + element2); } filteredElements.remove(element2); break outer; } } } } while (filteredElements.size() != previousSize); if (LOG.isDebugEnabled()) { for (PsiElement element : filteredElements) { LOG.debug("filtered element = " + element); } } return PsiUtilCore.toPsiElementArray(filteredElements); } public static boolean treeWalkUp(@NotNull final PsiScopeProcessor processor, @NotNull final PsiElement entrance, @Nullable final PsiElement maxScope, @NotNull final ResolveState state) { PsiElement prevParent = entrance; PsiElement scope = entrance; while (scope != null) { if (!scope.processDeclarations(processor, state, prevParent, entrance)) return false; if (scope == maxScope) break; prevParent = scope; scope = prevParent.getContext(); } return true; } public static boolean treeWalkUp(@NotNull final PsiElement entrance, @Nullable final PsiElement maxScope, @NotNull PairProcessor<? super PsiElement, ? super PsiElement> eachScopeAndLastParent) { PsiElement prevParent = null; PsiElement scope = entrance; while (scope != null) { if (!eachScopeAndLastParent.process(scope, prevParent)) return false; if (scope == maxScope) break; prevParent = scope; scope = prevParent.getContext(); } return true; } @NotNull public static PsiElement findPrevParent(@NotNull PsiElement ancestor, @NotNull PsiElement descendant) { PsiElement cur = descendant; while (cur != null) { final PsiElement parent = cur.getParent(); if (parent == ancestor) { return cur; } cur = parent; } throw new AssertionError(descendant + " is not a descendant of " + ancestor); } public static List<PsiElement> getInjectedElements(@NotNull OuterLanguageElement outerLanguageElement) { PsiElement psi = outerLanguageElement.getContainingFile().getViewProvider().getPsi(outerLanguageElement.getLanguage()); TextRange injectionRange = outerLanguageElement.getTextRange(); List<PsiElement> res = ContainerUtil.newArrayList(); assert psi != null : outerLanguageElement; for (PsiElement element = psi.findElementAt(injectionRange.getStartOffset()); element != null && injectionRange.intersectsStrict(element.getTextRange()); element = element.getNextSibling()) { res.add(element); } return res; } @Nullable public static PsiElement getDeepestVisibleFirst(@NotNull PsiElement psiElement) { PsiElement first = getDeepestFirst(psiElement); if (StringUtil.isEmptyOrSpaces(first.getText())) { first = nextVisibleLeaf(first); } return first; } @Nullable public static PsiElement getDeepestVisibleLast(@NotNull PsiElement psiElement) { PsiElement last = getDeepestLast(psiElement); if (StringUtil.isEmptyOrSpaces(last.getText())) { last = prevVisibleLeaf(last); } return last; } //<editor-fold desc="Deprecated stuff."> /** use {@link SyntaxTraverser#psiTraverser()} (to be removed in IDEA 2019) */ @Deprecated public static <T extends PsiElement> Iterator<T> childIterator(@NotNull PsiElement element, @NotNull Class<T> aClass) { return SyntaxTraverser.psiTraverser().children(element).filter(aClass).iterator(); } //</editor-fold> }
package plugin.google.maps; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import org.apache.cordova.CallbackContext; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.app.Activity; import android.content.res.Resources; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; public class AsyncKmlParser extends AsyncTask<String, Void, Bundle> { private XmlPullParser parser; private GoogleMap mMap; private Activity mActivity; private CallbackContext mCallback; private enum KML_TAG { style, stylemap, linestyle, polystyle, linestring, outerboundaryis, placemark, point, polygon, pair, multigeometry, key, styleurl, color, width, fill, name, description, coordinates }; public AsyncKmlParser(Activity activity, GoogleMap map, CallbackContext callbackContext) { mCallback = callbackContext; mMap = map; mActivity = activity; try { parser = XmlPullParserFactory.newInstance().newPullParser(); } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.toString()); } } @Override protected Bundle doInBackground(String... params) { Bundle kmlData = null; try { InputStream inputStream = mActivity.getResources().getAssets().open(params[0]); parser.setInput(inputStream, null); kmlData = parseXML(parser); } catch (Exception e) { e.printStackTrace(); return null; } return kmlData; } private Bundle getStyleById(Bundle styles, String styleId) { Bundle style = null; Bundle tmpBundle; String tagName, tmp; ArrayList<Bundle> bundleList; Iterator<Bundle> bundleIterator; if (styles.containsKey(styleId)) { style = styles.getBundle(styleId); tagName = style.getString("tagName"); if ("stylemap".equals(tagName)) { bundleList = style.getParcelableArrayList("children"); bundleIterator = bundleList.iterator(); while(bundleIterator.hasNext()) { tmpBundle = bundleIterator.next(); if ("normal".equals(tmpBundle.getString("key")) && tmpBundle.containsKey("styleurl")) { tmp = tmpBundle.getString("styleurl"); style = styles.getBundle(tmp); break; } } } } return style; } protected void onPostExecute(Bundle parseResult) { if (parseResult == null) { mCallback.error("KML Parse error"); return; } Bundle styles = parseResult.getBundle("styles"); ArrayList<Bundle> placeMarks = parseResult.getParcelableArrayList("placeMarks"); float density = Resources.getSystem().getDisplayMetrics().density; String tmp, tagName; Bundle node, style, childNode, tmpBundle; ArrayList<Bundle> bundleList; ArrayList<LatLng> latLngList; Iterator<Bundle> iterator = placeMarks.iterator(); Iterator<Bundle> bundleIterator; while(iterator.hasNext()) { node = iterator.next(); bundleList = node.getParcelableArrayList("children"); bundleIterator = bundleList.iterator(); while(bundleIterator.hasNext()) { childNode = bundleIterator.next(); tagName = childNode.getString("tagName"); switch(KML_TAG.valueOf(tagName)) { case point: latLngList = childNode.getParcelableArrayList("coordinates"); MarkerOptions markerOptions = new MarkerOptions(); tmp = node.getString("name"); if (node.containsKey("description")) { tmp += "\n\n" + node.getString("description"); } markerOptions.title(tmp); markerOptions.position(latLngList.get(0)); mMap.addMarker(markerOptions); break; case linestring: PolylineOptions polylineOptions = new PolylineOptions(); latLngList = childNode.getParcelableArrayList("coordinates"); polylineOptions.addAll(latLngList); Polyline polyline = mMap.addPolyline(polylineOptions); if (node.containsKey("styleurl")) { tmp = node.getString("styleurl"); } else { tmp = "#__default__"; } style = getStyleById(styles, tmp); if (style != null) { bundleList = style.getParcelableArrayList("children"); bundleIterator = bundleList.iterator(); while(bundleIterator.hasNext()) { style = bundleIterator.next(); tagName = style.getString("tagName"); switch(KML_TAG.valueOf(tagName)) { case linestyle: if (style.containsKey("color")) { polyline.setColor(parseKMLcolor(style.getString("color"))); } if (style.containsKey("width")) { polyline.setWidth(Integer.parseInt(style.getString("width")) * density); } break; } } } break; case polygon: ArrayList<Bundle> children = childNode.getParcelableArrayList("children"); childNode = children.get(0); PolygonOptions polygonOptions = new PolygonOptions(); latLngList = childNode.getParcelableArrayList("coordinates"); polygonOptions.addAll(latLngList); polygonOptions.strokeWidth(0); polygonOptions.strokeColor(Color.RED); polygonOptions.strokeWidth(4); mMap.addPolygon(polygonOptions); if (node.containsKey("styleurl")) { tmp = node.getString("styleurl"); } else { tmp = "#__default__"; } style = getStyleById(styles, tmp); if (style != null) { bundleList = style.getParcelableArrayList("children"); bundleIterator = bundleList.iterator(); while(bundleIterator.hasNext()) { style = bundleIterator.next(); tagName = style.getString("tagName"); switch(KML_TAG.valueOf(tagName)) { case polystyle: if (style.containsKey("color")) { polygonOptions.fillColor(parseKMLcolor(style.getString("color"))); } break; case linestyle: if (style.containsKey("color")) { polygonOptions.strokeColor(parseKMLcolor(style.getString("color"))); } if (style.containsKey("width")) { polygonOptions.strokeWidth(Float.parseFloat(style.getString("width")) * density); } break; } } } else { Log.e("client", "--" + style + " is null"); } break; } } } this.mCallback.success(); } private int parseKMLcolor(String colorStr) { String tmp = ""; for (int j = 2; j < colorStr.length() - 1; j+=2) { tmp = colorStr.substring(j, j + 2) + tmp; } tmp = colorStr.substring(0, 2) + tmp; Log.i("client", colorStr + " -> " + tmp); return Color.parseColor("#" + tmp); } private Bundle parseXML(XmlPullParser parser) throws XmlPullParserException,IOException { ArrayList<Bundle> placeMarks = new ArrayList<Bundle>(); int eventType = parser.getEventType(); Bundle currentNode = null; Bundle result = new Bundle(); ArrayList<Bundle> nodeStack = new ArrayList<Bundle>(); Bundle styles = new Bundle(); Bundle parentNode = null; ArrayList<Bundle> pairList = null; KML_TAG kmlTag = null; String tagName = null; String tmp; int nodeIndex = 0; while (eventType != XmlPullParser.END_DOCUMENT){ tagName = null; kmlTag = null; switch (eventType){ case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: tagName = parser.getName().toLowerCase(); try { kmlTag = KML_TAG.valueOf(tagName); } catch(Exception e) {} if (kmlTag == null) { eventType = parser.next(); continue; } switch (kmlTag) { case stylemap: case style: //push nodeStack.add(currentNode); currentNode = new Bundle(); currentNode.putString("tagName", tagName); tmp = parser.getAttributeValue(null, "id"); if (tmp == null) { tmp = "__default__"; } currentNode.putString("id", tmp); pairList = new ArrayList<Bundle>(); break; case multigeometry: //push nodeStack.add(currentNode); currentNode = new Bundle(); currentNode.putString("tagName", tagName); pairList = new ArrayList<Bundle>(); break; case placemark: currentNode = new Bundle(); currentNode.putString("tagName", tagName); pairList = null; break; case linestyle: case polystyle: case pair: if (pairList != null) { currentNode.putParcelableArrayList("children", pairList); pairList = new ArrayList<Bundle>(); } nodeStack.add(currentNode); currentNode = new Bundle(); currentNode.putString("tagName", tagName); break; case point: case linestring: case outerboundaryis: case polygon: //push if (pairList != null) { //currentNode.putParcelableArrayList("children", pairList); //pairList = null; } nodeStack.add(currentNode); currentNode = new Bundle(); currentNode.putString("tagName", tagName); break; case key: case styleurl: case name: case width: case color: case fill: case description: if (currentNode != null) { currentNode.putString(tagName, parser.nextText()); } break; case coordinates: if (currentNode != null) { ArrayList<LatLng> latLngList = new ArrayList<LatLng>(); String txt = parser.nextText(); String lines[] = txt.split("[\\n\\s]"); String tmpArry[]; int i; for (i = 0; i < lines.length; i++) { lines[i] = lines[i].replaceAll("[^0-9,.\\-]", ""); if ("".equals(lines[i]) == false) { tmpArry = lines[i].split(","); latLngList.add(new LatLng(Float.parseFloat(tmpArry[1]), Float.parseFloat(tmpArry[0]))); } } currentNode.putParcelableArrayList(tagName, latLngList); } break; default: break; } break; case XmlPullParser.END_TAG: if (currentNode != null) { tagName = parser.getName().toLowerCase(); kmlTag = null; try { kmlTag = KML_TAG.valueOf(tagName); } catch(Exception e) {} if (kmlTag == null) { eventType = parser.next(); continue; } switch (kmlTag) { case stylemap: case style: currentNode.putParcelableArrayList("children", pairList); styles.putBundle("#" + currentNode.getString("id"), currentNode); //pop nodeIndex = nodeStack.size() - 1; parentNode = nodeStack.get(nodeIndex); nodeStack.remove(nodeIndex); currentNode = parentNode; break; case multigeometry: //pop nodeIndex = nodeStack.size() - 1; parentNode = nodeStack.get(nodeIndex); parentNode.putParcelableArrayList("children", pairList); nodeStack.remove(nodeIndex); currentNode = parentNode; pairList = null; break; case placemark: placeMarks.add(currentNode); break; case pair: case linestyle: case polystyle: pairList.add(currentNode); //pop nodeIndex = nodeStack.size() - 1; parentNode = nodeStack.get(nodeIndex); nodeStack.remove(nodeIndex); currentNode = parentNode; break; case point: case outerboundaryis: case linestring: case coordinates: case polygon: //pop nodeIndex = nodeStack.size() - 1; parentNode = nodeStack.get(nodeIndex); nodeStack.remove(nodeIndex); if (parentNode.containsKey("children")) { pairList = parentNode.getParcelableArrayList("children"); pairList.add(currentNode); parentNode.putParcelableArrayList("children", pairList); } else { pairList = new ArrayList<Bundle>(); pairList.add(currentNode); parentNode.putParcelableArrayList("children", pairList); } currentNode = parentNode; break; default: break; } } break; } eventType = parser.next(); } result.putParcelableArrayList("placeMarks", placeMarks); result.putBundle("styles", styles); return result; } }
package org.jetbrains.cabal.parser; import com.intellij.testFramework.ParsingTestCase; import org.junit.Test; public class CabalParsingTest extends ParsingTestCase { static { System.setProperty("idea.platform.prefix", "Idea"); } public CabalParsingTest() { super("cabalParserTests", "cabal", new CabalParserDefinition()); } @Override protected String getTestDataPath() { return "data"; } @Test public void testBool() throws Exception { doTest(true); } @Test public void testFreeForm() throws Exception { doTest(true); } @Test public void testFreeLine() throws Exception { doTest(true); } @Test public void testIdentifier() throws Exception { doTest(true); } @Test public void testToken() throws Exception { doTest(true); } @Test public void testSimpleVersion() throws Exception { doTest(true); } @Test public void testVersionConstraint() throws Exception { doTest(true); } @Test public void testComplexVersionConstraint() throws Exception { doTest(true); } @Test public void testFullVersionConstraint() throws Exception { doTest(true); } @Test public void testSimpleTopLevel() throws Exception { doTest(true); } @Test public void testSimpleBuildInfo() throws Exception { doTest(true); } @Test public void testSimpleCondition() throws Exception { doTest(true); } @Test public void testComplexCondition() throws Exception { doTest(true); } @Test public void testIfElseSection() throws Exception { doTest(true); } @Test public void testSimpleOptionalCommaList() throws Exception { doTest(true); } @Test public void testBenchmark() throws Exception { doTest(true); } @Test public void testExecutable() throws Exception { doTest(true); } @Test public void testFlag() throws Exception { doTest(true); } @Test public void testInvalidField() throws Exception { doTest(true); } @Test public void testLibrary() throws Exception { doTest(true); } @Test public void testListInList() throws Exception { doTest(true); } @Test public void testRepoSource() throws Exception { doTest(true); } @Test public void testTestSuite() throws Exception { doTest(true); } @Test public void testEolComment() throws Exception { doTest(true); } }
/** * * @author JaneLDQ * @date 2014/11/14 */ package businesslogic.businessconditionbl; import java.io.FileOutputStream; import java.util.ArrayList; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import util.ResultMessage; import util.Time; import vo.BusinessConditionVO; import vo.CommodityLineItemVO; import vo.CommodityVO; import vo.ExceptionLineItemVO; import vo.ExceptionVO; import vo.PresentLineItemVO; import vo.PresentVO; import vo.RequirementVO; import vo.SaleVO; import businesslogic.commoditybl.Commodity; import businesslogic.exceptionbl.Loss; import businesslogic.exceptionbl.Overflow; import businesslogic.logbl.Log; import businesslogic.presentbl.Present; import businesslogic.salebl.Sale; import businesslogic.salebl.SaleReturn; public class BusinessCondition { public ResultMessage addLog(String content){ Log l=new Log(); return l.add(content); } public BusinessConditionVO show(String time1,String time2){ double[] saleIncome=saleIncome(time1,time2); double saleReturnIncome=saleReturnIncome(time1,time2); double costAdjustIncome=costAdjustIncome(time1,time2); double over=OverflowIncome(time1,time2); double adjust=costAdjustIncome(time1,time2); double sale=saleIncome[0]+saleReturnIncome+costAdjustIncome+over+adjust-saleIncome[2]; double saleAfterDiscount=saleIncome[1]+saleReturnIncome+costAdjustIncome+over+adjust-saleIncome[2]; double saleCost=saleCost(time1,time2); double loss=LossCost(time1,time2); double present=presentCost(time1,time2); double totalCost=saleCost+loss+present; double profit=saleAfterDiscount-totalCost; BusinessConditionVO result=new BusinessConditionVO(sale,saleAfterDiscount, saleIncome[0]-saleIncome[1],over,adjust,saleIncome[2],saleCost,loss,present,totalCost, profit); return result; } public double[] saleIncome(String time1,String time2){ double[] result=new double[3]; Sale s=new Sale(); ArrayList<SaleVO> list=s.findByTime(time1, time2); for(int i=0;i<list.size();i++){ SaleVO temp=list.get(i); if(temp.isWriteOff){ result[0]-=temp.totalBeforeDiscount; result[1]-=temp.totalAfterDiscount; result[2]-=temp.voucher; }else{ result[0]+=temp.totalBeforeDiscount; result[1]+=temp.totalAfterDiscount; result[2]+=temp.voucher; } } return result; } public double saleReturnIncome(String time1,String time2){ double result=0; SaleReturn sr=new SaleReturn(); time1=Time.jdugeTime1(time1); time2=Time.jdugeTime2(time2); ArrayList<SaleVO> list=sr.findByTime(time1, time2); ArrayList<CommodityLineItemVO> commodity=new ArrayList<CommodityLineItemVO>(); for(int i=0;i<list.size();i++){ commodity=list.get(i).saleList; for(int j=0;j<commodity.size();j++){ CommodityLineItemVO temp=commodity.get(j); Commodity c=new Commodity(); CommodityVO t=c.commodityPOToCommodityVO(c.getById(temp.id)); result=result+(t.recentPurchasePrice*temp.number-temp.total); } } return result; } public double costAdjustIncome(String time1,String time2){ return 0; } public double OverflowIncome(String time1,String time2){ double result=0; Overflow of=new Overflow(); time1=Time.jdugeTime1(time1); time2=Time.jdugeTime2(time2); ArrayList<ExceptionVO> list=of.findByTime(time1,time2); ArrayList<ExceptionLineItemVO> commodity=new ArrayList<ExceptionLineItemVO>(); for(int i=0;i<list.size();i++){ commodity=list.get(i).list; for(int j=0;j<commodity.size();j++){ ExceptionLineItemVO temp=commodity.get(j); Commodity c=new Commodity(); CommodityVO t=c.commodityPOToCommodityVO(c.getById(temp.id)); result=result+t.purchasePrice*(temp.actualNumber-temp.systemNumber); } } return result; } public double LossCost(String time1,String time2){ double result=0; Loss l=new Loss(); time1=Time.jdugeTime1(time1); time2=Time.jdugeTime2(time2); ArrayList<ExceptionVO> list=l.show(time1,time2); ArrayList<ExceptionLineItemVO> commodity=new ArrayList<ExceptionLineItemVO>(); for(int i=0;i<list.size();i++){ commodity=list.get(i).list; for(int j=0;j<commodity.size();j++){ ExceptionLineItemVO temp=commodity.get(j); Commodity c=new Commodity(); CommodityVO t=c.commodityPOToCommodityVO(c.getById(temp.id)); result=result+t.purchasePrice*(temp.systemNumber-temp.actualNumber); } } return result; } public double presentCost(String time1,String time2){ double result=0; Present p=new Present(); ArrayList<PresentVO> list=p.findByTime(time1, time2); ArrayList<PresentLineItemVO> present=new ArrayList<PresentLineItemVO>(); for(int i=0;i<list.size();i++){ present=list.get(i).list; for(int j=0;j<present.size();j++){ PresentLineItemVO temp=present.get(j); Commodity c=new Commodity(); CommodityVO t=c.commodityPOToCommodityVO(c.getById(temp.id)); result=result+t.recentPurchasePrice*temp.number; } } return result; } public double saleCost(String time1,String time2){ double result=0; Sale s=new Sale(); ArrayList<SaleVO> list=s.findByTime(time1, time2); ArrayList<CommodityLineItemVO> commodity=new ArrayList<CommodityLineItemVO>(); for(int i=0;i<list.size();i++){ commodity=list.get(i).saleList; for(int j=0;j<commodity.size();j++){ CommodityLineItemVO temp=commodity.get(j); Commodity c=new Commodity(); CommodityVO vo=c.commodityPOToCommodityVO(c.getById(temp.id)); result=result+temp.number*vo.recentPurchasePrice; } } return result; } public ResultMessage exportExcel(String path,RequirementVO vo){ HSSFWorkbook wb=new HSSFWorkbook(); HSSFSheet sheet=wb.createSheet(""); HSSFRow row=sheet.createRow(0); HSSFCellStyle style=wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCell cell=row.createCell(0); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(1); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(2); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(3); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(4); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(5); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(6); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(7); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(8); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(9); cell.setCellValue(""); cell.setCellStyle(style); cell=row.createCell(10); cell.setCellValue(""); cell.setCellStyle(style); BusinessConditionVO v=show(vo.time1,vo.time2); row=sheet.createRow(1); row.createCell(0).setCellValue(v.saleIncome); row.createCell(1).setCellValue(v.incomeAfterDiscount); row.createCell(2).setCellValue(v.discount); row.createCell(3).setCellValue(v.commodityOverIncome); row.createCell(4).setCellValue(v.costAdjustIncome); row.createCell(5).setCellValue(v.voucherIncome); row.createCell(6).setCellValue(v.saleCost); row.createCell(7).setCellValue(v.costByLoss); row.createCell(8).setCellValue(v.costBySending); row.createCell(9).setCellValue(v.saleCost); row.createCell(10).setCellValue(v.profit); try{ FileOutputStream fout=new FileOutputStream(path); wb.write(fout); fout.close(); }catch(Exception e){ e.printStackTrace(); } return ResultMessage.SUCCESS; } }
package ca.mcgill.mcb.pcingola.bigDataScript.osCmd; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import ca.mcgill.mcb.pcingola.bigDataScript.executioner.ExecutionerLocal; import ca.mcgill.mcb.pcingola.bigDataScript.util.Gpr; public class CmdLocal extends Cmd { public static final int MAX_PID_LINE_LENGTH = 1024; // A 'PID line' should not be longer than this... public static final int MAX_STDOUT_WAIT = 1000; // Maximum wait until STDOUT becomes avaialble protected Process process; // Java process (the one that actually executes our command) protected boolean readPid; protected String pid; // Only if child process reports PID and readPid is true protected String feedStdin; // Feed this string to stdin when the process starts public CmdLocal(String id, String args[]) { super(id, args); } @Override protected void execCmd() throws Exception { // Wait for the process to finish and store exit value exitValue = process.waitFor(); } @Override protected boolean execPrepare() throws Exception { // Build process and start it ProcessBuilder pb = new ProcessBuilder(commandArgs); if (debug) { StringBuilder cmdsb = new StringBuilder(); for (String arg : commandArgs) cmdsb.append(" " + arg); Gpr.debug("Executing: " + cmdsb); } process = pb.start(); // Feed something to STDIN? feedStdin(); // Child process prints PID to STDOUT? Read it if (!readPid()) { StringBuilder errStr = new StringBuilder(); InputStream stderr = process.getErrorStream(); // Error: Stdout was closed before we could read it // Try reading sdterr: show it to console and store it in 'error' int c; while ((stderr != null) && ((c = stderr.read()) >= 0)) { errStr.append((char) c); System.err.print((char) c); } if (errStr.length() > 0) error += errStr.toString(); return false; }; return true; } /** * Feed a string to process' STDIN * @throws InterruptedException * @throws IOException */ protected void feedStdin() throws InterruptedException, IOException { if ((feedStdin == null) || feedStdin.isEmpty()) return; // Nothing to do // Wait for STDOUT to become available while (getStdin() == null) sleep(1); // Write and close STDIN BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(getStdin())); bos.write(feedStdin); bos.flush(); bos.close(); } public String getPid() { return pid; } public InputStream getStderr() { if (process == null) return null; return process.getErrorStream(); } public OutputStream getStdin() { if (process == null) return null; return process.getOutputStream(); } public InputStream getStdout() { if (process == null) return null; return process.getInputStream(); } /** * Send a kill signal using 'bds kill' * @param pid */ protected void killBds(int pid) { // Create arguments ArrayList<String> args = new ArrayList<String>(); // Add command and arguments if ((executioner != null) && (task != null)) { for (String arg : executioner.osKillCommand(task)) args.add(arg); } else { for (String arg : ExecutionerLocal.LOCAL_KILL_COMMAND) args.add(arg); args.add("" + pid); } // Add tasks's pis if (task != null) args.add(task.getPid()); else args.add("" + pid); // Execute kill command try { // Execute 'bds kill pid' Process proc = Runtime.getRuntime().exec(args.toArray(ARGS_ARRAY_TYPE)); if (debug) Gpr.debug("Executing kill process for pid " + pid); int exitVal = proc.waitFor(); if (exitVal != 0) System.err.println("Error killing process " + pid); } catch (Exception e) { e.printStackTrace(); } } @Override protected void killCmd() { if (process != null) { // Do we have a PID number? Kill using that number int pidNum = Gpr.parseIntSafe(pid); if (pidNum > 0) killBds(pidNum); error += "Killed!\n"; if (debug) Gpr.debug("Killing process " + id); process.destroy(); } } /** * Read child process pid (or cluster job id) * @return * @throws InterruptedException * @throws IOException */ protected boolean readPid() throws InterruptedException, IOException { pid = ""; // Nothing to do? if (!readPid) return true; // Wait for STDOUT to become available while (getStdout() == null) sleep(1); // Read one line. // Note: We want to limit the damage if something goes wrong, so we use a small buffer... StringBuilder sb = new StringBuilder(); while (pid.isEmpty()) { for (int i = 0; true; i++) { int r = getStdout().read(); if (r < 0) { if (debug) System.err.println("WARNING: Process closed stdout prematurely. Could not read PID\n" + this); return false; } char ch = (char) r; if (ch == '\n') break; sb.append(ch); if (i >= MAX_PID_LINE_LENGTH) throw new RuntimeException("PID line too long!\n" + sb.toString()); } // Parse line. Format "PID \t pidNum \t childPidNum" if (debug) Gpr.debug("Got line: '" + sb + "'"); // Parse pid? if (executioner != null) pid = executioner.parsePidLine(sb.toString()); else pid = sb.toString().trim(); // Ignore spaces } if (task != null) task.setPid(pid); // Update task's pid return true; } public void setReadPid(boolean readPid) { this.readPid = readPid; } public void setStdin(String stdin) { feedStdin = stdin; } }
package com.actelion.research.gwt.gui.editor; import com.actelion.research.gwt.gui.editor.actions.ESRSVGTypeAction; import com.actelion.research.gwt.gui.viewer.GraphicsContext; import com.actelion.research.share.gui.editor.Model; import com.actelion.research.share.gui.editor.actions.*; import com.actelion.research.share.gui.editor.listeners.IChangeListener; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.*; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.RootPanel; import java.awt.*; import java.awt.geom.Point2D; class SVGToolBarImpl implements ToolBar<Element>, IChangeListener { static int instanceCount = 0; private final Image BUTTON_SVG_IMAGE = new Image(ImageHolder.SVGDRAWBUTTON); private final Image BUTTON_ESRAND = new Image(ImageHolder.SVGESRAND); private final Image BUTTON_ESROR = new Image(ImageHolder.SVGESROR); private Action[][] ACTIONS = null; private Model model = null; private Canvas canvas = null; private int selectedRow; private int selectetCol; private Action currentAction = null; private Action lastAction = null; private Action hoverAction; private int scale = 1; private boolean focus; SVGToolBarImpl(Model model, int scale) { this.model = model; this.scale = scale; instanceCount++; } /** * Creates the HTML Element containing the toolbar * * @param parent Parent HTML element * @param width Element with (specified via inline style) * @param height Element height (specified via inline style) * @return Element containing/representing the toolbar */ public Element createElement(Element parent, int width, int height) { String toolBarId = "toolbar" + instanceCount; DivElement toolbarHolder = Document.get().createDivElement(); toolbarHolder.setId(toolBarId); toolbarHolder.setAttribute("style", "position:absolute;width:" + width * scale + "px;height:" + height * scale + "px;"); parent.appendChild(toolbarHolder); canvas = Util.createScaledCanvas(width * scale, height * scale); canvas.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { focus = true; } }); canvas.addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { focus = false; } }); // Add the canvas to the toolbar container RootPanel.get(toolBarId).add(canvas); setupActions(); setupMouseHandlers(); model.addChangeListener(this); Timer t = new Timer() { public void run() { repaint(); } }; t.schedule(100); return toolbarHolder; } /** * Setup the button actions */ private void setupActions() { ACTIONS = new Action[][] { { new ClearAction(model), new UndoAction(model) }, { new CleanAction(model), new ZoomRotateAction(model) }, { new SelectionAction(model), model.isReaction() ? new AtomMapAction(model) : null, }, { new UnknownParityAction(model), new ESRSVGTypeAction(model, scale) }, { new DeleteAction(model), null }, { new NewBondAction(model), new NewChainAction(model) }, { new UpBondAction(model), new DownBondAction(model), }, { new AddRingAction(model, 3, false), new AddRingAction(model, 4, false), }, { new AddRingAction(model, 5, false), new AddRingAction(model, 6, false), }, { new AddRingAction(model, 7, false), new AddRingAction(model, 6, true), }, { new ChangeChargeAction(model, true), new ChangeChargeAction(model, false), }, { new ChangeAtomAction(model, 6), new ChangeAtomAction(model, 14), }, { new ChangeAtomAction(model, 7), new ChangeAtomAction(model, 15), }, { new ChangeAtomAction(model, 8), new ChangeAtomAction(model, 16), }, { new ChangeAtomAction(model, 9), new ChangeAtomAction(model, 17), }, { new ChangeAtomAction(model, 35), new ChangeAtomAction(model, 53), }, { new ChangeAtomAction(model, 1), new ChangeAtomPropertiesAction(model) }, }; lastAction = setAction(2, 0);// currentAction = ACTIONS[selectedRow][selectetCol]; } /** * Drawing function * * @param canvas */ private void draw(Canvas canvas) { Context2d context2d = canvas.getContext2d(); GraphicsContext ctx = new GraphicsContext(context2d); drawButtons(ctx); drawESRButtons(ctx); drawHover(ctx); } /** * Returns the row/col of an action within the button image * * @param a Action to be found * @return Point x,y representing column and row of the action of null if action * is not found within the image */ public Point getActionPosition(Action a) { for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { if (ACTIONS[row][col] == a) { return new Point(col, row); } } } return null; } /** * @param ctx */ private void drawButtons(GraphicsContext ctx) { ctx.clearRect(0, 0, IMAGE_WIDTH * scale, IMAGE_HEIGHT * scale); ctx.drawImage(BUTTON_SVG_IMAGE, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH * scale, IMAGE_HEIGHT * scale); if (selectedRow != -1 && selectetCol != -1) { double dx = IMAGE_WIDTH / COLS * scale; double dy = IMAGE_HEIGHT / ROWS * scale; int y = (int) (IMAGE_HEIGHT / ROWS * selectedRow * scale); int x = (int) (IMAGE_WIDTH / COLS * selectetCol * scale); Action action = getCurrentAction(); Point pt = getActionPosition(action); ctx.setFill(model.getGeomFactory().getDrawConfig().createColor(.5, .5, .5, .5)); ctx.fillRect(x, y, dx, dy); } double dy = IMAGE_HEIGHT * scale / ROWS; double dx = IMAGE_WIDTH * scale / COLS; for (int row = 0; row < ROWS + 1; row++) { ctx.setStroke(model.getGeomFactory().getDrawConfig().createColor(.8, .8, .8, .5)); ctx.drawLine(0, dy * row, IMAGE_WIDTH * scale, dy * row); } for (int col = 0; col <= COLS; col++) { ctx.drawLine(col * dx, 0, col * dx, IMAGE_HEIGHT * scale); } } /** * Draw the button when mouse is hovering it * * @param ctx */ private void drawHover(GraphicsContext ctx) { if (hoverAction != null && hoverAction != getCurrentAction()) { double dx = IMAGE_WIDTH / COLS * scale; double dy = IMAGE_HEIGHT / ROWS * scale; Point pt = getActionPosition(hoverAction); int y = (int) (IMAGE_HEIGHT * scale / ROWS * pt.y); int x = (int) (IMAGE_WIDTH * scale / COLS * pt.x); ctx.setFill(model.getGeomFactory().getDrawConfig().createColor(.3, .3, .3, .5)); ctx.fillRect(x, y, dx, dy); } } /** * Draw the current ESR image * * @param ctx */ private void drawESRButtons(GraphicsContext ctx) { int row = Model.rowFromESRType(model.getESRType()); int y = (int) (IMAGE_HEIGHT * scale / ROWS * 3); int x = (int) (IMAGE_WIDTH * scale / COLS * 1); double dx = IMAGE_WIDTH * scale / COLS; double dy = IMAGE_HEIGHT * scale / ROWS; Image node = null; switch (row) { case 0: break; case 1: node = BUTTON_ESROR; break; case 2: node = BUTTON_ESRAND; break; } if (node != null) { ctx.clearRect(x, y, node.getWidth() * scale, node.getHeight() * scale); ctx.drawImage(node, 0, 0, node.getWidth(), node.getHeight(), x, y, node.getWidth() * scale, node.getHeight() * scale); } } private void setupMouseHandlers() { canvas.addMouseDownHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent event) { onMousePressed(event); } }); canvas.addMouseUpHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { onMouseReleased(event); } }); canvas.addMouseMoveHandler(new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent event) { onMouseMoved(event); } }); canvas.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { onMouseLeft(event); } }); } private void onMouseLeft(MouseOutEvent event) { if (hoverAction != null) { hoverAction = null; repaint(); } } private void onMouseMoved(MouseMoveEvent evt) { double x = evt.getX(); double y = evt.getY(); if (x >= 0 && x <= IMAGE_WIDTH * scale && y >= 0 && y < IMAGE_HEIGHT * scale) { double dy = IMAGE_HEIGHT / ROWS * scale; double dx = IMAGE_WIDTH / COLS * scale; int col = (int) (x / dx); int row = (int) (y / dy); Action a = getAction(row, col); if (a != hoverAction) { hoverAction = a; repaint(); } } else { if (hoverAction != null) { hoverAction = null; repaint(); } } } /** * Find the action at row, col within the button image * * @param row y position * @param col x position * @return Action found or null with outside of the buttons range */ public Action getAction(int row, int col) { if (row >= 0 && row < ROWS && col >= 0 && col < COLS) return ACTIONS[row][col]; return null; } Action setAction(Action a) { selectedRow = -1; selectetCol = -1; currentAction = a; for (int r = 0; r < ACTIONS.length; r++) { for (int c = 0; c < 2; c++) { if (ACTIONS[r][c] == a) { selectedRow = r; selectetCol = c; currentAction = a; } } } return currentAction; } Action setAction(int row, int col) { if (ACTIONS[row][col] != null) { selectedRow = row; selectetCol = col; Action last = currentAction; currentAction = ACTIONS[selectedRow][selectetCol]; if (last != null && last != currentAction) { last.onActionLeave(); } currentAction.onActionEnter(); lastAction = last; } else { System.err.println("Error setting null action:"); } return currentAction; } private void onMousePressed(MouseEvent evt) { double x = evt.getX(); double y = evt.getY(); if (x >= 0 && x <= IMAGE_WIDTH * scale && y >= 0 && y < IMAGE_HEIGHT * scale) { double dy = IMAGE_HEIGHT / ROWS * scale; double dx = IMAGE_WIDTH / COLS * scale; int col = (int) (x / dx); int row = (int) (y / dy); Action action = setAction(row, col); if (action instanceof ButtonPressListener) { ButtonPressListener bpl = (ButtonPressListener) action; bpl.onButtonPressed(new Window(canvas), new Point2D.Double(x, y)); } repaint(); } } private void repaint() { draw(canvas); } private void onMouseReleased(MouseEvent evt) { boolean repaint = false; if (currentAction != null) { if (currentAction instanceof ButtonPressListener) { ButtonPressListener bpl = (ButtonPressListener) currentAction; bpl.onButtonReleased(/* this.getScene().getWindow() */null, new Point2D.Double(evt.getX(), evt.getY())); repaint = true; } if (currentAction.isCommand()) { currentAction.onMouseUp(new ACTMouseEvent(evt)); setAction(lastAction); repaint = true; } } if (repaint) { repaint(); } } @Override public Action getCurrentAction() { return currentAction; } @Override public boolean hasFocus() { return focus; } @Override public void onChange() { repaint(); } public void doAction(Action a) { if (a.isCommand()) { a.onCommand(); } else { setAction(a); } repaint(); } }
package com.bkahlert.devel.nebula.widgets.composer; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.BrowserFunction; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.bkahlert.devel.nebula.colors.RGB; import com.bkahlert.devel.nebula.utils.ExecUtils; import com.bkahlert.devel.nebula.utils.IConverter; import com.bkahlert.devel.nebula.widgets.browser.BrowserComposite; import com.bkahlert.devel.nebula.widgets.browser.IJavaScriptExceptionListener; import com.bkahlert.devel.nebula.widgets.browser.JavaScriptException; import com.bkahlert.devel.nebula.widgets.browser.extended.html.Anker; import com.bkahlert.devel.nebula.widgets.browser.extended.html.IAnker; import com.bkahlert.devel.nebula.widgets.timeline.TimelineJsonGenerator; /** * This is a wrapped CKEditor (ckeditor.com). * <p> * <b>Important developer warning</b>: Do not try to wrap a WYSIWYG editor based * on iframes like TinyMCE. Some internal browsers (verified with Webkit) do not * handle cut, copy and paste actions when the iframe is in focus. CKEditor can * operate in both modes - iframes and divs (and p tags). * * @author bkahlert * */ public class Composer extends BrowserComposite { private static final Logger LOGGER = Logger.getLogger(Composer.class); private static final Pattern URL_PATTERN = Pattern .compile("(.*?)(\\w+://[!#$&-;=?-\\[\\]_a-zA-Z~%]+)(.*?)"); public static enum ToolbarSet { DEFAULT, TERMINAL, NONE; } private final List<IAnkerLabelProvider> ankerLabelProviders = new ArrayList<IAnkerLabelProvider>(); private final List<ModifyListener> modifyListeners = new ArrayList<ModifyListener>(); private String oldHtml = ""; private final Timer delayChangeTimer = new Timer(this.getClass() .getSimpleName() + " :: Delay Change Timer", false); private TimerTask delayChangeTimerTask = null; public Composer(Composite parent, int style) { this(parent, style, 0, ToolbarSet.DEFAULT); } /** * * @param parent * @param style * @param delayChangeEventUpTo * is the delay that must have been passed in order to fire a * change event. If 0 no delay will be applied. The minimal delay * is defined by the CKEditor's config.js. * @throws IOException */ public Composer(Composite parent, int style, final long delayChangeEventUpTo, ToolbarSet toolbarSet) { super(parent, style); this.deactivateNativeMenu(); this.addJavaScriptExceptionListener(new IJavaScriptExceptionListener() { @Override public boolean thrown(JavaScriptException e) { LOGGER.error("Internal " + Composer.class.getSimpleName() + " error", e); return true; } }); this.fixShortcuts(delayChangeEventUpTo); this.listenForModifications(delayChangeEventUpTo); this.open( getFileUrl(Composer.class, "html/index.html", "?internal=true&toolbarSet=" + toolbarSet.toString().toLowerCase()), 30000, "return typeof jQuery != \"undefined\" && jQuery(\"html\").hasClass(\"ready\")"); this.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { if (Composer.this.delayChangeTimer != null) { Composer.this.delayChangeTimer.cancel(); } } }); } public void fixShortcuts(final long delayChangeEventUpTo) { this.getBrowser().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if ((e.stateMask & SWT.CTRL) != 0 || (e.stateMask & SWT.COMMAND) != 0) { if (e.keyCode == 97) { // a - select all Composer.this.selectAll(); } /* * The CKEditor plugin "onchange" does not notify on cut and * paste operations. Therefore we need to handle them here. */ if (e.keyCode == 120) { // x - cut // wait for the ui thread to apply the operation ExecUtils.asyncExec(new Runnable() { @Override public void run() { Composer.this.modifiedCallback( Composer.this.getSource(), delayChangeEventUpTo); } }); } if (e.keyCode == 99) { // c - copy // do nothing } if (e.keyCode == 118) { // v - paste // wait for the ui thread to apply the operation ExecUtils.asyncExec(new Runnable() { @Override public void run() { Composer.this.modifiedCallback( Composer.this.getSource(), delayChangeEventUpTo); } }); } } } }); } public void listenForModifications(final long delayChangeEventUpTo) { new BrowserFunction(this.getBrowser(), "modified") { @Override public Object function(Object[] arguments) { if (arguments.length >= 1) { if (arguments[0] instanceof String) { String newHtml = (String) arguments[0]; Composer.this.modifiedCallback(newHtml, delayChangeEventUpTo); } } return null; } }; this.getBrowser().addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { Composer.this.modifiedCallback(Composer.this.getSource(), 0); } }); } protected void modifiedCallback(String html, long delayChangeEventTo) { String newHtml = (html == null || html.replace("&nbsp;", " ").trim() .isEmpty()) ? "" : html.trim(); if (this.oldHtml.equals(newHtml)) { return; } // When space entered but widget is not disposing, create links if (delayChangeEventTo > 0) { String prevCaretCharacter = this.getPrevCaretCharacter(); if (prevCaretCharacter != null && this.getPrevCaretCharacter().matches("[\\s| ]")) { // space // non // breaking // space String autoLinkedHtml = this.createLinks(newHtml); if (!autoLinkedHtml.equals(newHtml)) { this.setSource(autoLinkedHtml, true); newHtml = autoLinkedHtml; } } } final String tmp = newHtml; final Runnable fireRunnable = new Runnable() { @Override public void run() { Event event = new Event(); event.display = Display.getCurrent(); event.widget = Composer.this; event.text = tmp; event.data = tmp; ModifyEvent modifyEvent = new ModifyEvent(event); for (ModifyListener modifyListener : Composer.this.modifyListeners) { modifyListener.modifyText(modifyEvent); } } }; this.oldHtml = tmp; if (this.delayChangeTimerTask != null) { this.delayChangeTimerTask.cancel(); } if (delayChangeEventTo > 0) { this.delayChangeTimerTask = new TimerTask() { @Override public void run() { fireRunnable.run(); } }; this.delayChangeTimer.schedule(this.delayChangeTimerTask, delayChangeEventTo); } else { this.delayChangeTimerTask = null; fireRunnable.run(); } } private String createLinks(String html) { boolean htmlChanged = false; Document doc = Jsoup.parseBodyFragment(html); for (Element e : doc.getAllElements()) { if (e.tagName().equals("a")) { IAnker anker = new Anker(e); IAnker newAnker = this.createAnkerFromLabelProviders(anker); if (newAnker == null && !anker.getHref().equals(anker.getContent())) { newAnker = new Anker(anker.getContent(), anker.getClasses(), anker.getContent()); } if (newAnker != null) { e.html(newAnker.toHtml()); htmlChanged = true; } } else { String ownText = e.ownText(); Matcher matcher = URL_PATTERN.matcher(ownText); if (matcher.matches()) { String uri = matcher.group(2); IAnker anker = new Anker(uri, new String[0], uri); IAnker newAnker = this.createAnkerFromLabelProviders(anker); if (newAnker == null) { newAnker = anker; } String newHtml = e.html().replace(uri, newAnker.toHtml()); e.html(newHtml); htmlChanged = true; } } } String newHtml = htmlChanged ? doc.body().children().toString() : html; return newHtml; } public IAnker createAnkerFromLabelProviders(IAnker oldAnker) { IAnker newAnker = null; for (IAnkerLabelProvider ankerLabelProvider : this.ankerLabelProviders) { if (ankerLabelProvider.isResponsible(oldAnker)) { newAnker = new Anker(ankerLabelProvider.getHref(oldAnker), ankerLabelProvider.getClasses(oldAnker), ankerLabelProvider.getContent(oldAnker)); break; } } return newAnker; } /** * Checks whether the current editor contents present changes when compared * to the contents loaded into the editor at startup. * * @return */ public Boolean isDirty() { Boolean isDirty = (Boolean) this.getBrowser().evaluate( "return com.bkahlert.devel.nebula.editor.isDirty();"); if (isDirty != null) { return isDirty; } else { return null; } } public void selectAll() { this.run("com.bkahlert.devel.nebula.editor.selectAll();"); } public Future<Boolean> setSource(String html) { return this.setSource(html, false); } public Future<Boolean> setSource(String html, boolean restoreSelection) { /* * do not wait for the delay to pass but invoke the task immediately */ if (this.delayChangeTimerTask != null) { this.delayChangeTimerTask.cancel(); this.delayChangeTimerTask.run(); this.delayChangeTimerTask = null; } return this.run("return com.bkahlert.devel.nebula.editor.setSource(" + TimelineJsonGenerator.enquote(html) + ", " + (restoreSelection ? "true" : "false") + ");", IConverter.CONVERTER_BOOLEAN); } /** * TODO use this.run * * @return */ public String getSource() { if (!this.isLoadingCompleted()) { return null; } String html = (String) this.getBrowser().evaluate( "return com.bkahlert.devel.nebula.editor.getSource();"); return html; } public void setMode(String mode) { this.run("com.bkahlert.devel.nebula.editor.setMode(\"" + mode + "\");"); } public void showSource() { this.setMode("source"); } public void hideSource() { this.setMode("wysiwyg"); } public String getPrevCaretCharacter() { if (!this.isLoadingCompleted()) { return null; } String html = (String) this .getBrowser() .evaluate( "return com.bkahlert.devel.nebula.editor.getPrevCaretCharacter();"); return html; } public void saveSelection() { this.run("com.bkahlert.devel.nebula.editor.saveSelection();"); } public void restoreSelection() { this.run("com.bkahlert.devel.nebula.editor.restoreSelection();"); } @Override public void setEnabled(boolean isEnabled) { this.run("return com.bkahlert.devel.nebula.editor.setEnabled(" + (isEnabled ? "true" : "false") + ");", IConverter.CONVERTER_BOOLEAN); } @Override public void setBackground(Color color) { String hex = new RGB(color.getRGB()).toHexString(); this.injectCss("html .cke_reset { background-color: " + hex + "; }"); } public void addAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) { this.ankerLabelProviders.add(ankerLabelProvider); } public void removeAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) { this.ankerLabelProviders.remove(ankerLabelProvider); } /** * Adds a {@link ModifyListener} to this {@link Image}. * <p> * Please note that {@link ModifyListener#modifyText(ModifyEvent)} is also * fired when the {@link Image} is being disposed. This is the last * opportunity to read the {@link Image}'s current demoAreaContent. * * @param modifyListener */ public void addModifyListener(ModifyListener modifyListener) { this.modifyListeners.add(modifyListener); } /** * Removes a {@link ModifyListener} from this {@link Image}. * * @param modifyListener */ public void removeModifyListener(ModifyListener modifyListener) { this.modifyListeners.remove(modifyListener); } }
package com.demonwav.mcdev.creator; import com.demonwav.mcdev.Type; import com.demonwav.mcdev.util.BukkitSettings; import com.demonwav.mcdev.util.BungeeCordSettings; import com.demonwav.mcdev.util.SpongeSettings; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ui.IdeBorderFactory; import org.jetbrains.annotations.NotNull; import java.awt.Desktop; import java.io.IOException; import java.net.URISyntaxException; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.event.HyperlinkEvent; public class ProjectChooserWizardStep extends ModuleWizardStep { private final MinecraftProjectCreator creator; private JPanel chooserPanel; private JPanel panel; private JPanel infoPanel; private JRadioButton bukkitRadioButton; private JRadioButton spigotRadioButton; private JRadioButton bungeecordRadioButton; private JEditorPane infoPane; private JRadioButton spongeRadioButton; private JRadioButton paperRadioButton; private Type type = Type.BUKKIT; private static final String bukkitInfo = "<html><font size=\"4\">Create a standard " + "<a href=\"http://bukkit.org/\">Bukkit</a> plugin, for use " + "on CraftBukkit, Spigot, and Paper servers.</font></html>"; private static final String spigotInfo = "<html><font size=\"4\">Create a standard " + "<a href=\"https: "on Spigot and Paper servers.</font></html>"; private static final String paperInfo = "<html><font size=\"4\">Create a standard " + "<a href=\"https://paper.readthedocs.io/en/paper-1.9/\">Paper</a> plugin, for use " + "on Paper servers.</font></html>"; private static final String bungeeCordInfo = "<html><font size=\"4\">Create a standard " + "<a href=\"https: "on BungeeCord servers.</font></html>"; private static final String spongeInfo = "<html><font size=\"4\">Create a standard " + "<a href=\"https: "on Sponge servers.</font></html>"; public ProjectChooserWizardStep(@NotNull MinecraftProjectCreator creator) { super(); this.creator = creator; } @Override public JComponent getComponent() { chooserPanel.setBorder(IdeBorderFactory.createBorder()); infoPanel.setBorder(IdeBorderFactory.createBorder()); // HTML parsing and hyperlink support infoPane.setContentType("text/html"); infoPane.addHyperlinkListener(e -> { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (URISyntaxException | IOException e1) { e1.printStackTrace(); } } } }); // Set initial text infoPane.setText(bukkitInfo); // Set type bukkitRadioButton.addChangeListener(e -> { if (type != Type.BUKKIT) { type = Type.BUKKIT; infoPane.setText(bukkitInfo); creator.setType(type); creator.setSettings(new BukkitSettings()); } }); spigotRadioButton.addChangeListener(e -> { if (type != Type.SPIGOT) { type = Type.SPIGOT; infoPane.setText(spigotInfo); creator.setType(type); creator.setSettings(new BukkitSettings()); } }); paperRadioButton.addChangeListener(e -> { if (type != Type.PAPER) { type = Type.PAPER; infoPane.setText(paperInfo); creator.setType(type); creator.setSettings(new BukkitSettings()); } }); spongeRadioButton.addChangeListener(e -> { if (type != Type.SPONGE) { type = Type.SPONGE; infoPane.setText(spongeInfo); creator.setType(type); creator.setSettings(new SpongeSettings()); } }); bungeecordRadioButton.addChangeListener(e -> { if (type != Type.BUNGEECORD) { type = Type.BUNGEECORD; infoPane.setText(bungeeCordInfo); creator.setType(type); creator.setSettings(new BungeeCordSettings()); } }); return panel; } @Override public void updateDataModel() {} }
package com.esotericsoftware.kryo.serializers; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** Serializes objects that implement the {@link Map} interface. * <p> * With the default constructor, a map requires a 1-3 byte header and an extra 4 bytes is written for each key/value pair. * @author Nathan Sweet <misc@n4te.com> */ public class MapSerializer extends Serializer<Map> { private Class keyClass, valueClass; private Serializer keySerializer, valueSerializer; private boolean keysCanBeNull = true, valuesCanBeNull = true; private Class keyGenericType, valueGenericType; /** @param keysCanBeNull False if all keys are not null. This saves 1 byte per key if keyClass is set. True if it is not known * (default). */ public void setKeysCanBeNull (boolean keysCanBeNull) { this.keysCanBeNull = keysCanBeNull; } /** @param keyClass The concrete class of each key. This saves 1 byte per key. Set to null if the class is not known or varies * per key (default). * @param keySerializer The serializer to use for each key. */ public void setKeyClass (Class keyClass, Serializer keySerializer) { this.keyClass = keyClass; this.keySerializer = keySerializer; } /** @param valueClass The concrete class of each value. This saves 1 byte per value. Set to null if the class is not known or * varies per value (default). * @param valueSerializer The serializer to use for each value. */ public void setValueClass (Class valueClass, Serializer valueSerializer) { this.valueClass = valueClass; this.valueSerializer = valueSerializer; } /** @param valuesCanBeNull True if values are not null. This saves 1 byte per value if keyClass is set. False if it is not known * (default). */ public void setValuesCanBeNull (boolean valuesCanBeNull) { this.valuesCanBeNull = valuesCanBeNull; } public void setGenerics (Kryo kryo, Class[] generics) { if (generics != null) { if (generics.length > 0 && generics[0] != null && kryo.isFinal(generics[0])) keyGenericType = generics[0]; if (generics.length > 1 && generics[1] != null && kryo.isFinal(generics[1])) valueGenericType = generics[1]; } } public void write (Kryo kryo, Output output, Map map) { int length = map.size(); output.writeInt(length, true); Serializer keySerializer = this.keySerializer; if (keyGenericType != null) { if (keySerializer == null) keySerializer = kryo.getSerializer(keyGenericType); keyGenericType = null; } Serializer valueSerializer = this.valueSerializer; if (valueGenericType != null) { if (valueSerializer == null) valueSerializer = kryo.getSerializer(valueGenericType); valueGenericType = null; } for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Entry entry = (Entry)iter.next(); if (keySerializer != null) { if (keysCanBeNull) kryo.writeObjectOrNull(output, entry.getKey(), keySerializer); else kryo.writeObject(output, entry.getKey(), keySerializer); } else kryo.writeClassAndObject(output, entry.getKey()); if (valueSerializer != null) { if (valuesCanBeNull) kryo.writeObjectOrNull(output, entry.getValue(), valueSerializer); else kryo.writeObject(output, entry.getValue(), valueSerializer); } else kryo.writeClassAndObject(output, entry.getValue()); } } /** Used by {@link #read(Kryo, Input, Class)} to create the new object. This can be overridden to customize object creation, eg * to call a constructor with arguments. The default implementation uses {@link Kryo#newInstance(Class)}. */ protected Map create (Kryo kryo, Input input, Class<Map> type) { return kryo.newInstance(type); } public Map read (Kryo kryo, Input input, Class<Map> type) { Map map = create(kryo, input, type); int length = input.readInt(true); Class keyClass = this.keyClass; Class valueClass = this.valueClass; Serializer keySerializer = this.keySerializer; if (keyGenericType != null) { keyClass = keyGenericType; if (keySerializer == null) keySerializer = kryo.getSerializer(keyClass); keyGenericType = null; } Serializer valueSerializer = this.valueSerializer; if (valueGenericType != null) { valueClass = valueGenericType; if (valueSerializer == null) valueSerializer = kryo.getSerializer(valueClass); valueGenericType = null; } kryo.reference(map); for (int i = 0; i < length; i++) { Object key; if (keySerializer != null) { if (keysCanBeNull) key = kryo.readObjectOrNull(input, keyClass, keySerializer); else key = kryo.readObject(input, keyClass, keySerializer); } else key = kryo.readClassAndObject(input); Object value; if (valueSerializer != null) { if (valuesCanBeNull) value = kryo.readObjectOrNull(input, valueClass, valueSerializer); else value = kryo.readObject(input, valueClass, valueSerializer); } else value = kryo.readClassAndObject(input); map.put(key, value); } return map; } protected Map createCopy (Kryo kryo, Map original) { return kryo.newInstance(original.getClass()); } public Map copy (Kryo kryo, Map original) { Map copy = createCopy(kryo, original); for (Iterator iter = original.entrySet().iterator(); iter.hasNext();) { Entry entry = (Entry)iter.next(); copy.put(kryo.copy(entry.getKey()), kryo.copy(entry.getValue())); } return copy; } }
package com.esotericsoftware.kryo.util; import com.esotericsoftware.kryo.ClassResolver; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.Registration; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import static com.esotericsoftware.kryo.util.Util.*; import static com.esotericsoftware.minlog.Log.*; /** Resolves classes by ID or by fully qualified class name. * @author Nathan Sweet <misc@n4te.com> */ public class DefaultClassResolver implements ClassResolver { static public final byte NAME = -1; protected Kryo kryo; protected final IntMap<Registration> idToRegistration = new IntMap(); protected final ObjectMap<Class, Registration> classToRegistration = new ObjectMap(); protected IdentityObjectIntMap<Class> classToNameId; protected IntMap<Class> nameIdToClass; protected ObjectMap<String, Class> nameToClass; protected int nextNameId; private int memoizedClassId = -1; private Registration memoizedClassIdValue; public void setKryo (Kryo kryo) { this.kryo = kryo; } public Registration register (Registration registration) { if (registration == null) throw new IllegalArgumentException("registration cannot be null."); if (TRACE) { if (registration.getId() == NAME) { trace("kryo", "Register class name: " + className(registration.getType()) + " (" + registration.getSerializer().getClass().getName() + ")"); } else { trace("kryo", "Register class ID " + registration.getId() + ": " + className(registration.getType()) + " (" + registration.getSerializer().getClass().getName() + ")"); } } classToRegistration.put(registration.getType(), registration); idToRegistration.put(registration.getId(), registration); if (registration.getType().isPrimitive()) classToRegistration.put(getWrapperClass(registration.getType()), registration); return registration; } public Registration registerImplicit (Class type) { return register(new Registration(type, kryo.getDefaultSerializer(type), NAME)); } /** If the class is not registered and {@link Kryo#setRegistrationRequired(boolean)} is false, it is automatically registered * using the {@link Kryo#addDefaultSerializer(Class, Class) default serializer}. */ public Registration getRegistration (Class type) { return classToRegistration.get(type); } public Registration getRegistration (int classID) { return idToRegistration.get(classID); } public Registration writeClass (Output output, Class type) { if (type == null) { if (TRACE || (DEBUG && kryo.getDepth() == 1)) log("Write", null); output.writeByte(Kryo.NULL); return null; } Registration registration = kryo.getRegistration(type); if (registration.getId() == NAME) writeName(output, type, registration); else { if (TRACE) trace("kryo", "Write class " + registration.getId() + ": " + className(type)); output.writeInt(registration.getId() + 2, true); } return registration; } protected void writeName (Output output, Class type, Registration registration) { output.writeByte(NAME + 2); if (classToNameId != null) { int nameId = classToNameId.get(type, -1); if (nameId != -1) { if (TRACE) trace("kryo", "Write class name reference " + nameId + ": " + className(type)); output.writeInt(nameId, true); return; } } // Only write the class name the first time encountered in object graph. if (TRACE) trace("kryo", "Write class name: " + className(type)); int nameId = nextNameId++; if (classToNameId == null) classToNameId = new IdentityObjectIntMap(); classToNameId.put(type, nameId); output.writeInt(nameId, true); output.writeString(type.getName()); } public Registration readClass (Input input) { int classID = input.readInt(true); switch (classID) { case Kryo.NULL: if (TRACE || (DEBUG && kryo.getDepth() == 1)) log("Read", null); return null; case NAME + 2: // Offset for NAME and NULL. return readName(input); } if (classID == memoizedClassId) return memoizedClassIdValue; Registration registration = idToRegistration.get(classID - 2); if (registration == null) throw new KryoException("Encountered unregistered class ID: " + (classID - 2)); if (TRACE) trace("kryo", "Read class " + (classID - 2) + ": " + className(registration.getType())); memoizedClassId = classID; memoizedClassIdValue = registration; return registration; } protected Registration readName (Input input) { int nameId = input.readInt(true); if (nameIdToClass == null) nameIdToClass = new IntMap(); Class type = nameIdToClass.get(nameId); if (type == null) { // Only read the class name the first time encountered in object graph. String className = input.readString(); if (nameToClass != null) type = nameToClass.get(className); if (type == null) { try { type = Class.forName(className, false, kryo.getClassLoader()); } catch (ClassNotFoundException ex) { throw new KryoException("Unable to find class: " + className, ex); } if (nameToClass == null) nameToClass = new ObjectMap(); nameToClass.put(className, type); } nameIdToClass.put(nameId, type); if (TRACE) trace("kryo", "Read class name: " + className); } else { if (TRACE) trace("kryo", "Read class name reference " + nameId + ": " + className(type)); } return kryo.getRegistration(type); } public void reset () { if (!kryo.isRegistrationRequired()) { if (classToNameId != null) classToNameId.clear(); if (nameIdToClass != null) nameIdToClass.clear(); nextNameId = 0; } } }
package com.github.assisstion.ModulePack.helper; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.github.assisstion.ModulePack.Pair; import com.github.assisstion.ModulePack.annotation.Dependency; @Dependency(Pair.class) public final class ArrayHelper{ private ArrayHelper(){} public static <T> int arrayCounter(T[] x){ int z = 0; for(int i = 0; i < x.length; i++){ T y = x[i]; if(y != null){ z++; } } return z; } public static <T> T[] arrayCopy(T[] x){ return arrayCopy(x, true); } public static <T> T[] arrayCopy(T[] x, boolean notNull){ int z = 0; T[] l = x.clone(); for(int i = 0; i < x.length; i++){ T y = x[i]; l[i] = null; if(!notNull || y != null){ l[z] = y; z++; } } T[] n = Arrays.copyOf(l, z); return n; } public static int[] arrayCopy(int[] x){ return arrayCopy(x, false); } public static int[] arrayCopy(int[] x, boolean notZero){ int z = 0; int[] l = new int[x.length + 1]; for(int i = 0; i < x.length; i++){ int y = x[i]; if(!notZero || y != 0){ l[z] = y; z++; } } int[] n = new int[z]; System.arraycopy(l, 0, n, 0, z); return n; } public static byte[] arrayCopy(byte[] x){ return arrayCopy(x, false); } public static byte[] arrayCopy(byte[] x, boolean notZero){ int z = 0; byte[] l = new byte[x.length + 1]; for(int i = 0; i < x.length; i++){ byte y = x[i]; if(!notZero || y != 0){ l[z] = y; z++; } } byte[] n = new byte[z]; System.arraycopy(l, 0, n, 0, z); return n; } public static char[] arrayCopy(char[] x){ return arrayCopy(x, false); } public static char[] arrayCopy(char[] x, boolean notZero){ int z = 0; char[] l = new char[x.length + 1]; for(int i = 0; i < x.length; i++){ char y = x[i]; if(!notZero || y != 0){ l[z] = y; z++; } } char[] n = new char[z]; System.arraycopy(l, 0, n, 0, z); return n; } public static <T> T[] arrayCopy(T[] x, int size){ int z = 0; T[] l = x.clone(); for(int i = 0; i < x.length; i++){ T y = x[i]; l[i] = null; if(y != null){ l[z] = y; z++; } } T[] n = Arrays.copyOf(l, size); return n; } public static <T> void arrayPrint(T[] x){ arrayPrint(x, "\n", true); } public static <T> void arrayPrint(T[] x, String separator){ arrayPrint(x, separator, false); } public static <T> void arrayPrint(T[] x, String separator, boolean finalSep){ T[] b = x;//arrayCopy(x); boolean first = true; for(int n = 0; n < b.length; n++){ if(first){ first = false; } else{ System.out.print(separator); } T w = b[n]; System.out.print(w); } if(finalSep){ System.out.print(separator); } } /* public static boolean contains(Object[] x, Object y){ for(int i = 0; i < x.length; i++){ if(x[i] == y){ return true; } } return false; } */ public static <T, S extends T> boolean containsArray(T[] x, S[] y){ for(int j = 0; j < y.length; j++){ for(int i = 0; i < x.length; i++){ if(x[i].equals(y[j])){ return true; } } } return false; } public static <T, S extends T> int positionIn(T[] x, S y){ return firstIndexOf(x, y); } public static void arrayPrint(int[] x) { int[] b = x;//arrayCopy(x); for(int n = 0; n < b.length; n++){ int w = b[n]; System.out.println(w); } } public static void arrayPrint(byte[] x) { byte[] b = x;//arrayCopy(x); for(int n = 0; n < b.length; n++){ byte w = b[n]; System.out.println(w); } } public static void arrayPrint(char[] x) { char[] b = x;//arrayCopy(x); for(int n = 0; n < b.length; n++){ char w = b[n]; System.out.println(w); } } public static <T, S extends T> boolean contains(T[] x, S y){ for(int i = 0; i < x.length; i++){ if(x[i].equals(y)){ return true; } } return false; } public static <T, S extends T> Set<Integer> indexOf(T[] x, S y){ HashSet<Integer> integers = new HashSet<Integer>(); for(int i = 0; i < x.length; i++){ if(x[i].equals(y)){ integers.add(i); } } return integers; } public static <T, S extends T> int firstIndexOf(T[] x, S y){ return nthIndexOf(x, y, 0); } //Index n, not numeral n public static <T, S extends T> int nthIndexOf(T[] x, S y, int n){ int counter = 0; for(int i = 0; i < x.length; i++){ if(x[i].equals(y)){ if(counter >= n){ return i; } else{ counter++; } } } return -1; } public static <T, S extends T> int lastIndexOf(T[] x, S y, int n){ int lastFound = -1; for(int i = 0; i < x.length; i++){ if(x[i].equals(y)){ lastFound = i; } } return lastFound; } public static <T, S extends T> Set<Pair<Integer, Integer>> indexOf(T[][] x, S y){ HashSet<Pair<Integer, Integer>> integers = new HashSet<Pair<Integer, Integer>>(); for(int i = 0; i < x.length; i++){ for(int j = 0; j < x[i].length; j++){ if(x[i][j].equals(y)){ integers.add(new Pair<Integer, Integer>(i, j)); } } } return integers; } public static <T, S extends T> Pair<Integer, Integer> firstIndexOf(T[][] x, S y){ return nthIndexOf(x, y, 0); } public static <T, S extends T> Pair<Integer, Integer> nthIndexOf(T[][] x, S y, int n){ int counter = 0; for(int i = 0; i < x.length; i++){ for(int j = 0; j < x[i].length; j++){ if(x[i][j].equals(y)){ if(counter >= n){ return new Pair<Integer, Integer>(i, j); } else{ counter++; } } } } return null; } public static <T, S extends T> Pair<Integer, Integer> lastIndexOf(T[][] x, S y){ Pair<Integer, Integer> lastFound = null; for(int i = 0; i < x.length; i++){ for(int j = 0; j < x[i].length; j++){ if(x[i][j].equals(y)){ lastFound = new Pair<Integer, Integer>(i, j); } } } return lastFound; } }
package com.googlecode.charts4j.parameters; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import com.googlecode.charts4j.AxisTextAlignment; import com.googlecode.charts4j.Color; import com.googlecode.charts4j.Data; import com.googlecode.charts4j.DataEncoding; import com.googlecode.charts4j.GeographicalArea; import com.googlecode.charts4j.LegendPosition; import com.googlecode.charts4j.LineStyle; import com.googlecode.charts4j.Marker; import com.googlecode.charts4j.Priority; import com.googlecode.charts4j.collect.ImmutableList; import com.googlecode.charts4j.collect.Lists; import com.googlecode.charts4j.collect.Maps; /** * <b>For Charts4J internal use only.</b> The ParameterManager contains all * the parameters for a given chart that is being built up. These parameters * will eventually be serialized to a string. * * @author Julien Chastang (julien.c.chastang at gmail dot com) */ public final class ParameterManager { /** The parameter map. */ private final Map<Class<? extends Parameter>, Parameter> parameterMap = Maps.newHashMap(); /** The Google Chart API URL. */ private final String url; /** * Instantiates a new parameter manager with the Google Chart API URL. * * @param url * the url */ public ParameterManager(final String url) { this.url = url; } /** * Inits the. */ public void init() { parameterMap.clear(); } /** * Adds the axis label position. * * @param index * the index * @param positions * the positions */ public void addAxisLabelPosition(final int index, final ImmutableList<? extends Number> positions) { getParameter(AxisLabelPositionsParameter.class).addLabelPosition(index, positions); } /** * Adds the axis labels. * * @param index * the index * @param labels * the labels */ public void addAxisLabels(final int index, final ImmutableList<? extends String> labels) { getParameter(AxisLabelsParameter.class).addAxisLabels(index, labels); } /** * Adds the axis range. * * @param index * the index * @param startOfRange * the start of range * @param endOfRange * the end of range */ public void addAxisRange(final int index, final double startOfRange, final double endOfRange) { getParameter(AxisRangesParameter.class).addAxisRange(index, startOfRange, endOfRange); } /** * Adds the axis style. * * @param index * the index * @param color * the color * @param fontSize * the font size * @param alignment * the alignment */ public void addAxisStyle(final int index, final Color color, final int fontSize, final AxisTextAlignment alignment) { getParameter(AxisStylesParameter.class).addAxisStyle(index, color, fontSize, alignment); } /** * Adds the axis types. * * @param axisTypes * the axis types */ public void addAxisTypes(final AxisTypes axisTypes) { getParameter(AxisTypesParameter.class).addAxisTypes(axisTypes); } /** * Sets the bar chart width and spacing parameter. * * @param width * the width * @param spaceBetweenBarsInGroup * the space between bars in group * @param spaceBetweenGroups * the space between groups */ public void setBarChartWidthAndSpacingParameter(final int width, final int spaceBetweenBarsInGroup, final int spaceBetweenGroups) { final BarChartWidthAndSpacingParameter p = new BarChartWidthAndSpacingParameter(width, spaceBetweenBarsInGroup, spaceBetweenGroups); parameterMap.put(BarChartWidthAndSpacingParameter.class, p); } /** * Sets the bar chart zero line parameter. * * @param d * the new bar chart zero line parameter */ public void setBarChartZeroLineParameter(final double d) { getParameter(BarChartZeroLinesParameter.class).addZeroLine(d); } /** * Adds the linear gradient fill. * * @param fillType * the fill type * @param angle * the angle * @param colorAndOffsets * the color and offsets */ public void addLinearGradientFill(final FillType fillType, final int angle, final ImmutableList<? extends ColorAndOffset> colorAndOffsets) { getParameter(ChartFillsParameter.class).addLinearGradientFill(fillType, angle, colorAndOffsets); } /** * Adds the linear stripe fill. * * @param fillType * the fill type * @param angle * the angle * @param colorAndWidths * the color and widths */ public void addLinearStripeFill(final FillType fillType, final int angle, final ImmutableList<? extends ColorAndWidth> colorAndWidths) { getParameter(ChartFillsParameter.class).addLinearStripeFill(fillType, angle, colorAndWidths); } /** * Adds the solid fill. * * @param solidFillType * the solid fill type * @param color * the color */ public void addSolidFill(final SolidFillType solidFillType, final Color color) { getParameter(ChartFillsParameter.class).addSolidFill(solidFillType, color); } /** * Adds the fill area marker. * * @param fillAreaType * the fill area type * @param color * the color * @param startLineIndex * the start line index * @param endLineIndex * the end line index */ public void addFillAreaMarker(final FillAreaType fillAreaType, final Color color, final int startLineIndex, final int endLineIndex) { getParameter(ChartMarkersParameter.class).addFillAreaMarker(fillAreaType, color, startLineIndex, endLineIndex); } /** * Adds the line style marker. * * @param color * the color * @param dataSetIndex * the data set index * @param dataPoint * the data point * @param size * the size * @param priority * the priority */ public void addLineStyleMarker(final Color color, final int dataSetIndex, final int dataPoint, final int size, final Priority priority) { getParameter(ChartMarkersParameter.class).addLineStyleMarker(color, dataSetIndex, dataPoint, size, priority); } /** * Add a marker to the plot. * * @param marker * the marker * @param dataSetIndex * the data set index * @param dataPoint * the data point */ public void addMarker(final Marker marker, final int dataSetIndex, final int dataPoint) { getParameter(ChartMarkersParameter.class).addMarker(marker, dataSetIndex, dataPoint); } /** * Add markers to each point on the plot. * * @param marker * the marker * @param dataSetIndex * the data set index */ public void addMarkers(final Marker marker, final int dataSetIndex) { getParameter(ChartMarkersParameter.class).addMarkers(marker, dataSetIndex); } /** * Adds the vertical range marker. * * @param color * the color * @param startPoint * the start point * @param endPoint * the end point */ public void addVerticalRangeMarker(final Color color, final double startPoint, final double endPoint) { getParameter(ChartMarkersParameter.class).addVerticalRangeMarker(color, startPoint, endPoint); } /** * Adds the horizontal range marker. * * @param color * the color * @param startPoint * the start point * @param endPoint * the end point */ public void addHorizontalRangeMarker(final Color color, final double startPoint, final double endPoint) { getParameter(ChartMarkersParameter.class).addHorizontalRangeMarker(color, startPoint, endPoint); } /** * Sets the chart size parameter. * * @param width * the width * @param height * the height */ public void setChartSizeParameter(final int width, final int height) { final ChartSizeParameter p = new ChartSizeParameter(width, height); parameterMap.put(ChartSizeParameter.class, p); } /** * Sets the chart title color and size parameter. * * @param color * the color * @param fontSize * the font size */ public void setChartTitleColorAndSizeParameter(final Color color, final int fontSize) { final ChartTitleColorAndSizeParameter p = new ChartTitleColorAndSizeParameter(color, fontSize); parameterMap.put(ChartTitleColorAndSizeParameter.class, p); } /** * Sets the chart title parameter. * * @param title * the new chart title parameter */ public void setChartTitleParameter(final String title) { final ChartTitleParameter p = new ChartTitleParameter(title); parameterMap.put(ChartTitleParameter.class, p); } /** * Sets the chart type parameter. * * @param chartType * the new chart type parameter */ public void setChartTypeParameter(final ChartType chartType) { final ChartTypeParameter p = new ChartTypeParameter(chartType); parameterMap.put(ChartTypeParameter.class, p); } /** * Adds the color. * * @param color * the color */ public void addColor(final Color color) { getParameter(ColorsParameter.class).addColors(Lists.of(color)); } /** * Adds the colors. * * @param colors * the colors */ public void addColors(final ImmutableList<? extends Color> colors) { getParameter(ColorsParameter.class).addColors(colors); } /** * Adds the legend. * * @param legend * the legend */ public void addLegend(final String legend) { getParameter(DataLegendsParameter.class).addLegends(Lists.of(legend)); } /** * Adds the legends. * * @param legends * the legends */ public void addLegends(final ImmutableList<? extends String> legends) { getParameter(DataLegendsParameter.class).addLegends(legends); } /** * Adds the data. * * @param data * the data */ public void addData(final Data data) { getParameter(DataParameter.class).addData(data); } /** * Sets the data encoding. * * @param dataEncoding * the new data encoding */ public void setDataEncoding(final DataEncoding dataEncoding) { getParameter(DataParameter.class).setDataEncoding(dataEncoding); } /** * Adds the geo code. * * @param geoCode * the geo code */ public void addGeoCode(final String geoCode) { getParameter(GeoCodesParameter.class).addGeoCode(geoCode); } /** * Sets the geographical area parameter. * * @param geographicalArea * the new geographical area parameter */ public void setGeographicalAreaParameter(final GeographicalArea geographicalArea) { final GeographicalAreaParameter p = new GeographicalAreaParameter(geographicalArea); parameterMap.put(GeographicalAreaParameter.class, p); } /** * Sets the grid line parameter. * * @param xAxisStepSize * the x axis step size * @param yAxisStepSize * the y axis step size * @param lengthOfLineSegment * the length of line segment * @param lengthOfBlankSegment * the length of blank segment */ public void setGridLineParameter(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment) { final GridLineParameter p = new GridLineParameter(xAxisStepSize, yAxisStepSize, lengthOfLineSegment, lengthOfBlankSegment); parameterMap.put(GridLineParameter.class, p); } /** * Sets the legend position parameter. * * @param legendPosition * the new legend position parameter */ public void setLegendPositionParameter(final LegendPosition legendPosition) { final LegendPositionParameter p = new LegendPositionParameter(legendPosition); parameterMap.put(LegendPositionParameter.class, p); } /** * Adds the line chart line style. * * @param lineStyle * the line style */ public void addLineChartLineStyle(final LineStyle lineStyle) { getParameter(LineChartLineStylesParameter.class).addLineStyle(lineStyle); } /** * Adds the pie chart and google o meter legend. * * @param legend * the legend */ public void addPieChartAndGoogleOMeterLegend(final String legend) { getParameter(PieChartAndGoogleOMeterLegendParameter.class).addLegend(legend); } /** * {@inheritDoc} */ @Override public String toString() { final Collection<Parameter> c = parameterMap.values(); final List<String> parameters = Lists.newLinkedList(); for (Parameter p : c) { final String paramString = p.toURLParameterString(); if (!"".equals(paramString)) { parameters.add(paramString); } } Collections.sort(parameters, new Comparator<String>() { public int compare(final String s1, final String s2) { return s1.length() - s2.length(); } }); int cnt = 0; final StringBuilder sb = new StringBuilder(url + "?"); for (String p : parameters) { sb.append(cnt++ > 0 ? "&" + p : p); } return sb.toString(); } /** * Get the parameter. * * @param <T> * type of parameter to retrieve * @param clazz * the class of the parameter to retrieve * * @return the parameter * @throws ParameterInstantiationException * if the parameter could not be instantiated */ private <T extends Parameter> T getParameter(final Class<T> clazz) throws ParameterInstantiationException { //Should always be safe. @SuppressWarnings("unchecked") T p = (T) parameterMap.get(clazz); if (p == null) { try { p = clazz.newInstance(); } catch (InstantiationException e) { throw new ParameterInstantiationException("Internal error: Could not instatiate " + clazz.getName(), e); } catch (IllegalAccessException e) { throw new ParameterInstantiationException("Internal error: Could not instatiate " + clazz.getName(), e); } parameterMap.put(clazz, p); } return p; } /** * The exception class for cases where the parameter cannot be instantiated * through reflection. */ public static class ParameterInstantiationException extends RuntimeException { /** The serial version uid. */ private static final long serialVersionUID = -7837316818196725716L; /** * Instantiates a new parameter instantiation exception. * * @param message * the message * @param cause * the cause */ private ParameterInstantiationException(final String message, final Throwable cause) { super(message, cause); } } }
package cmcc.iot.onenet.javasdk; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONObject; import org.junit.Test; import cmcc.iot.onenet.javasdk.api.bindata.AddBindataApi; import cmcc.iot.onenet.javasdk.api.bindata.GetBindataApi; import cmcc.iot.onenet.javasdk.api.cmds.QueryCmdsRespApi; import cmcc.iot.onenet.javasdk.api.cmds.QueryCmdsStatus; import cmcc.iot.onenet.javasdk.api.cmds.SendCmdsApi; import cmcc.iot.onenet.javasdk.api.datapoints.AddDatapointsApi; import cmcc.iot.onenet.javasdk.api.datapoints.GetDatapointsListApi; import cmcc.iot.onenet.javasdk.api.datastreams.AddDatastreamsApi; import cmcc.iot.onenet.javasdk.api.datastreams.DeleteDatastreamsApi; import cmcc.iot.onenet.javasdk.api.datastreams.FindDatastreamListApi; import cmcc.iot.onenet.javasdk.api.datastreams.GetDatastreamApi; import cmcc.iot.onenet.javasdk.api.datastreams.ModifyDatastramsApi; import cmcc.iot.onenet.javasdk.api.device.AddDevicesApi; import cmcc.iot.onenet.javasdk.api.device.DeleteDeviceApi; import cmcc.iot.onenet.javasdk.api.device.FindDevicesListApi; import cmcc.iot.onenet.javasdk.api.device.GetDeviceApi; import cmcc.iot.onenet.javasdk.api.device.ModifyDevicesApi; import cmcc.iot.onenet.javasdk.api.device.RegisterDeviceApi; import cmcc.iot.onenet.javasdk.api.key.AddKeyApi; import cmcc.iot.onenet.javasdk.api.key.DeleteKeyApi; import cmcc.iot.onenet.javasdk.api.key.FindKeyList; import cmcc.iot.onenet.javasdk.api.key.ModifyKeyApi; import cmcc.iot.onenet.javasdk.api.mqtt.CreateMqttTopicApi; import cmcc.iot.onenet.javasdk.api.mqtt.DeleteUserTopic; import cmcc.iot.onenet.javasdk.api.mqtt.FindTopicDevices; import cmcc.iot.onenet.javasdk.api.mqtt.GetDevicesTopicsApi; import cmcc.iot.onenet.javasdk.api.mqtt.GetUserTopics; import cmcc.iot.onenet.javasdk.api.mqtt.SendMqttApi; import cmcc.iot.onenet.javasdk.api.triggers.AddTriggersApi; import cmcc.iot.onenet.javasdk.api.triggers.DeleteTriggersApi; import cmcc.iot.onenet.javasdk.api.triggers.FindTriggersListApi; import cmcc.iot.onenet.javasdk.api.triggers.GetTriggersApi; import cmcc.iot.onenet.javasdk.api.triggers.ModifyTriggersApi; import cmcc.iot.onenet.javasdk.model.Data; import cmcc.iot.onenet.javasdk.model.Datapoints; import cmcc.iot.onenet.javasdk.model.Devices; import cmcc.iot.onenet.javasdk.model.Location; import cmcc.iot.onenet.javasdk.model.Permissions; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.response.bindata.NewBindataResponse; import cmcc.iot.onenet.javasdk.response.cmds.CmdsResponse; import cmcc.iot.onenet.javasdk.response.cmds.NewCmdsResponse; import cmcc.iot.onenet.javasdk.response.datapoints.DatapointsList; import cmcc.iot.onenet.javasdk.response.datastreams.DatastreamsResponse; import cmcc.iot.onenet.javasdk.response.datastreams.NewdatastramsResponse; import cmcc.iot.onenet.javasdk.response.device.DeviceList; import cmcc.iot.onenet.javasdk.response.device.DeviceResponse; import cmcc.iot.onenet.javasdk.response.device.NewDeviceResponse; import cmcc.iot.onenet.javasdk.response.device.RegDeviceResponse; import cmcc.iot.onenet.javasdk.response.key.KeyList; import cmcc.iot.onenet.javasdk.response.key.NewKeyResponse; import cmcc.iot.onenet.javasdk.response.mqtt.TopicDeviceList; import cmcc.iot.onenet.javasdk.response.triggers.NewTriggersResponse; import cmcc.iot.onenet.javasdk.response.triggers.TriggersList; import cmcc.iot.onenet.javasdk.response.triggers.TriggersResponse; public class ApiTest { @Test public void testAdddevices() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String title = "devices_test"; String desc = "devices_test"; String protocol = "HTTP"; Location location =new Location(106,29,370); List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String auth_info = "201503041a5829151"; /**** * * * @param title String * @param protocol HTTP,String * @param desc ,String * @param tags ,List<String> * @param location {"", "", ""},Location * @param isPrivate ,Booleanture * @param authInfo ,Object * @param other ,Map<String, Object> * @param interval MODBUS ,Integer * @param key masterkey,String */ AddDevicesApi api = new AddDevicesApi(title, protocol, desc, tags, location, null, auth_info, null, null, key); BasicResponse<NewDeviceResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testModifydevices() { String id = "1674527"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String title = "devices_test2"; String desc = "devices_test2"; String protocol = "HTTP"; List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String auth_info = "201503041a5829151"; /*** * * * @param id ID,String * @param title String * @param protocol HTTPString * @param desc String * @param tags List<String> * @param location {"", "", ""},Location * @param isPrivate Boolean * @param authInfo Object * @param other Map<String, Object> * @param interval MODBUS ,Integer * @param key masterkey apikey,String */ ModifyDevicesApi api = new ModifyDevicesApi(id, title, protocol, desc, tags,null,null,auth_info, null, null,key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetdevice() { String id = "1674527"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * * @param devid:String * @param key:masterkey apikey,String */ GetDeviceApi api = new GetDeviceApi(id, key); BasicResponse<DeviceResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testFinddevicesList() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * * @param keywords:idtitle,String * @param authinfo:sn,Object * @param devid: ID100,String * @param begin:,Date * @param end:,Date * @param tags:,List<String> * @param isPrivate Boolean * @param page:10000,Integer * @param perpage:30100,Integer * @param isOnline: * @param key:masterkey */ FindDevicesListApi api = new FindDevicesListApi(null, null, null, null, null, null, null, null, null, null, key); BasicResponse<DeviceList> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testRemovedevice() { String id = "1674526"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * * @param devid: ID,String * @param key: masterkey key */ DeleteDeviceApi api = new DeleteDeviceApi(id, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testRegisterDeviceApi() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String sn = "2017031401421"; String title = "myddddvvv2s"; String code = "ZSAuX3f1QPNp2n1m"; /** * * * @param code,String * @param macmac32 * @param snString512 * @param title: 32 * @param key: */ RegisterDeviceApi api = new RegisterDeviceApi(code, null, sn, title, key); BasicResponse<RegDeviceResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getData().key); } @Test public void testAddDatastreamsApi() { String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String id = "temperature2"; String devId = "1674527"; List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String unit = "celsius"; String unitsymbol = "C"; String cmd = "0003000000184411"; int interval = 60; String formula = "(A0+A1)*A2"; /** * * @param id String * @param devId:ID,String * @param tags:,List<Stirng> * @param unit:,String * @param unitSymbol:,String * @param cmd:MODBUS16 * @param interval:MODBUS,Integer * @param formula:MODBUS,String * @param key:masterkey apikey */ AddDatastreamsApi api = new AddDatastreamsApi(id, devId, tags, unit, unitsymbol, cmd, interval, formula, key); BasicResponse<NewdatastramsResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getData().id); } @Test public void testModifyDatastreamsApi() { String dsid = "temperature2"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String devId = "1674527"; List<String> tags = new ArrayList<String>(); tags.add("china"); tags.add("mobile"); String unit = "celsius"; String unitsymbol = "C"; String cmd = "0003000000184411"; int interval = 80; String formula = "(A0+A1)*A2"; /** * * @param dsid: ,String * @param devId:ID,String * @param tags: * @param unit:,String * @param unitSymbol:,String * @param cmd:MODBUS16 * @param interval:MODBUS,Integer * @param formula:MODBUS,String * @param key:masterkey apikey */ ModifyDatastramsApi api = new ModifyDatastramsApi(dsid, devId, tags, unit, unitsymbol, cmd, interval, formula, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetDatastream() { String devId = "212141"; String id = "datastream_idxx"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param devid:ID,String * @param datastreamid: ,String * @param key:masterkey apikey */ GetDatastreamApi api = new GetDatastreamApi(devId, id, key); BasicResponse<DatastreamsResponse> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getData().getId()); } @Test public void testFindDatastreamsListApi() { String datastreamids = "datastream_idxx,datastream_idxy"; String devid = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param datastreamids: ,String * @param devid:ID,String * @param key:masterkey apikey */ FindDatastreamListApi api = new FindDatastreamListApi(datastreamids, devid, key); BasicResponse<List<DatastreamsResponse>> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); System.out.println(response.getJson()); } @Test public void testRemoveDatastreamApi() { String dsid = "temperature2"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; String devId = "1674527"; /** * * @param devid:ID,String * @param datastreamid: ,String * @param key:masterkey apikey */ DeleteDatastreamsApi api = new DeleteDatastreamsApi(devId, dsid, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testAddDatapointsApi() { String devid = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; List<Datapoints> list = new ArrayList<Datapoints>(); List<Data> dl = new ArrayList<Data>(); dl.add(new Data("2013-04-22T00:35:43", 11)); dl.add(new Data("2013-04-22T00:36:43", 12)); list.add(new Datapoints("datastream_idxx", dl)); list.add(new Datapoints("datastream_idxy", dl)); Map<String, List<Datapoints>> map = new HashMap<String, List<Datapoints>>(); map.put("datastreams", list); /** * * @param map :,Map<String,List<Datapoints>> * @param data:,String * * type=4 * data="{\"temperature\":{\"2015-03-22T22:31:12\":22.5}}"; * type=5 * data=",;temperature,2015-03-22T22:31:12,22.5;pm2.5,89"; * @param type:JSONHTTP * @param devId:ID,String * @param key:masterkey apikey */ AddDatapointsApi api = new AddDatapointsApi(map, null, null, devid, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } //type=4 @Test public void testAddDatapointsTypefourApi() { String devid = "212141"; int type=4; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; String data="{\"datastream_idxx\":{\"2015-03-22T22:31:12\":22.5}}"; /** * * @param map :,Map<String,List<Datapoints>> * @param data:,String * * type=4 * data="{\"temperature\":{\"2015-03-22T22:31:12\":22.5}}"; * type=5 * data=",;temperature,2015-03-22T22:31:12,22.5;pm2.5,89"; * @param type:JSONHTTP * @param devId:ID,String * @param key:masterkey apikey */ AddDatapointsApi api = new AddDatapointsApi(null, data, type, devid, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetDatapointsApi() { String datastreamids = "datastream_idxx,datastream_idxy"; String devid = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param datastreamids:,String * @param start:,String * @param end:,String * @param devid:ID,String * * @param duration:,Integer * start+durationstart * end+durationend * * @param limit:0<n<=60001440,Integer * @param cursor:cursor,Integer * @param interval:interval,Integer * @param metd:,String * @param first:1-0-1,Integer * @param sort:DESC|ASCDESC:ASC,String * @param key:masterkey apikey */ GetDatapointsListApi api = new GetDatapointsListApi(datastreamids, null, null, devid, null, null, null, null, null, null, null, key); BasicResponse<DatapointsList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testAddtriggersApi() { String dsid = "datastream_idxx"; String url = "http://xx.bb.com"; String type = "=="; int threshold = 100; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param title:,String * @param dsid:id,String * @param devids:ID,List<String> * @param dsuuids:uuid,List<String> * @param desturl:url,String * @param type:String * @param threshold:type,Integer * @param key:masterkey apikey */ AddTriggersApi api = new AddTriggersApi(null, dsid, null, null, url, type, threshold, key); BasicResponse<NewTriggersResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testModifyTriggersApi() { String url = "http://xx.bbc.com"; String type = "=="; int threshold = 100; List<String> dsuuids = new ArrayList<String>(); dsuuids.add("28ccffa8-9eab-53d0-8365-84928950c473"); String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; String tirggerid = "288"; /** * * @param tirggerid:ID,String * @param title:,String * @param dsidid,String * @param devids:ID,List<String> * @param dsuuids:uuid,List<String> * @param desturl:url,String * @param type:String * @param threshold:type,Integer * @param key:masterkey apikey */ ModifyTriggersApi api = new ModifyTriggersApi(tirggerid, null, null, null, dsuuids, url, type, threshold, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testGetTriggersApi() { String tirggerid = "288"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param tirggerid:ID,String * @param key:masterkey apikey */ GetTriggersApi api = new GetTriggersApi(tirggerid, key); BasicResponse<TriggersResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testFindTriggersListApi() { String title = "test"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param title:,String * @param page:10000,Integer * @param perpage:30100,Integer * @param key:masterkey apikey */ FindTriggersListApi api = new FindTriggersListApi(title, null, null, key); BasicResponse<TriggersList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testRemoveTriggersApi() { String tirggerid = "3228"; String key = "9ylHzkz25nre41i=SuJR=F=k5kU="; /** * * @param tirggerid:ID,String * @param key:masterkey apikey */ DeleteTriggersApi api = new DeleteTriggersApi(tirggerid, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testAddBindataApi() { String devId = "212141"; String datastreamid = "datastream_idxy"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; String filename = "a"; String filepath = "E://data.txt"; /** * * * @param devId:,String * @param datastreamid:,String * @param key:masterkey key * @param filename:,String * @param filepath,String */ AddBindataApi api = new AddBindataApi(devId, datastreamid, key, filename, filepath); BasicResponse<NewBindataResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testGetBindataApi() { String index = "212141_1490712458735_datastream_idxx"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * * @param index:,String * @param key:masterkey key */ GetBindataApi api = new GetBindataApi(index, key); System.out.println(api.executeApi()); } @Test public void testAddKeyApi() { String title = "sharing key"; List<Permissions> permissions = new ArrayList<Permissions>(); List<Devices> resources = new ArrayList<Devices>(); List<String> accessMethods = new ArrayList<String>(); resources.add(new Devices("212141")); accessMethods.add("POST"); accessMethods.add("GET"); accessMethods.add("PUT"); permissions.add(new Permissions(resources, accessMethods)); String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; AddKeyApi api = new AddKeyApi(title, permissions, key); BasicResponse<NewKeyResponse> response = api.executeApi(); System.out.println(response.getData().getKey()); System.out.println(response.getJson()); } @Test public void testModifyKeyApi() { String title = "sharing key"; String apikey = "A1HzNFR344JgmZCZ3=O9FsQ9q=s="; List<Permissions> permissions = new ArrayList<Permissions>(); List<Devices> resources = new ArrayList<Devices>(); List<String> accessMethods = new ArrayList<String>(); resources.add(new Devices("212141")); accessMethods.add("POST"); accessMethods.add("GET"); accessMethods.add("PUT"); permissions.add(new Permissions(resources, accessMethods)); String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; ModifyKeyApi api = new ModifyKeyApi(title, apikey, permissions, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testFindKeyList() { String devId = "212141"; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * API key * @param apikeyapikey,String * @param page:10000,Integer * @param perpage:30100,Integer * @param devid,master-key,String * @param keymasterkey(master-key) */ FindKeyList api = new FindKeyList(null, null, null, devId, key); BasicResponse<KeyList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testRemoveKeyApi() { String keystr = "A1HzNFR344JgmZCZ3=O9FsQ9q=s="; String key = "m4EubNp9WCeAxjFu4lVw=kn2idE="; /** * API key * @param keystrapikey,String * @param keymasterkey(master-key) */ DeleteKeyApi api = new DeleteKeyApi(keystr, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testSendBytesCmdsApi() throws IOException { String devId = "9288"; String key = "JKRfIzneAwXLdI6V0Yy83XOavb8="; File file = new File("E://data.txt"); long fileSize = file.length(); FileInputStream fi = new FileInputStream(file); byte[] buffer = new byte[2]; buffer[0] = (byte) (0x61); buffer[1] = (byte) (0x62); /** * * @param devIdIDString * @param qos:0,Integer * 0 * 1(timeout * * type=0 * @param timeOut:0,Integer * 0, * >0 timeout0~2678400 * type=0 * @param type://00CMD_REQ1PUSH_DATA * @param contents:jsonstring64K * @param key:masterkeyapikey */ SendCmdsApi api = new SendCmdsApi(devId, null, null, null, buffer, key); BasicResponse<NewCmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } // String @Test public void testSendStrCmdsApi() throws IOException { String devId = "9288"; String key = "JKRfIzneAwXLdI6V0Yy83XOavb8="; String text = "xxxxxxxxxxxxxxxxx"; /** * * @param devIdIDString * @param qos:0,Integer * 0 * 1(timeout * * type=0 * @param timeOut:0,Integer * 0, * >0 timeout0~2678400 * type=0 * @param type://00CMD_REQ1PUSH_DATA * @param contents:jsonstring64K * @param key:masterkeyapikey */ SendCmdsApi api = new SendCmdsApi(devId, null, null, null, text, key); BasicResponse<NewCmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } // json @Test public void testSendJsonCmdsApi() throws IOException { String devId = "9288"; String key = "JKRfIzneAwXLdI6V0Yy83XOavb8="; JSONObject json = new JSONObject(); json.put("title", "xxxxxxxxxxx"); /** * * @param devIdID,String * @param qos:0,Integer * 0 * 1(timeout * * type=0 * @param timeOut:0,Integer * 0, * >0 timeout0~2678400 * type=0 * @param type://00CMD_REQ1PUSH_DATA * @param contents:jsonstring64K * @param key:masterkeyapikey */ SendCmdsApi api = new SendCmdsApi(devId, null, null, null, json.toString(), key); BasicResponse<NewCmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testQueryCmdsStatusApi(){ String cmdUuid="3a7b478e-f07d-56e6-b312-2362ac15f13f"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * * @param cmduuid:id,String * @param key:masterkeyapikey */ QueryCmdsStatus api=new QueryCmdsStatus(cmdUuid,key); BasicResponse<CmdsResponse> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testQueryCmdsRespApi(){ String cmdUuid="3a7b478e-f07d-56e6-b312-2362ac15f13f"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * * @param cmduuid:id,String * @param key:masterkeyapikey */ QueryCmdsRespApi api=new QueryCmdsRespApi(cmdUuid,key); String response = api.executeApi(); System.out.println(response); } @Test public void testCreateMqttTopicApi(){ String name="testtopic"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * Topic * @param name:,String * @param keymasterkey */ CreateMqttTopicApi api=new CreateMqttTopicApi(name,key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testSendMqttsApi(){ String topic="testtopic"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; JSONObject json = new JSONObject(); json.put("title", "wangxiaojun is laosiji"); /** *Topic * @param topic,String * @param contents:jsonstring64K * @param keymasterkey */ SendMqttApi api = new SendMqttApi(topic, json, key); BasicResponse<Void> response = api.executeApi(); System.out.println("errno:"+response.errno+" error:"+response.error); } @Test public void testFindDevicesListApi(){ String topic="testtopic"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; int page=1; int perPage=1; /** * Topic * @param page. ,1,Integer * @param perPage. 1-1000,Integer * @param topic,String * @param keymasterkey */ FindTopicDevices api=new FindTopicDevices(page, perPage, topic, key); BasicResponse<TopicDeviceList> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testGetTopicsApi(){ String devId="9288"; String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * Topic * @param devIdID,String * @param keymasterkey */ GetDevicesTopicsApi api=new GetDevicesTopicsApi(devId,key); BasicResponse<List<String>> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testGetUserTopicsApi(){ String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; /** * Topic * @param keymasterkey */ GetUserTopics api=new GetUserTopics(key); BasicResponse<List<String>> response = api.executeApi(); System.out.println(response.getJson()); } @Test public void testRemoveUserTopic(){ String key="JKRfIzneAwXLdI6V0Yy83XOavb8="; String name="testtopic"; /** * Topic * @param nametopic * @param keymasterkey */ DeleteUserTopic api=new DeleteUserTopic(name,key); BasicResponse<Void> response = api.executeApi(); System.out.println(response.getJson()); } }
package com.googlecode.jmxtrans.model.output; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Result; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.model.ValidationException; import com.googlecode.jmxtrans.model.naming.KeyUtils; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.NotThreadSafe; import javax.inject.Inject; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static com.google.common.base.Charsets.UTF_8; import static com.googlecode.jmxtrans.model.PropertyResolver.resolveProps; @NotThreadSafe public class GraphiteWriter extends BaseOutputWriter { private static final Logger log = LoggerFactory.getLogger(GraphiteWriter.class); private static final String DEFAULT_ROOT_PREFIX = "servers"; private GenericKeyedObjectPool<InetSocketAddress, Socket> pool; private final String rootPrefix; private final InetSocketAddress address; @JsonCreator public GraphiteWriter( @JsonProperty("typeNames") ImmutableList<String> typeNames, @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("rootPrefix") String rootPrefix, @JsonProperty("host") String host, @JsonProperty("port") Integer port, @JsonProperty("settings") Map<String, Object> settings) { super(typeNames, booleanAsNumber, debugEnabled, settings); this.rootPrefix = resolveProps( firstNonNull( rootPrefix, (String) getSettings().get("rootPrefix"), DEFAULT_ROOT_PREFIX)); host = resolveProps(host); if (host == null) { host = (String) getSettings().get(HOST); } if (host == null) { throw new NullPointerException("Host cannot be null."); } if (port == null) { port = Settings.getIntegerSetting(getSettings(), PORT, null); } if (port == null) { throw new NullPointerException("Port cannot be null."); } this.address = new InetSocketAddress(host, port); } public void validateSetup(Server server, Query query) throws ValidationException { } public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null; try { socket = pool.borrowObject(address); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (NumberUtils.isNumeric(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); writer.flush(); if (writer.checkError()) { log.error("Error writing to Graphite, clearing Graphite socket pool"); pool.returnObject(address, socket); pool.clear(); } } else { log.warn("Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value, result); } } } } } finally { pool.returnObject(address, socket); } } public String getHost() { return address.getHostName(); } public int getPort() { return address.getPort(); } @Inject public void setPool(GenericKeyedObjectPool<InetSocketAddress, Socket> pool) { this.pool = pool; } public static Builder builder() { return new Builder(); } public static final class Builder { private final ImmutableList.Builder<String> typeNames = ImmutableList.builder(); private boolean booleanAsNumber; private Boolean debugEnabled; private String rootPrefix; private String host; private Integer port; private Builder() {} public Builder addTypeNames(List<String> typeNames) { this.typeNames.addAll(typeNames); return this; } public Builder addTypeName(String typeName) { typeNames.add(typeName); return this; } public Builder setBooleanAsNumber(boolean booleanAsNumber) { this.booleanAsNumber = booleanAsNumber; return this; } public Builder setDebugEnabled(boolean debugEnabled) { this.debugEnabled = debugEnabled; return this; } public Builder setRootPrefix(String rootPrefix) { this.rootPrefix = rootPrefix; return this; } public Builder setHost(String host) { this.host = host; return this; } public Builder setPort(int port) { this.port = port; return this; } public GraphiteWriter build() { return new GraphiteWriter( typeNames.build(), booleanAsNumber, debugEnabled, rootPrefix, host, port, null ); } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-09-03"); this.setApiVersion("18.13.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-12-04"); this.setApiVersion("17.14.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.j256.ormlite.android; import java.io.Serializable; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import android.test.AndroidTestCase; import com.j256.ormlite.dao.BaseDaoImpl; import com.j256.ormlite.dao.CloseableIterator; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.dao.RawRowMapper; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.db.SqliteAndroidDatabaseType; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseFieldConfig; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.misc.BaseDaoEnabled; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.j256.ormlite.stmt.UpdateBuilder; import com.j256.ormlite.stmt.Where; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTableConfig; import com.j256.ormlite.table.TableUtils; public class AndroidJdbcBaseDaoImplTest extends AndroidTestCase { private final static boolean CLOSE_IS_NOOP = true; private final static boolean UPDATE_ROWS_RETURNS_ONE = true; private static final String DATASOURCE_ERROR = "Property 'dataSource' is required"; private DatabaseType databaseType = new SqliteAndroidDatabaseType(); private ConnectionSource connectionSource; private DatabaseHelper helper; private Set<Class<?>> dropClassSet = new HashSet<Class<?>>(); private Set<DatabaseTableConfig<?>> dropTableConfigSet = new HashSet<DatabaseTableConfig<?>>(); protected boolean isTableExistsWorks() { return false; } @Override protected void setUp() throws Exception { super.setUp(); helper = new DatabaseHelper(getContext()); connectionSource = helper.getConnectionSource(); } @Override protected void tearDown() throws Exception { super.tearDown(); closeConnectionSource(); if (helper != null) { helper.close(); } } private void closeConnectionSource() throws Exception { if (connectionSource != null) { for (Class<?> clazz : dropClassSet) { dropTable(clazz, true); } for (DatabaseTableConfig<?> tableConfig : dropTableConfigSet) { dropTable(tableConfig, true); } connectionSource.close(); connectionSource = null; } databaseType = null; } protected <T, ID> Dao<T, ID> createDao(Class<T> clazz, boolean createTable) throws Exception { if (connectionSource == null) { throw new SQLException(DATASOURCE_ERROR); } @SuppressWarnings("unchecked") BaseDaoImpl<T, ID> dao = (BaseDaoImpl<T, ID>) DaoManager.createDao(connectionSource, clazz); return configDao(dao, createTable); } protected <T, ID> Dao<T, ID> createDao(DatabaseTableConfig<T> tableConfig, boolean createTable) throws Exception { if (connectionSource == null) { throw new SQLException(DATASOURCE_ERROR); } @SuppressWarnings("unchecked") BaseDaoImpl<T, ID> dao = (BaseDaoImpl<T, ID>) DaoManager.createDao(connectionSource, tableConfig); return configDao(dao, createTable); } protected <T> void createTable(Class<T> clazz, boolean dropAtEnd) throws Exception { try { // first we drop it in case it existed before dropTable(clazz, true); } catch (SQLException ignored) { // ignore any errors about missing tables } TableUtils.createTable(connectionSource, clazz); if (dropAtEnd) { dropClassSet.add(clazz); } } protected <T> void createTable(DatabaseTableConfig<T> tableConfig, boolean dropAtEnd) throws Exception { try { // first we drop it in case it existed before dropTable(tableConfig, true); } catch (SQLException ignored) { // ignore any errors about missing tables } TableUtils.createTable(connectionSource, tableConfig); if (dropAtEnd) { dropTableConfigSet.add(tableConfig); } } protected <T> void dropTable(Class<T> clazz, boolean ignoreErrors) throws Exception { // drop the table and ignore any errors along the way TableUtils.dropTable(connectionSource, clazz, ignoreErrors); } protected <T> void dropTable(DatabaseTableConfig<T> tableConfig, boolean ignoreErrors) throws Exception { // drop the table and ignore any errors along the way TableUtils.dropTable(connectionSource, tableConfig, ignoreErrors); } private <T, ID> Dao<T, ID> configDao(BaseDaoImpl<T, ID> dao, boolean createTable) throws Exception { if (connectionSource == null) { throw new SQLException(DATASOURCE_ERROR); } dao.setConnectionSource(connectionSource); if (createTable) { DatabaseTableConfig<T> tableConfig = dao.getTableConfig(); if (tableConfig == null) { tableConfig = DatabaseTableConfig.fromClass(connectionSource, dao.getDataClass()); } createTable(tableConfig, true); } dao.initialize(); return dao; } private final static String DEFAULT_VALUE_STRING = "1314199"; private final static int DEFAULT_VALUE = Integer.parseInt(DEFAULT_VALUE_STRING); private final static int ALL_TYPES_STRING_WIDTH = 4; private final static String FOO_TABLE_NAME = "footable"; private final static String ENUM_TABLE_NAME = "enumtable"; private final static String NULL_BOOLEAN_TABLE_NAME = "nullbooltable"; private final static String NULL_INT_TABLE_NAME = "nullinttable"; private final static String DEFAULT_BOOLEAN_VALUE = "true"; private final static String DEFAULT_STRING_VALUE = "foo"; // this can't have non-zero milliseconds private static DateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); private final static String DEFAULT_DATE_VALUE = "2010-07-16 01:31:17.000000"; private final static String DEFAULT_DATE_LONG_VALUE = "1282768620000"; private final static String DEFAULT_DATE_STRING_FORMAT = "MM/dd/yyyy HH-mm-ss-SSSSSS"; private static DateFormat defaultDateStringFormat = new SimpleDateFormat(DEFAULT_DATE_STRING_FORMAT); private final static String DEFAULT_DATE_STRING_VALUE = "07/16/2010 01-31-17-000000"; private final static String DEFAULT_BYTE_VALUE = "1"; private final static String DEFAULT_SHORT_VALUE = "2"; private final static String DEFAULT_INT_VALUE = "3"; private final static String DEFAULT_LONG_VALUE = "4"; private final static String DEFAULT_FLOAT_VALUE = "5"; private final static String DEFAULT_DOUBLE_VALUE = "6"; private final static String DEFAULT_ENUM_VALUE = "FIRST"; private final static String DEFAULT_ENUM_NUMBER_VALUE = "1"; public void testCreateDaoStatic() throws Exception { if (connectionSource == null) { return; } createTable(Foo.class, true); Dao<Foo, Integer> fooDao = DaoManager.createDao(connectionSource, Foo.class); String stuff = "stuff"; Foo foo = new Foo(); foo.stuff = stuff; assertEquals(1, fooDao.create(foo)); // now we query for foo from the database to make sure it was persisted right Foo foo2 = fooDao.queryForId(foo.id); assertNotNull(foo2); assertEquals(foo.id, foo2.id); assertEquals(stuff, foo2.stuff); } public void testCreateUpdateDelete() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String s1 = "stuff"; Foo foo1 = new Foo(); foo1.stuff = s1; assertEquals(0, foo1.id); // persist foo to db through the dao and sends the id on foo because it was auto-generated by the db assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); assertEquals(s1, foo1.stuff); // now we query for foo from the database to make sure it was persisted right Foo foo2 = fooDao.queryForId(foo1.id); assertNotNull(foo2); assertEquals(foo1.id, foo2.id); assertEquals(s1, foo2.stuff); String s2 = "stuff2"; foo2.stuff = s2; // now we update 1 row in a the database after changing foo assertEquals(1, fooDao.update(foo2)); // now we get it from the db again to make sure it was updated correctly Foo foo3 = fooDao.queryForId(foo1.id); assertEquals(s2, foo3.stuff); assertEquals(1, fooDao.delete(foo2)); assertNull(fooDao.queryForId(foo1.id)); } public void testDoubleCreate() throws Exception { Dao<DoubleCreate, Object> doubleDao = createDao(DoubleCreate.class, true); int id = 313413123; DoubleCreate foo = new DoubleCreate(); foo.id = id; assertEquals(1, doubleDao.create(foo)); try { doubleDao.create(foo); fail("expected exception"); } catch (SQLException e) { // expected } } public void testIterateRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> acctList = fooDao.queryForAll(); int initialSize = acctList.size(); Foo foo1 = new Foo(); foo1.stuff = "s1"; Foo foo2 = new Foo(); foo2.stuff = "s2"; Foo foo3 = new Foo(); foo3.stuff = "s3"; fooDao.create(foo1); fooDao.create(foo2); fooDao.create(foo3); assertTrue(foo1.id != foo2.id); assertTrue(foo1.id != foo3.id); assertTrue(foo2.id != foo3.id); assertEquals(foo1, fooDao.queryForId(foo1.id)); assertEquals(foo2, fooDao.queryForId(foo2.id)); assertEquals(foo3, fooDao.queryForId(foo3.id)); acctList = fooDao.queryForAll(); assertEquals(initialSize + 3, acctList.size()); assertEquals(foo1, acctList.get(acctList.size() - 3)); assertEquals(foo2, acctList.get(acctList.size() - 2)); assertEquals(foo3, acctList.get(acctList.size() - 1)); int acctC = 0; Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { Foo foo = iterator.next(); if (acctC == acctList.size() - 3) { assertEquals(foo1, foo); } else if (acctC == acctList.size() - 2) { iterator.remove(); assertEquals(foo2, foo); } else if (acctC == acctList.size() - 1) { assertEquals(foo3, foo); } acctC++; } assertEquals(initialSize + 3, acctC); } public void testGeneratedField() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; assertEquals(0, foo1.id); assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); } public void testGeneratedIdNotNullField() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; assertEquals(0, foo1.id); assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); } public void testObjectToString() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff = "foo123231"; Foo foo1 = new Foo(); foo1.stuff = stuff; String objStr = fooDao.objectToString(foo1); assertTrue(objStr.contains(Integer.toString(foo1.id))); assertTrue(objStr.contains(stuff)); } public void testCreateNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.create((Foo) null)); } public void testUpdateNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.update((Foo) null)); } public void testUpdateIdNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.updateId(null, null)); } public void testDeleteNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.delete((Foo) null)); } public void testCloseInIterator() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); Iterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { iterator.next(); closeConnectionSource(); } if (!CLOSE_IS_NOOP) { fail("expected exception"); } } catch (IllegalStateException e) { // expected } } public void testCloseIteratorFirst() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); closeConnectionSource(); try { fooDao.iterator(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } public void testCloseIteratorBeforeNext() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { closeConnectionSource(); iterator.next(); } if (!CLOSE_IS_NOOP) { fail("expected exception"); } } catch (IllegalStateException e) { // expected } finally { iterator.close(); } } public void testCloseIteratorBeforeRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { iterator.next(); closeConnectionSource(); iterator.remove(); } fail("expected exception"); } catch (Exception e) { // expected } } public void testNoNextBeforeRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { iterator.remove(); fail("expected exception"); } catch (IllegalStateException e) { // expected } finally { iterator.close(); } } public void testIteratePageSize() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); int numItems = 1000; fooDao.callBatchTasks(new InsertCallable(numItems, fooDao)); // now delete them with the iterator to test page-size Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } public void testIteratorPreparedQuery() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); // do an insert of bunch of items final int numItems = 100; fooDao.callBatchTasks(new InsertCallable(numItems, fooDao)); int lastX = 10; PreparedQuery<Foo> preparedQuery = fooDao.queryBuilder().where().ge(Foo.VAL_FIELD_NAME, numItems - lastX).prepare(); // now delete them with the iterator to test page-size Iterator<Foo> iterator = fooDao.iterator(preparedQuery); int itemC = 0; while (iterator.hasNext()) { Foo foo = iterator.next(); System.out.println("Foo = " + foo.val); itemC++; } assertEquals(lastX, itemC); } private static class InsertCallable implements Callable<Void> { private int numItems; private Dao<Foo, Integer> fooDao; public InsertCallable(int numItems, Dao<Foo, Integer> fooDao) { this.numItems = numItems; this.fooDao = fooDao; } public Void call() throws Exception { for (int i = 0; i < numItems; i++) { Foo foo = new Foo(); foo.val = i; assertEquals(1, fooDao.create(foo)); } return null; } } public void testDeleteObjects() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> fooList = new ArrayList<Foo>(); for (int i = 0; i < 100; i++) { Foo foo = new Foo(); foo.stuff = Integer.toString(i); assertEquals(1, fooDao.create(foo)); fooList.add(foo); } int deleted = fooDao.delete(fooList); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } public void testDeleteObjectsNone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> fooList = new ArrayList<Foo>(); assertEquals(fooList.size(), fooDao.delete(fooList)); assertEquals(0, fooDao.queryForAll().size()); } public void testDeleteIds() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); final List<Integer> fooIdList = new ArrayList<Integer>(); fooDao.callBatchTasks(new Callable<Void>() { public Void call() throws Exception { for (int i = 0; i < 100; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); fooIdList.add(foo.id); } return null; } }); int deleted = fooDao.deleteIds(fooIdList); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooIdList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } public void testDeleteIdsNone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Integer> fooIdList = new ArrayList<Integer>(); assertEquals(fooIdList.size(), fooDao.deleteIds(fooIdList)); assertEquals(0, fooDao.queryForAll().size()); } public void testDeletePreparedStmtIn() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Integer> fooIdList = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); fooIdList.add(foo.id); } DeleteBuilder<Foo, Integer> stmtBuilder = fooDao.deleteBuilder(); stmtBuilder.where().in(Foo.ID_FIELD_NAME, fooIdList); int deleted = fooDao.delete(stmtBuilder.prepare()); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooIdList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } public void testDeleteAllPreparedStmt() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); int fooN = 100; for (int i = 0; i < fooN; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); } DeleteBuilder<Foo, Integer> stmtBuilder = fooDao.deleteBuilder(); int deleted = fooDao.delete(stmtBuilder.prepare()); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooN, deleted); } assertEquals(0, fooDao.queryForAll().size()); } public void testHasNextAfterDone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { } assertFalse(iterator.hasNext()); } public void testNextWithoutHasNext() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); try { iterator.next(); fail("expected exception"); } catch (Exception e) { // expected } } public void testRemoveAfterDone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); assertFalse(iterator.hasNext()); try { iterator.remove(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } public void testIteratorNoResults() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); assertFalse(iterator.hasNext()); assertNull(iterator.next()); } public void testCreateNoId() throws Exception { Dao<NoId, Object> whereDao = createDao(NoId.class, true); NoId noId = new NoId(); assertEquals(0, whereDao.queryForAll().size()); // this should work even though there is no id whereDao.create(noId); assertEquals(1, whereDao.queryForAll().size()); } public void testJustIdCreateQueryDelete() throws Exception { Dao<JustId, Object> justIdDao = createDao(JustId.class, true); String id = "just-id"; JustId justId = new JustId(); justId.id = id; assertEquals(1, justIdDao.create(justId)); JustId justId2 = justIdDao.queryForId(id); assertNotNull(justId2); assertEquals(id, justId2.id); assertEquals(1, justIdDao.delete(justId)); assertNull(justIdDao.queryForId(id)); // update should fail during construction } public void testJustIdUpdateId() throws Exception { Dao<JustId, Object> justIdDao = createDao(JustId.class, true); String id = "just-id-update-1"; JustId justId = new JustId(); justId.id = id; assertEquals(1, justIdDao.create(justId)); JustId justId2 = justIdDao.queryForId(id); assertNotNull(justId2); assertEquals(id, justId2.id); String id2 = "just-id-update-2"; // change the id assertEquals(1, justIdDao.updateId(justId2, id2)); assertNull(justIdDao.queryForId(id)); JustId justId3 = justIdDao.queryForId(id2); assertNotNull(justId3); assertEquals(id2, justId3.id); assertEquals(1, justIdDao.delete(justId3)); assertNull(justIdDao.queryForId(id)); assertNull(justIdDao.queryForId(id2)); } public void testJustIdRefresh() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff1 = "just-id-refresh-1"; Foo foo1 = new Foo(); foo1.stuff = stuff1; assertEquals(1, fooDao.create(foo1)); int id = foo1.id; Foo foo2 = fooDao.queryForId(id); assertNotNull(foo2); assertEquals(id, foo2.id); assertEquals(stuff1, foo2.stuff); String stuff2 = "just-id-refresh-2"; foo2.stuff = stuff2; // change the id in the db assertEquals(1, fooDao.update(foo2)); Foo foo3 = fooDao.queryForId(id); assertNotNull(foo3); assertEquals(id, foo3.id); assertEquals(stuff2, foo3.stuff); assertEquals(stuff1, foo1.stuff); assertEquals(1, fooDao.refresh(foo1)); assertEquals(stuff2, foo1.stuff); } public void testSpringConstruction() throws Exception { if (connectionSource == null) { return; } createTable(Foo.class, true); BaseDaoImpl<Foo, Integer> fooDao = new BaseDaoImpl<Foo, Integer>(Foo.class) { }; try { fooDao.create(new Foo()); fail("expected exception"); } catch (IllegalStateException e) { // expected } fooDao.setConnectionSource(connectionSource); fooDao.initialize(); Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); assertEquals(1, fooDao.delete(foo)); } public void testForeignCreation() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); ForeignWrapper wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(wrapper.id, wrapper2.id); assertEquals(wrapper.foreign.id, wrapper2.foreign.id); assertTrue(wrapperDao.objectsEqual(wrapper, wrapper2)); // this won't be true because wrapper2.foreign is a shell assertFalse(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertNull(wrapper2.foreign.stringField); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); // now it should be true assertTrue(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertEquals(stuff1, wrapper2.foreign.stringField); // create a new foreign foreign = new AllTypes(); String stuff2 = "stuff2"; foreign.stringField = stuff2; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); // change the foreign object wrapper.foreign = foreign; // update it assertEquals(1, wrapperDao.update(wrapper)); wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(wrapper.id, wrapper2.id); assertEquals(wrapper.foreign.id, wrapper2.foreign.id); assertTrue(wrapperDao.objectsEqual(wrapper, wrapper2)); // this won't be true because wrapper2.foreign is a shell assertFalse(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertNull(wrapper2.foreign.stringField); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); // now it should be true assertTrue(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertEquals(stuff2, wrapper2.foreign.stringField); } public void testForeignRefreshNoChange() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); ForeignWrapper wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); AllTypes foreign2 = wrapper2.foreign; assertEquals(stuff1, foreign2.stringField); assertEquals(1, wrapperDao.refresh(wrapper2)); assertSame(foreign2, wrapper2.foreign); assertEquals(stuff1, wrapper2.foreign.stringField); // now, in the background, we change the foreign ForeignWrapper wrapper3 = wrapperDao.queryForId(wrapper.id); AllTypes foreign3 = new AllTypes(); String stuff3 = "stuff3"; foreign3.stringField = stuff3; assertEquals(1, foreignDao.create(foreign3)); wrapper3.foreign = foreign3; assertEquals(1, wrapperDao.update(wrapper3)); assertEquals(1, wrapperDao.refresh(wrapper2)); // now all of a sudden wrapper2 should not have the same foreign field assertNotSame(foreign2, wrapper2.foreign); assertNull(wrapper2.foreign.stringField); } public void testMultipleForeignWrapper() throws Exception { Dao<MultipleForeignWrapper, Integer> multipleWrapperDao = createDao(MultipleForeignWrapper.class, true); Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); MultipleForeignWrapper multiWrapper = new MultipleForeignWrapper(); multiWrapper.foreign = foreign; multiWrapper.foreignWrapper = wrapper; // this sets the wrapper id assertEquals(1, multipleWrapperDao.create(multiWrapper)); MultipleForeignWrapper multiWrapper2 = multipleWrapperDao.queryForId(multiWrapper.id); assertEquals(foreign.id, multiWrapper2.foreign.id); assertNull(multiWrapper2.foreign.stringField); assertEquals(wrapper.id, multiWrapper2.foreignWrapper.id); assertNull(multiWrapper2.foreignWrapper.foreign); assertEquals(1, foreignDao.refresh(multiWrapper2.foreign)); assertEquals(stuff1, multiWrapper2.foreign.stringField); assertNull(multiWrapper2.foreignWrapper.foreign); assertEquals(1, wrapperDao.refresh(multiWrapper2.foreignWrapper)); assertEquals(foreign.id, multiWrapper2.foreignWrapper.foreign.id); assertNull(multiWrapper2.foreignWrapper.foreign.stringField); assertEquals(1, foreignDao.refresh(multiWrapper2.foreignWrapper.foreign)); assertEquals(stuff1, multiWrapper2.foreignWrapper.foreign.stringField); } public void testRefreshNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); // this should be a noop assertEquals(0, fooDao.refresh(null)); } public void testGetSet() throws Exception { Dao<GetSet, Integer> getSetDao = createDao(GetSet.class, true); GetSet getSet = new GetSet(); String stuff = "ewfewfewfew343u42f"; getSet.setStuff(stuff); assertEquals(1, getSetDao.create(getSet)); GetSet getSet2 = getSetDao.queryForId(getSet.id); assertEquals(stuff, getSet2.stuff); } public void testQueryForFirst() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff = "ewf4334234u42f"; QueryBuilder<Foo, Integer> qb = fooDao.queryBuilder(); qb.where().eq(Foo.STUFF_FIELD_NAME, stuff); assertNull(fooDao.queryForFirst(qb.prepare())); Foo foo1 = new Foo(); foo1.stuff = stuff; assertEquals(1, fooDao.create(foo1)); // should still get foo1 Foo foo2 = fooDao.queryForFirst(qb.prepare()); assertEquals(foo1.id, foo2.id); assertEquals(stuff, foo2.stuff); // create another with same stuff Foo foo3 = new Foo(); String stuff2 = "ewf43342wefwffwefwe34u42f"; foo3.stuff = stuff2; assertEquals(1, fooDao.create(foo3)); foo2 = fooDao.queryForFirst(qb.prepare()); assertEquals(foo1.id, foo2.id); assertEquals(stuff, foo2.stuff); } public void testFieldConfig() throws Exception { List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>(); fieldConfigs.add(new DatabaseFieldConfig("id", "id2", DataType.UNKNOWN, null, 0, false, false, true, null, false, null, false, null, false, null, false, null, null, false, 0, 0)); fieldConfigs.add(new DatabaseFieldConfig("stuff", "stuffy", DataType.UNKNOWN, null, 0, false, false, false, null, false, null, false, null, false, null, false, null, null, false, 0, 0)); DatabaseTableConfig<NoAnno> tableConfig = new DatabaseTableConfig<NoAnno>(NoAnno.class, "noanno", fieldConfigs); Dao<NoAnno, Integer> noAnnotaionDao = createDao(tableConfig, true); NoAnno noa = new NoAnno(); String stuff = "qpoqwpjoqwp12"; noa.stuff = stuff; assertEquals(1, noAnnotaionDao.create(noa)); NoAnno noa2 = noAnnotaionDao.queryForId(noa.id); assertEquals(noa.id, noa2.id); assertEquals(stuff, noa2.stuff); } public void testFieldConfigForeign() throws Exception { List<DatabaseFieldConfig> noAnnotationsFieldConfigs = new ArrayList<DatabaseFieldConfig>(); DatabaseFieldConfig field1 = new DatabaseFieldConfig("id"); field1.setColumnName("idthingie"); field1.setGeneratedId(true); noAnnotationsFieldConfigs.add(field1); DatabaseFieldConfig field2 = new DatabaseFieldConfig("stuff"); field2.setColumnName("stuffy"); noAnnotationsFieldConfigs.add(field2); DatabaseTableConfig<NoAnno> noAnnotationsTableConfig = new DatabaseTableConfig<NoAnno>(NoAnno.class, noAnnotationsFieldConfigs); Dao<NoAnno, Integer> noAnnotationDao = createDao(noAnnotationsTableConfig, true); NoAnno noa = new NoAnno(); String stuff = "qpoqwpjoqwp12"; noa.stuff = stuff; assertEquals(1, noAnnotationDao.create(noa)); assertNotNull(noAnnotationDao.queryForId(noa.id)); List<DatabaseFieldConfig> noAnnotationsForiegnFieldConfigs = new ArrayList<DatabaseFieldConfig>(); DatabaseFieldConfig field3 = new DatabaseFieldConfig("id"); field3.setColumnName("anotherid"); field3.setGeneratedId(true); noAnnotationsForiegnFieldConfigs.add(field3); DatabaseFieldConfig field4 = new DatabaseFieldConfig("foreign"); field4.setColumnName("foreignThingie"); field4.setForeign(true); field4.setForeignTableConfig(noAnnotationsTableConfig); noAnnotationsForiegnFieldConfigs.add(field4); DatabaseTableConfig<NoAnnoFor> noAnnotationsForiegnTableConfig = new DatabaseTableConfig<NoAnnoFor>(NoAnnoFor.class, noAnnotationsForiegnFieldConfigs); Dao<NoAnnoFor, Integer> noAnnotaionForeignDao = createDao(noAnnotationsForiegnTableConfig, true); NoAnnoFor noaf = new NoAnnoFor(); noaf.foreign = noa; assertEquals(1, noAnnotaionForeignDao.create(noaf)); NoAnnoFor noaf2 = noAnnotaionForeignDao.queryForId(noaf.id); assertNotNull(noaf2); assertEquals(noaf.id, noaf2.id); assertEquals(noa.id, noaf2.foreign.id); assertNull(noaf2.foreign.stuff); assertEquals(1, noAnnotationDao.refresh(noaf2.foreign)); assertEquals(stuff, noaf2.foreign.stuff); } public void testGeneratedIdNotNull() throws Exception { // we saw an error with the not null before the generated id stuff under hsqldb Dao<GeneratedIdNotNull, Integer> dao = createDao(GeneratedIdNotNull.class, true); assertEquals(1, dao.create(new GeneratedIdNotNull())); } public void testBasicStuff() throws Exception { Dao<Basic, String> fooDao = createDao(Basic.class, true); String string = "s1"; Basic foo1 = new Basic(); foo1.id = string; assertEquals(1, fooDao.create(foo1)); Basic foo2 = fooDao.queryForId(string); assertTrue(fooDao.objectsEqual(foo1, foo2)); List<Basic> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertTrue(fooDao.objectsEqual(foo1, fooList.get(0))); int i = 0; for (Basic foo3 : fooDao) { assertTrue(fooDao.objectsEqual(foo1, foo3)); i++; } assertEquals(1, i); assertEquals(1, fooDao.delete(foo2)); assertNull(fooDao.queryForId(string)); fooList = fooDao.queryForAll(); assertEquals(0, fooList.size()); i = 0; for (Basic foo3 : fooDao) { assertTrue(fooDao.objectsEqual(foo1, foo3)); i++; } assertEquals(0, i); } public void testMultiplePrimaryKey() throws Exception { Dao<Basic, String> fooDao = createDao(Basic.class, true); Basic foo1 = new Basic(); foo1.id = "dup"; assertEquals(1, fooDao.create(foo1)); try { fooDao.create(foo1); fail("expected exception"); } catch (SQLException e) { // expected } } public void testDefaultValue() throws Exception { Dao<DefaultValue, Object> defValDao = createDao(DefaultValue.class, true); DefaultValue defVal1 = new DefaultValue(); assertEquals(1, defValDao.create(defVal1)); List<DefaultValue> defValList = defValDao.queryForAll(); assertEquals(1, defValList.size()); DefaultValue defVal2 = defValList.get(0); assertEquals(DEFAULT_VALUE, (int) defVal2.intField); } public void testNotNull() throws Exception { Dao<NotNull, Object> defValDao = createDao(NotNull.class, true); NotNull notNull = new NotNull(); try { defValDao.create(notNull); fail("expected exception"); } catch (SQLException e) { // expected } } public void testNotNullOkay() throws Exception { Dao<NotNull, Object> defValDao = createDao(NotNull.class, true); NotNull notNull = new NotNull(); notNull.notNull = "not null"; assertEquals(1, defValDao.create(notNull)); } public void testGeneratedId() throws Exception { Dao<GeneratedId, Object> genIdDao = createDao(GeneratedId.class, true); GeneratedId genId = new GeneratedId(); assertEquals(0, genId.id); assertEquals(1, genIdDao.create(genId)); long id = genId.id; assertEquals(1, id); GeneratedId genId2 = genIdDao.queryForId(id); assertNotNull(genId2); assertEquals(id, genId2.id); genId = new GeneratedId(); assertEquals(0, genId.id); assertEquals(1, genIdDao.create(genId)); id = genId.id; assertEquals(2, id); genId2 = genIdDao.queryForId(id); assertNotNull(genId2); assertEquals(id, genId2.id); } public void testAllTypes() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); String stringVal = "some string"; boolean boolVal = true; // we have to round this because the db may not be storing millis long millis = (System.currentTimeMillis() / 1000) * 1000; Date dateVal = new Date(millis); Date dateLongVal = new Date(millis); Date dateStringVal = new Date(millis); char charVal = 'w'; byte byteVal = 117; short shortVal = 15217; int intVal = 1023213; long longVal = 1231231231231L; float floatVal = 123.13F; double doubleVal = 1413312.1231233; OurEnum enumVal = OurEnum.FIRST; allTypes.stringField = stringVal; allTypes.booleanField = boolVal; allTypes.dateField = dateVal; allTypes.dateLongField = dateLongVal; allTypes.dateStringField = dateStringVal; allTypes.charField = charVal; allTypes.byteField = byteVal; allTypes.shortField = shortVal; allTypes.intField = intVal; allTypes.longField = longVal; allTypes.floatField = floatVal; allTypes.doubleField = doubleVal; allTypes.enumField = enumVal; allTypes.enumStringField = enumVal; allTypes.enumIntegerField = enumVal; SerialData obj = new SerialData(); String key = "key"; String value = "value"; obj.addEntry(key, value); allTypes.serialField = obj; assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); assertEquals(value, allTypesList.get(0).serialField.map.get(key)); assertEquals(1, allDao.refresh(allTypes)); // queries on all fields QueryBuilder<AllTypes, Integer> qb = allDao.queryBuilder(); checkQueryResult(allDao, qb, allTypes, AllTypes.STRING_FIELD_NAME, stringVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.BOOLEAN_FIELD_NAME, boolVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_FIELD_NAME, dateVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_LONG_FIELD_NAME, dateLongVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_STRING_FIELD_NAME, dateStringVal, true); if (!databaseType.getDatabaseName().equals("Derby")) { checkQueryResult(allDao, qb, allTypes, AllTypes.CHAR_FIELD_NAME, charVal, true); } checkQueryResult(allDao, qb, allTypes, AllTypes.BYTE_FIELD_NAME, byteVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.SHORT_FIELD_NAME, shortVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.INT_FIELD_NAME, intVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.LONG_FIELD_NAME, longVal, true); // float tested below checkQueryResult(allDao, qb, allTypes, AllTypes.DOUBLE_FIELD_NAME, doubleVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_FIELD_NAME, enumVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_STRING_FIELD_NAME, enumVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_INTEGER_FIELD_NAME, enumVal, true); } /** * This is special because comparing floats may not work as expected. */ public void testAllTypesFloat() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); float floatVal = 123.13F; float floatLowVal = floatVal * 0.9F; float floatHighVal = floatVal * 1.1F; allTypes.floatField = floatVal; assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); assertEquals(1, allDao.refresh(allTypes)); // queries on all fields QueryBuilder<AllTypes, Integer> qb = allDao.queryBuilder(); // float comparisons are not exactly right so we switch to a low -> high query instead if (!checkQueryResult(allDao, qb, allTypes, AllTypes.FLOAT_FIELD_NAME, floatVal, false)) { qb.where().gt(AllTypes.FLOAT_FIELD_NAME, floatLowVal).and().lt(AllTypes.FLOAT_FIELD_NAME, floatHighVal); List<AllTypes> results = allDao.query(qb.prepare()); assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } } public void testAllTypesDefault() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); } public void testNumberTypes() throws Exception { Dao<NumberTypes, Integer> numberDao = createDao(NumberTypes.class, true); NumberTypes numberMins = new NumberTypes(); numberMins.byteField = Byte.MIN_VALUE; numberMins.shortField = Short.MIN_VALUE; numberMins.intField = Integer.MIN_VALUE; numberMins.longField = Long.MIN_VALUE; numberMins.floatField = -1.0e+37F; numberMins.doubleField = -1.0e+307; assertEquals(1, numberDao.create(numberMins)); NumberTypes numberMins2 = new NumberTypes(); numberMins2.byteField = Byte.MIN_VALUE; numberMins2.shortField = Short.MIN_VALUE; numberMins2.intField = Integer.MIN_VALUE; numberMins2.longField = Long.MIN_VALUE; numberMins2.floatField = 1.0e-37F; // derby couldn't take 1.0e-307 for some reason numberMins2.doubleField = 1.0e-306; assertEquals(1, numberDao.create(numberMins2)); NumberTypes numberMaxs = new NumberTypes(); numberMaxs.byteField = Byte.MAX_VALUE; numberMaxs.shortField = Short.MAX_VALUE; numberMaxs.intField = Integer.MAX_VALUE; numberMaxs.longField = Long.MAX_VALUE; numberMaxs.floatField = 1.0e+37F; numberMaxs.doubleField = 1.0e+307; assertEquals(1, numberDao.create(numberMaxs)); assertEquals(1, numberDao.refresh(numberMaxs)); List<NumberTypes> allTypesList = numberDao.queryForAll(); assertEquals(3, allTypesList.size()); assertTrue(numberDao.objectsEqual(numberMins, allTypesList.get(0))); assertTrue(numberDao.objectsEqual(numberMins2, allTypesList.get(1))); assertTrue(numberDao.objectsEqual(numberMaxs, allTypesList.get(2))); } public void testStringWidthTooLong() throws Exception { if (connectionSource == null) { return; } if (!connectionSource.getDatabaseType().isVarcharFieldWidthSupported()) { return; } Dao<StringWidth, Object> stringWidthDao = createDao(StringWidth.class, true); StringWidth stringWidth = new StringWidth(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ALL_TYPES_STRING_WIDTH + 1; i++) { sb.append("c"); } String string = sb.toString(); assertTrue(string.length() > ALL_TYPES_STRING_WIDTH); stringWidth.stringField = string; try { stringWidthDao.create(stringWidth); fail("expected exception"); } catch (SQLException e) { // expected } } public void testStringWidthOkay() throws Exception { Dao<StringWidth, Object> stringWidthDao = createDao(StringWidth.class, true); StringWidth stringWidth = new StringWidth(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ALL_TYPES_STRING_WIDTH; i++) { sb.append("c"); } String string = sb.toString(); assertTrue(string.length() == ALL_TYPES_STRING_WIDTH); stringWidth.stringField = string; assertEquals(1, stringWidthDao.create(stringWidth)); List<StringWidth> stringWidthList = stringWidthDao.queryForAll(); assertEquals(1, stringWidthList.size()); assertTrue(stringWidthDao.objectsEqual(stringWidth, stringWidthList.get(0))); } public void testCreateReserverdTable() throws Exception { Dao<Create, String> whereDao = createDao(Create.class, true); String id = "from-string"; Create where = new Create(); where.id = id; assertEquals(1, whereDao.create(where)); Create where2 = whereDao.queryForId(id); assertEquals(id, where2.id); assertEquals(1, whereDao.delete(where2)); assertNull(whereDao.queryForId(id)); } public void testCreateReserverdFields() throws Exception { Dao<ReservedField, Object> reservedDao = createDao(ReservedField.class, true); String from = "from-string"; ReservedField res = new ReservedField(); res.from = from; assertEquals(1, reservedDao.create(res)); int id = res.select; ReservedField res2 = reservedDao.queryForId(id); assertNotNull(res2); assertEquals(id, res2.select); String group = "group-string"; for (ReservedField reserved : reservedDao) { assertEquals(from, reserved.from); reserved.group = group; reservedDao.update(reserved); } Iterator<ReservedField> reservedIterator = reservedDao.iterator(); while (reservedIterator.hasNext()) { ReservedField reserved = reservedIterator.next(); assertEquals(from, reserved.from); assertEquals(group, reserved.group); reservedIterator.remove(); } assertEquals(0, reservedDao.queryForAll().size()); } public void testEscapeCharInField() throws Exception { if (connectionSource == null) { return; } StringBuilder sb = new StringBuilder(); String word = "foo"; connectionSource.getDatabaseType().appendEscapedWord(sb, word); String escaped = sb.toString(); int index = escaped.indexOf(word); String escapeString = escaped.substring(0, index); Dao<Basic, String> fooDao = createDao(Basic.class, true); Basic foo1 = new Basic(); String id = word + escapeString + word; foo1.id = id; assertEquals(1, fooDao.create(foo1)); Basic foo2 = fooDao.queryForId(id); assertNotNull(foo2); assertEquals(id, foo2.id); } public void testGeneratedIdCapital() throws Exception { createDao(GeneratedColumnCapital.class, true); } public void testObject() throws Exception { Dao<ObjectHolder, Integer> objDao = createDao(ObjectHolder.class, true); ObjectHolder foo1 = new ObjectHolder(); foo1.obj = new SerialData(); String key = "key2"; String value = "val2"; foo1.obj.addEntry(key, value); String strObj = "fjpwefefwpjoefwjpojopfew"; foo1.strObj = strObj; assertEquals(1, objDao.create(foo1)); ObjectHolder foo2 = objDao.queryForId(foo1.id); assertTrue(objDao.objectsEqual(foo1, foo2)); } public void testNotSerializable() throws Exception { try { createDao(NotSerializable.class, true); fail("expected exception"); } catch (IllegalArgumentException e) { // expected } } public void testStringEnum() throws Exception { Dao<LocalEnumString, Object> fooDao = createDao(LocalEnumString.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumString foo = new LocalEnumString(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); List<LocalEnumString> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(ourEnum, fooList.get(0).ourEnum); } public void testUnknownStringEnum() throws Exception { Dao<LocalEnumString, Object> fooDao = createDao(LocalEnumString.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumString foo = new LocalEnumString(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumString2, Object> foo2Dao = createDao(LocalEnumString2.class, false); try { foo2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } public void testIntEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); List<LocalEnumInt> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(ourEnum, fooList.get(0).ourEnum); } public void testUnknownIntEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumInt2, Object> foo2Dao = createDao(LocalEnumInt2.class, false); try { foo2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } public void testUnknownIntUnknownValEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumInt3, Object> foo2Dao = createDao(LocalEnumInt3.class, false); List<LocalEnumInt3> fooList = foo2Dao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(OurEnum2.FIRST, fooList.get(0).ourEnum); } public void testNullHandling() throws Exception { Dao<AllObjectTypes, Object> allDao = createDao(AllObjectTypes.class, true); AllObjectTypes all = new AllObjectTypes(); assertEquals(1, allDao.create(all)); List<AllObjectTypes> allList = allDao.queryForAll(); assertEquals(1, allList.size()); assertTrue(allDao.objectsEqual(all, allList.get(0))); } public void testObjectNotNullHandling() throws Exception { Dao<AllObjectTypes, Object> allDao = createDao(AllObjectTypes.class, true); AllObjectTypes all = new AllObjectTypes(); all.stringField = "foo"; all.booleanField = false; Date dateValue = new Date(1279649192000L); all.dateField = dateValue; all.byteField = 0; all.shortField = 0; all.intField = 0; all.longField = 0L; all.floatField = 0F; all.doubleField = 0D; all.objectField = new SerialData(); all.ourEnum = OurEnum.FIRST; assertEquals(1, allDao.create(all)); assertEquals(1, allDao.refresh(all)); List<AllObjectTypes> allList = allDao.queryForAll(); assertEquals(1, allList.size()); assertTrue(allDao.objectsEqual(all, allList.get(0))); } public void testDefaultValueHandling() throws Exception { Dao<AllTypesDefault, Object> allDao = createDao(AllTypesDefault.class, true); AllTypesDefault all = new AllTypesDefault(); assertEquals(1, allDao.create(all)); assertEquals(1, allDao.refresh(all)); List<AllTypesDefault> allList = allDao.queryForAll(); assertEquals(1, allList.size()); all.stringField = DEFAULT_STRING_VALUE; all.dateField = defaultDateFormat.parse(DEFAULT_DATE_VALUE); all.dateLongField = new Date(Long.parseLong(DEFAULT_DATE_LONG_VALUE)); all.dateStringField = defaultDateStringFormat.parse(DEFAULT_DATE_STRING_VALUE); all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.byteField = Byte.parseByte(DEFAULT_BYTE_VALUE); all.byteObj = Byte.parseByte(DEFAULT_BYTE_VALUE); all.shortField = Short.parseShort(DEFAULT_SHORT_VALUE); all.shortObj = Short.parseShort(DEFAULT_SHORT_VALUE); all.intField = Integer.parseInt(DEFAULT_INT_VALUE); all.intObj = Integer.parseInt(DEFAULT_INT_VALUE); all.longField = Long.parseLong(DEFAULT_LONG_VALUE); all.longObj = Long.parseLong(DEFAULT_LONG_VALUE); all.floatField = Float.parseFloat(DEFAULT_FLOAT_VALUE); all.floatObj = Float.parseFloat(DEFAULT_FLOAT_VALUE); all.doubleField = Double.parseDouble(DEFAULT_DOUBLE_VALUE); all.doubleObj = Double.parseDouble(DEFAULT_DOUBLE_VALUE); all.ourEnum = OurEnum.valueOf(DEFAULT_ENUM_VALUE); assertFalse(allDao.objectsEqual(all, allList.get(0))); } public void testBooleanDefaultValueHandling() throws Exception { Dao<BooleanDefault, Object> allDao = createDao(BooleanDefault.class, true); BooleanDefault all = new BooleanDefault(); assertEquals(1, allDao.create(all)); List<BooleanDefault> allList = allDao.queryForAll(); assertEquals(1, allList.size()); all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); assertFalse(allDao.objectsEqual(all, allList.get(0))); } public void testNullUnPersistToBooleanPrimitive() throws Exception { Dao<NullBoolean1, Object> null1Dao = createDao(NullBoolean1.class, true); NullBoolean1 nullThing = new NullBoolean1(); assertEquals(1, null1Dao.create(nullThing)); Dao<NullBoolean2, Object> null2Dao = createDao(NullBoolean2.class, false); try { null2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } public void testNullUnPersistToIntPrimitive() throws Exception { Dao<NullInt1, Object> null1Dao = createDao(NullInt1.class, true); NullInt1 nullThing = new NullInt1(); assertEquals(1, null1Dao.create(nullThing)); Dao<NullInt2, Object> null2Dao = createDao(NullInt2.class, false); try { null2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } public void testQueryRawStrings() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; foo.stuff = stuff; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<String[]> results = fooDao.queryRaw(queryString); assertEquals(0, results.getResults().size()); assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); boolean gotId = false; boolean gotStuff = false; boolean gotVal = false; // all this crap is here because of android column order for (int colC = 0; colC < 3; colC++) { if (colNames[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { gotId = true; } else if (colNames[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { gotStuff = true; } else if (colNames[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { gotVal = true; } } assertTrue(gotId); assertTrue(gotStuff); assertTrue(gotVal); List<String[]> resultList = results.getResults(); assertEquals(1, resultList.size()); String[] result = resultList.get(0); assertEquals(colN, result.length); for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (results.getColumnNames()[colC] == "id") { assertEquals(Integer.toString(foo.id), result[colC]); } if (results.getColumnNames()[colC] == "stuff") { assertEquals(stuff, result[1]); } } } public void testQueryRawStringsIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; int val = 12321411; foo.stuff = stuff; foo.val = val; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<String[]> results = fooDao.queryRaw(queryString); CloseableIterator<String[]> iterator = results.closeableIterator(); try { assertFalse(iterator.hasNext()); } finally { iterator.close(); } assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); String[] result = iterator.next(); assertEquals(colN, result.length); boolean foundId = false; boolean foundStuff = false; boolean foundVal = false; for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { assertEquals(Integer.toString(foo.id), result[colC]); foundId = true; } if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { assertEquals(stuff, result[colC]); foundStuff = true; } if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { assertEquals(Integer.toString(val), result[colC]); foundVal = true; } } assertTrue(foundId); assertTrue(foundStuff); assertTrue(foundVal); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } public void testQueryRawMappedIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); final Foo foo = new Foo(); String stuff = "eprjpejrre"; foo.stuff = stuff; String queryString = buildFooQueryAllString(fooDao); Mapper mapper = new Mapper(); GenericRawResults<Foo> rawResults = fooDao.queryRaw(queryString, mapper); assertEquals(0, rawResults.getResults().size()); assertEquals(1, fooDao.create(foo)); rawResults = fooDao.queryRaw(queryString, mapper); Iterator<Foo> iterator = rawResults.iterator(); assertTrue(iterator.hasNext()); Foo foo2 = iterator.next(); assertEquals(foo.id, foo2.id); assertEquals(foo.stuff, foo2.stuff); assertEquals(foo.val, foo2.val); assertFalse(iterator.hasNext()); } public void testQueryRawObjectsIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; int val = 213123; foo.stuff = stuff; foo.val = val; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<Object[]> results = fooDao.queryRaw(queryString, new DataType[] { DataType.INTEGER, DataType.STRING, DataType.INTEGER }); CloseableIterator<Object[]> iterator = results.closeableIterator(); try { assertFalse(iterator.hasNext()); } finally { iterator.close(); } assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString, new DataType[] { DataType.INTEGER, DataType.STRING, DataType.INTEGER }); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); Object[] result = iterator.next(); assertEquals(colN, result.length); String[] columnNames = results.getColumnNames(); boolean foundId = false; boolean foundStuff = false; boolean foundVal = false; for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (columnNames[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { assertEquals(foo.id, result[colC]); foundId = true; } if (columnNames[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { assertEquals(stuff, result[colC]); foundStuff = true; } if (columnNames[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { assertEquals(val, result[colC]); foundVal = true; } } assertTrue(foundId); assertTrue(foundStuff); assertTrue(foundVal); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } public void testNotNullDefault() throws Exception { Dao<NotNullDefault, Object> dao = createDao(NotNullDefault.class, true); NotNullDefault notNullDefault = new NotNullDefault(); assertEquals(1, dao.create(notNullDefault)); } public void testStringDefault() throws Exception { Dao<StringDefalt, Object> dao = createDao(StringDefalt.class, true); StringDefalt foo = new StringDefalt(); assertEquals(1, dao.create(foo)); } public void testDateUpdate() throws Exception { Dao<LocalDate, Object> dao = createDao(LocalDate.class, true); LocalDate localDate = new LocalDate(); // note: this does not have milliseconds Date date = new Date(2131232000); localDate.date = date; assertEquals(1, dao.create(localDate)); List<LocalDate> allDates = dao.queryForAll(); assertEquals(1, allDates.size()); assertEquals(date, allDates.get(0).date); // now we update it assertEquals(1, dao.update(localDate)); allDates = dao.queryForAll(); assertEquals(1, allDates.size()); assertEquals(date, allDates.get(0).date); // now we set it to null localDate.date = null; // now we update it assertEquals(1, dao.update(localDate)); allDates = dao.queryForAll(); assertEquals(1, allDates.size()); // we should get null back and not some auto generated field assertNull(allDates.get(0).date); } public void testDateRefresh() throws Exception { Dao<LocalDate, Object> dao = createDao(LocalDate.class, true); LocalDate localDate = new LocalDate(); // note: this does not have milliseconds Date date = new Date(2131232000); localDate.date = date; assertEquals(1, dao.create(localDate)); assertEquals(1, dao.refresh(localDate)); } public void testSpringBadWiring() throws Exception { BaseDaoImpl<String, String> daoSupport = new BaseDaoImpl<String, String>(String.class) { }; try { daoSupport.initialize(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } public void testUnique() throws Exception { Dao<Unique, Long> dao = createDao(Unique.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; Unique unique = new Unique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new Unique(); unique.stuff = stuff; assertEquals(1, dao.create(unique)); unique = new Unique(); unique.uniqueStuff = uniqueStuff; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } public void testDoubleUnique() throws Exception { Dao<DoubleUnique, Long> dao = createDao(DoubleUnique.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; DoubleUnique unique = new DoubleUnique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new DoubleUnique(); unique.stuff = stuff; try { // either 1st field can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } unique = new DoubleUnique(); unique.uniqueStuff = uniqueStuff; try { // nor 2nd field can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } unique = new DoubleUnique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; try { // nor both fields can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } public void testDoubleUniqueCombo() throws Exception { Dao<DoubleUniqueCombo, Long> dao = createDao(DoubleUniqueCombo.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; DoubleUniqueCombo unique = new DoubleUniqueCombo(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new DoubleUniqueCombo(); unique.stuff = stuff; assertEquals(1, dao.create(unique)); unique = new DoubleUniqueCombo(); unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); unique = new DoubleUniqueCombo(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } public void testUniqueAndUniqueCombo() throws Exception { Dao<UniqueAndUniqueCombo, Long> dao = createDao(UniqueAndUniqueCombo.class, true); String unique1 = "unique but not combo"; String combo1 = "combo unique"; String combo2 = "another combo unique"; UniqueAndUniqueCombo unique = new UniqueAndUniqueCombo(); unique.unique1 = unique1; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new UniqueAndUniqueCombo(); unique.unique1 = unique1; try { dao.create(unique); fail("this should throw"); } catch (Exception e) { // expected } unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = combo2; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = unique1; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = unique1; unique.combo2 = combo2; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = combo2; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } public void testForeignQuery() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; Date date = new Date(); foreign.dateField = date; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); QueryBuilder<ForeignWrapper, Integer> qb = wrapperDao.queryBuilder(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, foreign.id); List<ForeignWrapper> results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * now look it up not by foreign.id but by foreign which should extract the id automagically */ qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, foreign); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * Now let's try the same thing but with a SelectArg */ SelectArg selectArg = new SelectArg(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, selectArg); selectArg.setValue(foreign.id); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * Now let's try the same thing but with a SelectArg with foreign value, not foreign.id */ selectArg = new SelectArg(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, selectArg); selectArg.setValue(foreign); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); } public void testPrepareStatementUpdateValueString() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "dqedqdq"; foo.stuff = stuff; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.STUFF_FIELD_NAME, stuff); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String newStuff = "fepojefpjo"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, newStuff); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.query(stmtb.prepare()); assertEquals(0, results.size()); } public void testInSubQuery() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Basic, String> basicDao = createDao(Basic.class, true); Basic basic1 = new Basic(); String string1 = "ewpofjewgprgrg"; basic1.id = string1; assertEquals(1, basicDao.create(basic1)); Basic basic2 = new Basic(); String string2 = "e2432423432wpofjewgprgrg"; basic2.id = string2; assertEquals(1, basicDao.create(basic2)); Foo foo1 = new Foo(); foo1.stuff = basic1.id; Foo foo2 = new Foo(); foo2.stuff = basic2.id; Foo foo3 = new Foo(); String string3 = "neither of the others"; foo3.stuff = string3; int num1 = 7; for (int i = 0; i < num1; i++) { assertEquals(1, fooDao.create(foo1)); } int num2 = 17; for (int i = 0; i < num2; i++) { assertEquals(1, fooDao.create(foo2)); } int num3 = 29; long maxId = 0; for (int i = 0; i < num3; i++) { assertEquals(1, fooDao.create(foo3)); if (foo3.id > maxId) { maxId = foo3.id; } } QueryBuilder<Basic, String> bqb = basicDao.queryBuilder(); bqb.selectColumns(Basic.ID_FIELD); // string1 bqb.where().eq(Basic.ID_FIELD, string1); List<Foo> results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1, results.size()); // string2 bqb.where().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num2, results.size()); // ! string2 with not().in(...) bqb.where().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().not().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num3, results.size()); // string3 which there should be none bqb.where().eq(Basic.ID_FIELD, string3); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(0, results.size()); // string1 OR string2 bqb.where().eq(Basic.ID_FIELD, string1).or().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num2, results.size()); // all strings IN bqb.where().in(Basic.ID_FIELD, string1, string2, string3); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num2, results.size()); // string1 AND string2 which there should be none bqb.where().eq(Basic.ID_FIELD, string1).and().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(0, results.size()); } public void testInSubQuerySelectArgs() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Basic, String> basicDao = createDao(Basic.class, true); Basic basic1 = new Basic(); String string1 = "ewpofjewgprgrg"; basic1.id = string1; assertEquals(1, basicDao.create(basic1)); Basic basic2 = new Basic(); String string2 = "e2432423432wpofjewgprgrg"; basic2.id = string2; assertEquals(1, basicDao.create(basic2)); Foo foo1 = new Foo(); foo1.stuff = basic1.id; Foo foo2 = new Foo(); foo2.stuff = basic2.id; int num1 = 7; for (int i = 0; i < num1; i++) { assertEquals(1, fooDao.create(foo1)); } int num2 = 17; long maxId = 0; for (int i = 0; i < num2; i++) { assertEquals(1, fooDao.create(foo2)); if (foo2.id > maxId) { maxId = foo2.id; } } // using seletArgs SelectArg arg1 = new SelectArg(); SelectArg arg2 = new SelectArg(); QueryBuilder<Basic, String> bqb = basicDao.queryBuilder(); bqb.selectColumns(Basic.ID_FIELD); bqb.where().eq(Basic.ID_FIELD, arg1); PreparedQuery<Foo> preparedQuery = fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).and().lt(Foo.ID_FIELD_NAME, arg2).prepare(); arg1.setValue(string1); // this should get none arg2.setValue(0); List<Foo> results = fooDao.query(preparedQuery); assertEquals(0, results.size()); } public void testPrepareStatementUpdateValueNumber() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); foo.val = 123213; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.ID_FIELD_NAME, foo.id); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); updateb.updateColumnValue(Foo.VAL_FIELD_NAME, foo.val + 1); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); assertEquals(foo.val + 1, results.get(0).val); } public void testPrepareStatementUpdateValueExpression() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); foo.val = 123213; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.ID_FIELD_NAME, foo.id); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String stuff = "deopdjq"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, stuff); StringBuilder sb = new StringBuilder(); updateb.escapeColumnName(sb, Foo.VAL_FIELD_NAME); sb.append("+ 1"); updateb.updateColumnExpression(Foo.VAL_FIELD_NAME, sb.toString()); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.queryForAll(); assertEquals(1, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(foo.val + 1, results.get(0).val); } public void testPrepareStatementUpdateValueWhere() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 78582351; assertEquals(1, fooDao.create(foo1)); Foo foo2 = new Foo(); String stuff = "eopqjdepodje"; foo2.stuff = stuff; foo2.val = 123344131; assertEquals(1, fooDao.create(foo2)); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String newStuff = "deopdjq"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, newStuff); StringBuilder sb = new StringBuilder(); updateb.escapeColumnName(sb, Foo.VAL_FIELD_NAME); sb.append("+ 1"); updateb.updateColumnExpression(Foo.VAL_FIELD_NAME, sb.toString()); updateb.where().eq(Foo.ID_FIELD_NAME, foo2.id); assertEquals(1, fooDao.update(updateb.prepare())); List<Foo> results = fooDao.queryForAll(); assertEquals(2, results.size()); Foo foo = results.get(0); assertEquals(foo1.id, foo.id); assertEquals(foo1.val, foo.val); assertNull(foo.stuff); foo = results.get(1); assertEquals(foo2.id, foo.id); assertEquals(foo2.val + 1, foo.val); assertEquals(newStuff, foo.stuff); } public void testStringAsId() throws Exception { checkTypeAsId(StringId.class, "foo", "bar"); } public void testLongStringAsId() throws Exception { try { createDao(LongStringId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } public void testBooleanAsId() throws Exception { try { createDao(BooleanId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } public void testBooleanObjAsId() throws Exception { try { createDao(BooleanObjId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } public void testDateAsId() throws Exception { // no milliseconds checkTypeAsId(DateId.class, new Date(1232312313000L), new Date(1232312783000L)); } public void testDateLongAsId() throws Exception { // no milliseconds checkTypeAsId(DateLongId.class, new Date(1232312313000L), new Date(1232312783000L)); } public void testDateStringAsId() throws Exception { // no milliseconds checkTypeAsId(DateStringId.class, new Date(1232312313000L), new Date(1232312783000L)); } public void testByteAsId() throws Exception { checkTypeAsId(ByteId.class, (byte) 1, (byte) 2); } public void testByteObjAsId() throws Exception { checkTypeAsId(ByteObjId.class, (byte) 1, (byte) 2); } public void testShortAsId() throws Exception { checkTypeAsId(ShortId.class, (short) 1, (short) 2); } public void testShortObjAsId() throws Exception { checkTypeAsId(ShortObjId.class, (short) 1, (short) 2); } public void testIntAsId() throws Exception { checkTypeAsId(IntId.class, (int) 1, (int) 2); } public void testIntObjAsId() throws Exception { checkTypeAsId(IntObjId.class, (int) 1, (int) 2); } public void testLongAsId() throws Exception { checkTypeAsId(LongId.class, (long) 1, (long) 2); } public void testLongObjAsId() throws Exception { checkTypeAsId(LongObjId.class, (long) 1, (long) 2); } public void testFloatAsId() throws Exception { checkTypeAsId(FloatId.class, (float) 1, (float) 2); } public void testFloatObjAsId() throws Exception { checkTypeAsId(FloatObjId.class, (float) 1, (float) 2); } public void testDoubleAsId() throws Exception { checkTypeAsId(DoubleId.class, (double) 1, (double) 2); } public void testDoubleObjAsId() throws Exception { checkTypeAsId(DoubleObjId.class, (double) 1, (double) 2); } public void testEnumAsId() throws Exception { checkTypeAsId(EnumId.class, OurEnum.SECOND, OurEnum.FIRST); } public void testEnumStringAsId() throws Exception { checkTypeAsId(EnumStringId.class, OurEnum.SECOND, OurEnum.FIRST); } public void testEnumIntegerAsId() throws Exception { checkTypeAsId(EnumIntegerId.class, OurEnum.SECOND, OurEnum.FIRST); } public void testSerializableAsId() throws Exception { try { createDao(SerializableId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } public void testRecursiveForeign() throws Exception { Dao<Recursive, Integer> recursiveDao = createDao(Recursive.class, true); Recursive recursive1 = new Recursive(); Recursive recursive2 = new Recursive(); recursive2.foreign = recursive1; assertEquals(recursiveDao.create(recursive1), 1); assertEquals(recursiveDao.create(recursive2), 1); Recursive recursive3 = recursiveDao.queryForId(recursive2.id); assertNotNull(recursive3); assertEquals(recursive1.id, recursive3.foreign.id); } public void testSerializableWhere() throws Exception { Dao<AllTypes, Object> allDao = createDao(AllTypes.class, true); try { // can't query for a serial field allDao.queryBuilder().where().eq(AllTypes.SERIAL_FIELD_NAME, new SelectArg()); fail("expected exception"); } catch (SQLException e) { // expected } } public void testSerializedBytes() throws Exception { Dao<SerializedBytes, Integer> dao = createDao(SerializedBytes.class, true); SerializedBytes serial = new SerializedBytes(); serial.bytes = new byte[] { 1, 25, 3, 124, 10 }; assertEquals(1, dao.create(serial)); SerializedBytes raw2 = dao.queryForId(serial.id); assertNotNull(raw2); assertEquals(serial.id, raw2.id); assertTrue(Arrays.equals(serial.bytes, raw2.bytes)); } public void testByteArray() throws Exception { Dao<ByteArray, Integer> dao = createDao(ByteArray.class, true); ByteArray foo = new ByteArray(); foo.bytes = new byte[] { 17, 25, 3, 124, 0, 127, 10 }; assertEquals(1, dao.create(foo)); ByteArray raw2 = dao.queryForId(foo.id); assertNotNull(raw2); assertEquals(foo.id, raw2.id); assertTrue(Arrays.equals(foo.bytes, raw2.bytes)); } public void testSuperClassAnnotations() throws Exception { Dao<Sub, Integer> dao = createDao(Sub.class, true); Sub sub1 = new Sub(); String stuff = "doepqjdpqdq"; sub1.stuff = stuff; assertEquals(1, dao.create(sub1)); Sub sub2 = dao.queryForId(sub1.id); assertNotNull(sub2); assertEquals(sub1.id, sub2.id); assertEquals(sub1.stuff, sub2.stuff); } public void testFieldIndex() throws Exception { Dao<Index, Integer> dao = createDao(Index.class, true); Index index1 = new Index(); String stuff = "doepqjdpqdq"; index1.stuff = stuff; assertEquals(1, dao.create(index1)); Index index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); // this should work assertEquals(1, dao.create(index1)); PreparedQuery<Index> query = dao.queryBuilder().where().eq("stuff", index1.stuff).prepare(); List<Index> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(stuff, results.get(1).stuff); } public void testFieldIndexColumnName() throws Exception { Dao<IndexColumnName, Integer> dao = createDao(IndexColumnName.class, true); IndexColumnName index1 = new IndexColumnName(); String stuff = "doepqjdpqdq"; index1.stuff = stuff; assertEquals(1, dao.create(index1)); IndexColumnName index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); // this should work assertEquals(1, dao.create(index1)); PreparedQuery<IndexColumnName> query = dao.queryBuilder().where().eq(IndexColumnName.STUFF_COLUMN_NAME, index1.stuff).prepare(); List<IndexColumnName> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(stuff, results.get(1).stuff); } public void testFieldUniqueIndex() throws Exception { Dao<UniqueIndex, Integer> dao = createDao(UniqueIndex.class, true); UniqueIndex index1 = new UniqueIndex(); String stuff1 = "doepqjdpqdq"; index1.stuff = stuff1; assertEquals(1, dao.create(index1)); UniqueIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff1, index2.stuff); try { dao.create(index1); fail("This should have thrown"); } catch (SQLException e) { // expected } String stuff2 = "fewofwgwgwee"; index1.stuff = stuff2; assertEquals(1, dao.create(index1)); PreparedQuery<UniqueIndex> query = dao.queryBuilder().where().eq("stuff", stuff1).prepare(); List<UniqueIndex> results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff1, results.get(0).stuff); query = dao.queryBuilder().where().eq("stuff", stuff2).prepare(); results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff2, results.get(0).stuff); } public void testComboFieldIndex() throws Exception { Dao<ComboIndex, Integer> dao = createDao(ComboIndex.class, true); ComboIndex index1 = new ComboIndex(); String stuff = "doepqjdpqdq"; long junk1 = 131234124213213L; index1.stuff = stuff; index1.junk = junk1; assertEquals(1, dao.create(index1)); ComboIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); assertEquals(junk1, index2.junk); assertEquals(1, dao.create(index1)); PreparedQuery<ComboIndex> query = dao.queryBuilder().where().eq("stuff", index1.stuff).prepare(); List<ComboIndex> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(junk1, results.get(0).junk); assertEquals(stuff, results.get(1).stuff); assertEquals(junk1, results.get(1).junk); } public void testComboUniqueFieldIndex() throws Exception { Dao<ComboUniqueIndex, Integer> dao = createDao(ComboUniqueIndex.class, true); ComboUniqueIndex index1 = new ComboUniqueIndex(); String stuff1 = "doepqjdpqdq"; long junk = 131234124213213L; index1.stuff = stuff1; index1.junk = junk; assertEquals(1, dao.create(index1)); ComboUniqueIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(index1.stuff, index2.stuff); assertEquals(index1.junk, index2.junk); try { dao.create(index1); fail("This should have thrown"); } catch (SQLException e) { // expected } String stuff2 = "fpeowjfewpf"; index1.stuff = stuff2; // same junk assertEquals(1, dao.create(index1)); PreparedQuery<ComboUniqueIndex> query = dao.queryBuilder().where().eq("stuff", stuff1).prepare(); List<ComboUniqueIndex> results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff1, results.get(0).stuff); assertEquals(junk, results.get(0).junk); query = dao.queryBuilder().where().eq("stuff", stuff2).prepare(); results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff2, results.get(0).stuff); assertEquals(junk, results.get(0).junk); } public void testLongVarChar() throws Exception { Dao<LongVarChar, Integer> dao = createDao(LongVarChar.class, true); LongVarChar lvc = new LongVarChar(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10240; i++) { sb.append("."); } String stuff = sb.toString(); lvc.stuff = stuff; assertEquals(1, dao.create(lvc)); LongVarChar lvc2 = dao.queryForId(lvc.id); assertNotNull(lvc2); assertEquals(stuff, lvc2.stuff); } public void testTableExists() throws Exception { if (!isTableExistsWorks()) { return; } Dao<Foo, Integer> dao = createDao(Foo.class, false); assertFalse(dao.isTableExists()); TableUtils.createTable(connectionSource, Foo.class); assertTrue(dao.isTableExists()); TableUtils.dropTable(connectionSource, Foo.class, false); assertFalse(dao.isTableExists()); } public void testRaw() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo = new Foo(); int val = 131265312; foo.val = val; assertEquals(1, dao.create(foo)); StringBuilder sb = new StringBuilder(); databaseType.appendEscapedEntityName(sb, Foo.VAL_FIELD_NAME); String fieldName = sb.toString(); QueryBuilder<Foo, Integer> qb = dao.queryBuilder(); qb.where().eq(Foo.ID_FIELD_NAME, foo.id).and().raw(fieldName + " = " + val); assertEquals(1, dao.query(qb.prepare()).size()); qb.where().eq(Foo.ID_FIELD_NAME, foo.id).and().raw(fieldName + " != " + val); assertEquals(0, dao.query(qb.prepare()).size()); } public void testUuidInsertQuery() throws Exception { Dao<UuidGeneratedId, UUID> dao = createDao(UuidGeneratedId.class, true); UuidGeneratedId uuid1 = new UuidGeneratedId(); String stuff1 = "fopewfjefjwgw"; uuid1.stuff = stuff1; assertNull(uuid1.id); assertEquals(1, dao.create(uuid1)); assertNotNull(uuid1.id); UuidGeneratedId uuid2 = new UuidGeneratedId(); String stuff2 = "fopefewjfepowfjefjwgw"; uuid2.stuff = stuff2; assertNull(uuid2.id); assertEquals(1, dao.create(uuid2)); assertNotNull(uuid2.id); assertFalse(uuid1.id.equals(uuid2.id)); List<UuidGeneratedId> uuids = dao.queryForAll(); assertEquals(2, uuids.size()); UuidGeneratedId uuid3 = dao.queryForId(uuid1.id); assertEquals(stuff1, uuid3.stuff); uuid3 = dao.queryForId(uuid2.id); assertEquals(stuff2, uuid3.stuff); } public void testBaseDaoEnabled() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(dao); assertEquals(1, one.create()); } public void testBaseDaoEnabledForeign() throws Exception { Dao<One, Integer> oneDao = createDao(One.class, true); Dao<ForeignDaoEnabled, Integer> foreignDao = createDao(ForeignDaoEnabled.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(oneDao); assertEquals(1, one.create()); ForeignDaoEnabled foreign = new ForeignDaoEnabled(); foreign.one = one; foreign.setDao(foreignDao); assertEquals(1, foreign.create()); ForeignDaoEnabled foreign2 = foreignDao.queryForId(foreign.id); assertNotNull(foreign2); assertEquals(one.id, foreign2.one.id); assertNull(foreign2.one.stuff); assertEquals(1, foreign2.one.refresh()); assertEquals(stuff, foreign2.one.stuff); } public void testBasicEagerCollection() throws Exception { Dao<EagerAccount, Integer> accountDao = createDao(EagerAccount.class, true); Dao<EagerOrder, Integer> orderDao = createDao(EagerOrder.class, true); EagerAccount account = new EagerAccount(); String name = "fwepfjewfew"; account.name = name; assertEquals(1, accountDao.create(account)); EagerOrder order1 = new EagerOrder(); int val1 = 13123441; order1.val = val1; order1.account = account; assertEquals(1, orderDao.create(order1)); EagerOrder order2 = new EagerOrder(); int val2 = 113787097; order2.val = val2; order2.account = account; assertEquals(1, orderDao.create(order2)); EagerAccount account2 = accountDao.queryForId(account.id); assertEquals(name, account2.name); assertNotNull(account2.orders); int orderC = 0; for (EagerOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; } } assertEquals(2, orderC); // insert it via the collection EagerOrder order3 = new EagerOrder(); int val3 = 76557654; order3.val = val3; order3.account = account; account2.orders.add(order3); // the size should change immediately assertEquals(3, account2.orders.size()); // now insert it behind the collections back EagerOrder order4 = new EagerOrder(); int val4 = 1123587097; order4.val = val4; order4.account = account; assertEquals(1, orderDao.create(order4)); // account2's collection should not have changed assertEquals(3, account2.orders.size()); // now we refresh the collection assertEquals(1, accountDao.refresh(account2)); assertEquals(name, account2.name); assertNotNull(account2.orders); orderC = 0; for (EagerOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; case 4 : assertEquals(val4, order.val); break; } } assertEquals(4, orderC); } public void testBasicLazyCollection() throws Exception { Dao<LazyAccount, Integer> accountDao = createDao(LazyAccount.class, true); Dao<LazyOrder, Integer> orderDao = createDao(LazyOrder.class, true); LazyAccount account = new LazyAccount(); String name = "fwepfjewfew"; account.name = name; assertEquals(1, accountDao.create(account)); LazyOrder order1 = new LazyOrder(); int val1 = 13123441; order1.val = val1; order1.account = account; assertEquals(1, orderDao.create(order1)); LazyOrder order2 = new LazyOrder(); int val2 = 113787097; order2.val = val2; order2.account = account; assertEquals(1, orderDao.create(order2)); LazyAccount account2 = accountDao.queryForId(account.id); assertEquals(name, account2.name); assertNotNull(account2.orders); int orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; } } assertEquals(2, orderC); // insert it via the collection LazyOrder order3 = new LazyOrder(); int val3 = 76557654; order3.val = val3; order3.account = account; account2.orders.add(order3); orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; } } assertEquals(3, orderC); // now insert it behind the collections back LazyOrder order4 = new LazyOrder(); int val4 = 1123587097; order4.val = val4; order4.account = account; assertEquals(1, orderDao.create(order4)); // without refreshing we should see the new order orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; case 4 : assertEquals(val4, order.val); break; } } assertEquals(4, orderC); } @SuppressWarnings("unchecked") public void testUseOfAndMany() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id)); List<Foo> results = where.query(); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); // this should match none where.clear(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id), where.eq(Foo.ID_FIELD_NAME, notId)); results = where.query(); assertEquals(0, results.size()); } @SuppressWarnings("unchecked") public void testUseOfAndInt() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id)); List<Foo> results = where.query(); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); // this should match none where.clear(); where.eq(Foo.VAL_FIELD_NAME, val); where.eq(Foo.ID_FIELD_NAME, id); where.eq(Foo.ID_FIELD_NAME, notId); where.and(3); results = where.query(); assertEquals(0, results.size()); } @SuppressWarnings("unchecked") public void testUseOfOrMany() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.or(where.eq(Foo.ID_FIELD_NAME, id), where.eq(Foo.ID_FIELD_NAME, notId), where.eq(Foo.VAL_FIELD_NAME, val + 1), where.eq(Foo.VAL_FIELD_NAME, val + 1)); List<Foo> results = where.query(); assertEquals(2, results.size()); assertEquals(id, results.get(0).id); assertEquals(notId, results.get(1).id); } public void testUseOfOrInt() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.eq(Foo.ID_FIELD_NAME, id); where.eq(Foo.ID_FIELD_NAME, notId); where.eq(Foo.VAL_FIELD_NAME, val + 1); where.eq(Foo.VAL_FIELD_NAME, val + 1); where.or(4); List<Foo> results = where.query(); assertEquals(2, results.size()); assertEquals(id, results.get(0).id); assertEquals(notId, results.get(1).id); } public void testQueryForMatching() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Foo match = new Foo(); match.val = val; List<Foo> results = dao.queryForMatching(match); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); match = new Foo(); match.id = notId; match.val = val; results = dao.queryForMatching(match); assertEquals(0, results.size()); } public void testQueryForFieldValues() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put(Foo.VAL_FIELD_NAME, val); List<Foo> results = dao.queryForFieldValues(fieldValues); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); fieldValues.put(Foo.ID_FIELD_NAME, notId); fieldValues.put(Foo.VAL_FIELD_NAME, val); results = dao.queryForFieldValues(fieldValues); assertEquals(0, results.size()); } public void testInsertAutoGeneratedId() throws Exception { Dao<Foo, Integer> dao1 = createDao(Foo.class, true); Dao<NotQuiteFoo, Integer> dao2 = createDao(NotQuiteFoo.class, false); Foo foo = new Foo(); assertEquals(1, dao1.create(foo)); NotQuiteFoo notQuiteFoo = new NotQuiteFoo(); notQuiteFoo.id = foo.id + 1; assertEquals(1, dao2.create(notQuiteFoo)); List<Foo> results = dao1.queryForAll(); assertEquals(2, results.size()); assertEquals(foo.id, results.get(0).id); assertEquals(notQuiteFoo.id, results.get(1).id); } public void testCreateWithAllowGeneratedIdInsert() throws Exception { if (databaseType == null || !databaseType.isAllowGeneratedIdInsertSupported()) { return; } Dao<AllowGeneratedIdInsert, Integer> dao = createDao(AllowGeneratedIdInsert.class, true); AllowGeneratedIdInsert foo = new AllowGeneratedIdInsert(); assertEquals(1, dao.create(foo)); AllowGeneratedIdInsert result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.id, result.id); AllowGeneratedIdInsert foo2 = new AllowGeneratedIdInsert(); assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.id, result.id); assertFalse(foo2.id == foo.id); AllowGeneratedIdInsert foo3 = new AllowGeneratedIdInsert(); foo3.id = 10002; assertEquals(1, dao.create(foo3)); result = dao.queryForId(foo3.id); assertNotNull(result); assertEquals(foo3.id, result.id); assertFalse(foo3.id == foo.id); assertFalse(foo3.id == foo2.id); } public void testCreateWithAllowGeneratedIdInsertObject() throws Exception { if (databaseType == null || !databaseType.isAllowGeneratedIdInsertSupported()) { return; } Dao<AllowGeneratedIdInsertObject, Integer> dao = createDao(AllowGeneratedIdInsertObject.class, true); AllowGeneratedIdInsertObject foo = new AllowGeneratedIdInsertObject(); assertEquals(1, dao.create(foo)); AllowGeneratedIdInsertObject result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.id, result.id); AllowGeneratedIdInsertObject foo2 = new AllowGeneratedIdInsertObject(); assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.id, result.id); assertFalse(foo2.id == foo.id); AllowGeneratedIdInsertObject foo3 = new AllowGeneratedIdInsertObject(); foo3.id = 10002; assertEquals(1, dao.create(foo3)); result = dao.queryForId(foo3.id); assertNotNull(result); assertEquals(foo3.id, result.id); assertFalse(foo3.id == foo.id); assertFalse(foo3.id == foo2.id); } public void testCreateOrUpdate() throws Exception { Dao<NotQuiteFoo, Integer> dao = createDao(NotQuiteFoo.class, true); NotQuiteFoo foo1 = new NotQuiteFoo(); foo1.stuff = "wow"; CreateOrUpdateStatus status = dao.createOrUpdate(foo1); assertTrue(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); String stuff2 = "4134132"; foo1.stuff = stuff2; status = dao.createOrUpdate(foo1); assertFalse(status.isCreated()); assertTrue(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); NotQuiteFoo result = dao.queryForId(foo1.id); assertEquals(stuff2, result.stuff); } public void testCreateOrUpdateNull() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); CreateOrUpdateStatus status = dao.createOrUpdate(null); assertFalse(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(0, status.getNumLinesChanged()); } public void testCreateOrUpdateNullId() throws Exception { Dao<CreateOrUpdateObjectId, Integer> dao = createDao(CreateOrUpdateObjectId.class, true); CreateOrUpdateObjectId foo = new CreateOrUpdateObjectId(); String stuff = "21313"; foo.stuff = stuff; CreateOrUpdateStatus status = dao.createOrUpdate(foo); assertTrue(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); CreateOrUpdateObjectId result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(stuff, result.stuff); String stuff2 = "pwojgfwe"; foo.stuff = stuff2; dao.createOrUpdate(foo); result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(stuff2, result.stuff); } public void testUpdateNoChange() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); foo.id = 13567567; foo.val = 1232131; assertEquals(1, dao.create(foo)); assertEquals(1, dao.update(foo)); assertEquals(1, dao.update(foo)); } public void testNullForeign() throws Exception { Dao<Order, Integer> orderDao = createDao(Order.class, true); int NUM_ORDERS = 10; for (int orderC = 0; orderC < NUM_ORDERS; orderC++) { Order order = new Order(); order.val = orderC; assertEquals(1, orderDao.create(order)); } List<Order> results = orderDao.queryBuilder().where().isNull(Order.ONE_FIELD_NAME).query(); assertNotNull(results); assertEquals(NUM_ORDERS, results.size()); } private <T extends TestableType<ID>, ID> void checkTypeAsId(Class<T> clazz, ID id1, ID id2) throws Exception { Constructor<T> constructor = clazz.getDeclaredConstructor(); Dao<T, ID> dao = createDao(clazz, true); String s1 = "stuff"; T data1 = constructor.newInstance(); data1.setId(id1); data1.setStuff(s1); // create it assertEquals(1, dao.create(data1)); // refresh it assertEquals(1, dao.refresh(data1)); // now we query for foo from the database to make sure it was persisted right T data2 = dao.queryForId(id1); assertNotNull(data2); assertEquals(id1, data2.getId()); assertEquals(s1, data2.getStuff()); // now we update 1 row in a the database after changing stuff String s2 = "stuff2"; data2.setStuff(s2); assertEquals(1, dao.update(data2)); // now we get it from the db again to make sure it was updated correctly T data3 = dao.queryForId(id1); assertEquals(s2, data3.getStuff()); // change its id assertEquals(1, dao.updateId(data2, id2)); // the old id should not exist assertNull(dao.queryForId(id1)); T data4 = dao.queryForId(id2); assertNotNull(data4); assertEquals(s2, data4.getStuff()); // delete it assertEquals(1, dao.delete(data2)); // should not find it assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); // create data1 and data2 data1.setId(id1); assertEquals(1, dao.create(data1)); data2 = constructor.newInstance(); data2.setId(id2); assertEquals(1, dao.create(data2)); data3 = dao.queryForId(id1); assertNotNull(data3); assertEquals(id1, data3.getId()); data4 = dao.queryForId(id2); assertNotNull(data4); assertEquals(id2, data4.getId()); // delete a collection of ids List<ID> idList = new ArrayList<ID>(); idList.add(id1); idList.add(id2); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, dao.deleteIds(idList)); } else { assertEquals(2, dao.deleteIds(idList)); } assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); // delete a collection of objects assertEquals(1, dao.create(data1)); assertEquals(1, dao.create(data2)); List<T> dataList = new ArrayList<T>(); dataList.add(data1); dataList.add(data2); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, dao.delete(dataList)); } else { assertEquals(2, dao.delete(dataList)); } assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); } /** * Returns the object if the query failed or null otherwise. */ private boolean checkQueryResult(Dao<AllTypes, Integer> allDao, QueryBuilder<AllTypes, Integer> qb, AllTypes allTypes, String fieldName, Object value, boolean required) throws SQLException { qb.where().eq(fieldName, value); List<AllTypes> results = allDao.query(qb.prepare()); if (required) { assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } else if (results.size() == 1) { assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } else { return false; } SelectArg selectArg = new SelectArg(); qb.where().eq(fieldName, selectArg); selectArg.setValue(value); results = allDao.query(qb.prepare()); assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); return true; } private String buildFooQueryAllString(Dao<Foo, Object> fooDao) throws SQLException { String queryString = fooDao.queryBuilder() .selectColumns(Foo.ID_FIELD_NAME, Foo.STUFF_FIELD_NAME, Foo.VAL_FIELD_NAME) .prepareStatementString(); return queryString; } private interface TestableType<ID> { String getStuff(); void setStuff(String stuff); ID getId(); void setId(ID id); } private static class Mapper implements RawRowMapper<Foo> { public Foo mapRow(String[] columnNames, String[] resultColumns) { Foo foo = new Foo(); for (int i = 0; i < columnNames.length; i++) { if (columnNames[i].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { foo.id = Integer.parseInt(resultColumns[i]); } else if (columnNames[i].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { foo.stuff = resultColumns[i]; } else if (columnNames[i].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { foo.val = Integer.parseInt(resultColumns[i]); } } return foo; } } @DatabaseTable(tableName = FOO_TABLE_NAME) protected static class Foo { public final static String ID_FIELD_NAME = "id"; public final static String STUFF_FIELD_NAME = "stuff"; public final static String VAL_FIELD_NAME = "val"; @DatabaseField(generatedId = true, columnName = ID_FIELD_NAME) public int id; @DatabaseField(columnName = STUFF_FIELD_NAME) public String stuff; @DatabaseField(columnName = VAL_FIELD_NAME) public int val; public Foo() { } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return id == ((Foo) other).id; } @Override public String toString() { return "Foo.id=" + id; } } @DatabaseTable(tableName = FOO_TABLE_NAME) protected static class NotQuiteFoo { @DatabaseField(id = true, columnName = Foo.ID_FIELD_NAME) public int id; @DatabaseField(columnName = Foo.STUFF_FIELD_NAME) public String stuff; @DatabaseField(columnName = Foo.VAL_FIELD_NAME) public int val; public NotQuiteFoo() { } } protected static class DoubleCreate { @DatabaseField(id = true) int id; } protected static class NoId { @DatabaseField public String notId; } private static class JustId { @DatabaseField(id = true) public String id; } private static class ForeignWrapper { private final static String FOREIGN_FIELD_NAME = "foreign"; @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true, columnName = FOREIGN_FIELD_NAME) AllTypes foreign; } private static class MultipleForeignWrapper { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true) AllTypes foreign; @DatabaseField(foreign = true) ForeignWrapper foreignWrapper; } protected static class GetSet { @DatabaseField(generatedId = true, useGetSet = true) private int id; @DatabaseField(useGetSet = true) private String stuff; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } protected static class NoAnno { public int id; public String stuff; public NoAnno() { } } protected static class NoAnnoFor { public int id; public NoAnno foreign; public NoAnnoFor() { } } protected static class GeneratedIdNotNull { @DatabaseField(generatedId = true, canBeNull = false) public int id; @DatabaseField public String stuff; public GeneratedIdNotNull() { } } protected static class Basic { public final static String ID_FIELD = "id"; @DatabaseField(id = true, columnName = ID_FIELD) String id; } private static class DefaultValue { @DatabaseField(defaultValue = DEFAULT_VALUE_STRING) Integer intField; DefaultValue() { } } protected static class NotNull { @DatabaseField(canBeNull = false) String notNull; NotNull() { } } protected static class GeneratedId { @DatabaseField(generatedId = true) int id; @DatabaseField String other; public GeneratedId() { } } protected static class AllTypes { public static final String STRING_FIELD_NAME = "stringField"; public static final String BOOLEAN_FIELD_NAME = "booleanField"; public static final String DATE_FIELD_NAME = "dateField"; public static final String DATE_LONG_FIELD_NAME = "dateLongField"; public static final String DATE_STRING_FIELD_NAME = "dateStringField"; public static final String SERIAL_FIELD_NAME = "serialField"; public static final String CHAR_FIELD_NAME = "charField"; public static final String BYTE_FIELD_NAME = "byteField"; public static final String SHORT_FIELD_NAME = "shortField"; public static final String INT_FIELD_NAME = "intField"; public static final String LONG_FIELD_NAME = "longField"; public static final String FLOAT_FIELD_NAME = "floatField"; public static final String DOUBLE_FIELD_NAME = "doubleField"; public static final String ENUM_FIELD_NAME = "enumField"; public static final String ENUM_STRING_FIELD_NAME = "enumStringField"; public static final String ENUM_INTEGER_FIELD_NAME = "enumIntegerField"; @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = STRING_FIELD_NAME) String stringField; @DatabaseField(columnName = BOOLEAN_FIELD_NAME) boolean booleanField; @DatabaseField(columnName = DATE_FIELD_NAME) Date dateField; @DatabaseField(columnName = DATE_LONG_FIELD_NAME, dataType = DataType.DATE_LONG) Date dateLongField; @DatabaseField(columnName = DATE_STRING_FIELD_NAME, dataType = DataType.DATE_STRING, format = DEFAULT_DATE_STRING_FORMAT) Date dateStringField; @DatabaseField(columnName = CHAR_FIELD_NAME) char charField; @DatabaseField(columnName = BYTE_FIELD_NAME) byte byteField; @DatabaseField(columnName = SHORT_FIELD_NAME) short shortField; @DatabaseField(columnName = INT_FIELD_NAME) int intField; @DatabaseField(columnName = LONG_FIELD_NAME) long longField; @DatabaseField(columnName = FLOAT_FIELD_NAME) float floatField; @DatabaseField(columnName = DOUBLE_FIELD_NAME) double doubleField; @DatabaseField(columnName = SERIAL_FIELD_NAME, dataType = DataType.SERIALIZABLE) SerialData serialField; @DatabaseField(columnName = ENUM_FIELD_NAME) OurEnum enumField; @DatabaseField(columnName = ENUM_STRING_FIELD_NAME, dataType = DataType.ENUM_STRING) OurEnum enumStringField; @DatabaseField(columnName = ENUM_INTEGER_FIELD_NAME, dataType = DataType.ENUM_INTEGER) OurEnum enumIntegerField; AllTypes() { } } protected static class AllTypesDefault { @DatabaseField(generatedId = true) int id; @DatabaseField(defaultValue = DEFAULT_STRING_VALUE) String stringField; @DatabaseField(defaultValue = DEFAULT_DATE_VALUE) Date dateField; @DatabaseField(dataType = DataType.DATE_LONG, defaultValue = DEFAULT_DATE_LONG_VALUE) Date dateLongField; @DatabaseField(dataType = DataType.DATE_STRING, defaultValue = DEFAULT_DATE_STRING_VALUE, format = DEFAULT_DATE_STRING_FORMAT) Date dateStringField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) boolean booleanField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) Boolean booleanObj; @DatabaseField(defaultValue = DEFAULT_BYTE_VALUE) byte byteField; @DatabaseField(defaultValue = DEFAULT_BYTE_VALUE) Byte byteObj; @DatabaseField(defaultValue = DEFAULT_SHORT_VALUE) short shortField; @DatabaseField(defaultValue = DEFAULT_SHORT_VALUE) Short shortObj; @DatabaseField(defaultValue = DEFAULT_INT_VALUE) int intField; @DatabaseField(defaultValue = DEFAULT_INT_VALUE) Integer intObj; @DatabaseField(defaultValue = DEFAULT_LONG_VALUE) long longField; @DatabaseField(defaultValue = DEFAULT_LONG_VALUE) Long longObj; @DatabaseField(defaultValue = DEFAULT_FLOAT_VALUE) float floatField; @DatabaseField(defaultValue = DEFAULT_FLOAT_VALUE) Float floatObj; @DatabaseField(defaultValue = DEFAULT_DOUBLE_VALUE) double doubleField; @DatabaseField(defaultValue = DEFAULT_DOUBLE_VALUE) Double doubleObj; @DatabaseField(dataType = DataType.SERIALIZABLE) SerialData objectField; @DatabaseField(defaultValue = DEFAULT_ENUM_VALUE) OurEnum ourEnum; @DatabaseField(defaultValue = DEFAULT_ENUM_NUMBER_VALUE, dataType = DataType.ENUM_INTEGER) OurEnum ourEnumNumber; AllTypesDefault() { } } protected static class BooleanDefault { @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) boolean booleanField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) Boolean booleanObj; BooleanDefault() { } } protected static class AllObjectTypes { @DatabaseField(generatedId = true) int id; @DatabaseField String stringField; @DatabaseField Boolean booleanField; @DatabaseField Date dateField; @DatabaseField Byte byteField; @DatabaseField Short shortField; @DatabaseField Integer intField; @DatabaseField Long longField; @DatabaseField Float floatField; @DatabaseField Double doubleField; @DatabaseField(dataType = DataType.SERIALIZABLE) SerialData objectField; @DatabaseField OurEnum ourEnum; AllObjectTypes() { } } protected static class NumberTypes { @DatabaseField(generatedId = true) public int id; @DatabaseField public byte byteField; @DatabaseField public short shortField; @DatabaseField public int intField; @DatabaseField public long longField; @DatabaseField public float floatField; @DatabaseField public double doubleField; public NumberTypes() { } } protected static class StringWidth { @DatabaseField(width = ALL_TYPES_STRING_WIDTH) String stringField; StringWidth() { } } // for testing reserved table names as fields private static class Create { @DatabaseField(id = true) public String id; } // for testing reserved words as field names protected static class ReservedField { @DatabaseField(id = true) public int select; @DatabaseField public String from; @DatabaseField public String table; @DatabaseField public String where; @DatabaseField public String group; @DatabaseField public String order; @DatabaseField public String values; public ReservedField() { } } // test the field name that has a capital letter in it protected static class GeneratedColumnCapital { @DatabaseField(generatedId = true, columnName = "idCap") int id; @DatabaseField String other; public GeneratedColumnCapital() { } } protected static class ObjectHolder { @DatabaseField(generatedId = true) public int id; @DatabaseField(dataType = DataType.SERIALIZABLE) public SerialData obj; @DatabaseField(dataType = DataType.SERIALIZABLE) public String strObj; public ObjectHolder() { } } protected static class NotSerializable { @DatabaseField(generatedId = true) public int id; @DatabaseField(dataType = DataType.SERIALIZABLE) public ObjectHolder obj; public NotSerializable() { } } protected static class SerialData implements Serializable { private static final long serialVersionUID = -3883857119616908868L; public Map<String, String> map; public SerialData() { } public void addEntry(String key, String value) { if (map == null) { map = new HashMap<String, String>(); } map.put(key, value); } @Override public int hashCode() { return map.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } SerialData other = (SerialData) obj; if (map == null) { return other.map == null; } else { return map.equals(other.map); } } } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumString { @DatabaseField OurEnum ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumString2 { @DatabaseField OurEnum2 ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt { @DatabaseField(dataType = DataType.ENUM_INTEGER) OurEnum ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt2 { @DatabaseField(dataType = DataType.ENUM_INTEGER) OurEnum2 ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt3 { @DatabaseField(dataType = DataType.ENUM_INTEGER, unknownEnumName = "FIRST") OurEnum2 ourEnum; } private enum OurEnum { FIRST, SECOND, ; } private enum OurEnum2 { FIRST, ; } @DatabaseTable(tableName = NULL_BOOLEAN_TABLE_NAME) protected static class NullBoolean1 { @DatabaseField Boolean val; } @DatabaseTable(tableName = NULL_BOOLEAN_TABLE_NAME) protected static class NullBoolean2 { @DatabaseField(throwIfNull = true) boolean val; } @DatabaseTable(tableName = NULL_INT_TABLE_NAME) protected static class NullInt1 { @DatabaseField Integer val; } @DatabaseTable(tableName = NULL_INT_TABLE_NAME) protected static class NullInt2 { @DatabaseField(throwIfNull = true) int val; } @DatabaseTable protected static class NotNullDefault { @DatabaseField(canBeNull = false, defaultValue = "3") String stuff; } @DatabaseTable protected static class Unique { @DatabaseField(generatedId = true) int id; @DatabaseField String stuff; @DatabaseField(unique = true) String uniqueStuff; } @DatabaseTable protected static class DoubleUnique { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String stuff; @DatabaseField(unique = true) String uniqueStuff; } @DatabaseTable protected static class DoubleUniqueCombo { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueCombo = true) String stuff; @DatabaseField(uniqueCombo = true) String uniqueStuff; } @DatabaseTable protected static class UniqueAndUniqueCombo { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String unique1; @DatabaseField(uniqueCombo = true) String combo1; @DatabaseField(uniqueCombo = true) String combo2; } @DatabaseTable protected static class StringDefalt { @DatabaseField(defaultValue = "3") String stuff; } @DatabaseTable protected static class LocalDate { @DatabaseField(generatedId = true) int id; @DatabaseField Date date; } @DatabaseTable protected static class StringId implements TestableType<String> { @DatabaseField(id = true) String id; @DatabaseField String stuff; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongStringId implements TestableType<String> { @DatabaseField(id = true, dataType = DataType.LONG_STRING) String id; @DatabaseField String stuff; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class BooleanId implements TestableType<Boolean> { @DatabaseField(id = true) boolean id; @DatabaseField String stuff; public Boolean getId() { return id; } public void setId(Boolean bool) { this.id = bool; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class BooleanObjId implements TestableType<Boolean> { @DatabaseField(id = true) Boolean id; @DatabaseField String stuff; public Boolean getId() { return id; } public void setId(Boolean bool) { this.id = bool; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateId implements TestableType<Date> { @DatabaseField(id = true) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateLongId implements TestableType<Date> { @DatabaseField(id = true, dataType = DataType.DATE_LONG) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateStringId implements TestableType<Date> { @DatabaseField(id = true, dataType = DataType.DATE_STRING) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ByteId implements TestableType<Byte> { @DatabaseField(id = true) byte id; @DatabaseField String stuff; public Byte getId() { return id; } public void setId(Byte id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ByteObjId implements TestableType<Byte> { @DatabaseField(id = true) Byte id; @DatabaseField String stuff; public Byte getId() { return id; } public void setId(Byte id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ShortId implements TestableType<Short> { @DatabaseField(id = true) short id; @DatabaseField String stuff; public Short getId() { return id; } public void setId(Short id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ShortObjId implements TestableType<Short> { @DatabaseField(id = true) Short id; @DatabaseField String stuff; public Short getId() { return id; } public void setId(Short id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class IntId implements TestableType<Integer> { @DatabaseField(id = true) int id; @DatabaseField String stuff; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class IntObjId implements TestableType<Integer> { @DatabaseField(id = true) Integer id; @DatabaseField String stuff; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongId implements TestableType<Long> { @DatabaseField(id = true) long id; @DatabaseField String stuff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongObjId implements TestableType<Long> { @DatabaseField(id = true) Long id; @DatabaseField String stuff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class FloatId implements TestableType<Float> { @DatabaseField(id = true) float id; @DatabaseField String stuff; public Float getId() { return id; } public void setId(Float id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class FloatObjId implements TestableType<Float> { @DatabaseField(id = true) Float id; @DatabaseField String stuff; public Float getId() { return id; } public void setId(Float id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DoubleId implements TestableType<Double> { @DatabaseField(id = true) double id; @DatabaseField String stuff; public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DoubleObjId implements TestableType<Double> { @DatabaseField(id = true) Double id; @DatabaseField String stuff; public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumId implements TestableType<OurEnum> { @DatabaseField(id = true) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumStringId implements TestableType<OurEnum> { @DatabaseField(id = true, dataType = DataType.ENUM_STRING) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumIntegerId implements TestableType<OurEnum> { @DatabaseField(id = true, dataType = DataType.ENUM_INTEGER) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class SerializableId implements TestableType<SerialData> { @DatabaseField(id = true, dataType = DataType.SERIALIZABLE) SerialData serial; @DatabaseField String stuff; public SerialData getId() { return serial; } public void setId(SerialData id) { this.serial = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class Recursive { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true) Recursive foreign; public Recursive() { } } @DatabaseTable protected static class SerializedBytes { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.SERIALIZABLE) byte[] bytes; public SerializedBytes() { } } @DatabaseTable protected static class ByteArray { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.BYTE_ARRAY) byte[] bytes; public ByteArray() { } } @DatabaseTable protected static class Index { @DatabaseField(generatedId = true) int id; @DatabaseField(index = true) String stuff; public Index() { } } @DatabaseTable protected static class IndexColumnName { public static final String STUFF_COLUMN_NAME = "notStuff"; @DatabaseField(generatedId = true) int id; @DatabaseField(index = true, columnName = STUFF_COLUMN_NAME) String stuff; public IndexColumnName() { } } @DatabaseTable protected static class UniqueIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueIndex = true) String stuff; public UniqueIndex() { } } @DatabaseTable protected static class ComboIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(indexName = "stuffjunk") String stuff; @DatabaseField(indexName = "stuffjunk") long junk; public ComboIndex() { } } @DatabaseTable protected static class ComboUniqueIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueIndexName = "stuffjunk") String stuff; @DatabaseField(uniqueIndexName = "stuffjunk") long junk; public ComboUniqueIndex() { } } @DatabaseTable protected static class LongVarChar { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.LONG_STRING) String stuff; public LongVarChar() { } } protected static class Base { @DatabaseField(id = true) int id; public Base() { // for ormlite } } protected static class Sub extends Base { @DatabaseField String stuff; public Sub() { // for ormlite } } protected static class UuidGeneratedId { @DatabaseField(generatedId = true) public UUID id; @DatabaseField public String stuff; public UuidGeneratedId() { } } protected static class One extends BaseDaoEnabled<One, Integer> { @DatabaseField(generatedId = true) public int id; @DatabaseField public String stuff; public One() { } } protected static class ForeignDaoEnabled extends BaseDaoEnabled<ForeignDaoEnabled, Integer> { @DatabaseField(generatedId = true) public int id; @DatabaseField(foreign = true) public One one; public ForeignDaoEnabled() { } } protected static class EagerAccount { @DatabaseField(generatedId = true) int id; @DatabaseField String name; @ForeignCollectionField(eager = true) Collection<EagerOrder> orders; protected EagerAccount() { } } protected static class EagerOrder { @DatabaseField(generatedId = true) int id; @DatabaseField int val; @DatabaseField(foreign = true) EagerAccount account; protected EagerOrder() { } } protected static class LazyAccount { @DatabaseField(generatedId = true) int id; @DatabaseField String name; @ForeignCollectionField Collection<LazyOrder> orders; protected LazyAccount() { } } protected static class LazyOrder { @DatabaseField(generatedId = true) int id; @DatabaseField int val; @DatabaseField(foreign = true) LazyAccount account; protected LazyOrder() { } } protected static class AllowGeneratedIdInsert { @DatabaseField(generatedId = true, allowGeneratedIdInsert = true) int id; @DatabaseField String stuff; } protected static class AllowGeneratedIdInsertObject { @DatabaseField(generatedId = true, allowGeneratedIdInsert = true) Integer id; @DatabaseField String stuff; } protected static class CreateOrUpdateObjectId { @DatabaseField(generatedId = true) public Integer id; @DatabaseField public String stuff; public CreateOrUpdateObjectId() { } } protected static class Order { public static final String ONE_FIELD_NAME = "one_id"; @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) int val; @DatabaseField(foreign = true, columnName = ONE_FIELD_NAME) One one; protected Order() { } } }
package org.bonej.geometry; import java.util.Arrays; public final class Centroid { private Centroid() {} /** * Find the centroid of an array in double[i][n] format, where i = number of * points and n = number of dimensions * * @param points a set of points in N-dimensions. * @return array containing centroid in N-dimensions */ static double[] getCentroid(final double[][] points) { if (Arrays.stream(points).mapToInt(p -> p.length).distinct().count() != 1) { throw new IllegalArgumentException( "Points must have the same dimensionality"); } final int nDimensions = points[0].length; final double[] centroid = new double[nDimensions]; for (final double[] point : points) { for (int d = 0; d < nDimensions; d++) { centroid[d] += point[d]; } } for (int i = 0; i < centroid.length; i++) { centroid[i] /= points.length; } return centroid; } }
package com.jcwhatever.bukkit.pvs.scripting; import com.jcwhatever.bukkit.generic.scripting.GenericsScriptManager; import com.jcwhatever.bukkit.generic.scripting.IScript; import com.jcwhatever.bukkit.generic.scripting.ScriptApiRepo; import com.jcwhatever.bukkit.generic.utils.ScriptUtils.ScriptConstructor; import com.jcwhatever.bukkit.generic.scripting.api.IScriptApi; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiDepends; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiEconomy; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiInclude; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiInventory; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiItemBank; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiMsg; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiPermissions; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiRand; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiScheduler; import com.jcwhatever.bukkit.generic.scripting.api.ScriptApiSounds; import com.jcwhatever.bukkit.generic.utils.FileUtils.DirectoryTraversal; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.pvs.api.PVStarAPI; import com.jcwhatever.bukkit.pvs.api.scripting.Script; import com.jcwhatever.bukkit.pvs.api.scripting.ScriptManager; import com.jcwhatever.bukkit.pvs.scripting.api.EventsApi; import com.jcwhatever.bukkit.pvs.scripting.api.PlayerApi; import com.jcwhatever.bukkit.pvs.scripting.api.SchedulerApi; import com.jcwhatever.bukkit.pvs.scripting.api.SpawnApi; import com.jcwhatever.bukkit.pvs.scripting.api.StatsApi; import com.jcwhatever.bukkit.pvs.scripting.repo.PVArenasRepoApi; import com.jcwhatever.bukkit.pvs.scripting.repo.PVEventsRepoApi; import com.jcwhatever.bukkit.pvs.scripting.repo.PVPlayersRepoApi; import org.bukkit.plugin.Plugin; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import javax.script.ScriptEngineManager; /** * A central repository of unevaluated scripts which can be used for one or more arenas. */ public class PVScriptManager implements ScriptManager { private final GenericsScriptManager _scriptRepository; private final Map<String, IScriptApi> _apiMap = new HashMap<>(30); private final File _scriptFolder; /* * Constructor. */ public PVScriptManager(Plugin plugin, File scriptFolder) { PreCon.notNull(plugin); PreCon.notNull(scriptFolder); _scriptFolder = scriptFolder; _scriptRepository = new GenericsScriptManager(plugin) { @Override public ScriptConstructor<IScript> getScriptConstructor() { return new ScriptConstructor<IScript>() { @Override public IScript construct(String name, @Nullable String filename, String type, String script) { return new PVScript(name, filename, type, script); } }; } }; _scriptRepository.loadScripts(_scriptFolder, DirectoryTraversal.RECURSIVE); // register Generics script api registerApiType(new ScriptApiEconomy(PVStarAPI.getPlugin())); registerApiType(new ScriptApiInclude(PVStarAPI.getPlugin(), _scriptRepository)); registerApiType(new ScriptApiInventory(PVStarAPI.getPlugin())); registerApiType(new ScriptApiItemBank(PVStarAPI.getPlugin())); registerApiType(new ScriptApiMsg(PVStarAPI.getPlugin())); registerApiType(new ScriptApiPermissions(PVStarAPI.getPlugin())); registerApiType(new ScriptApiSounds(PVStarAPI.getPlugin())); registerApiType(new ScriptApiDepends(PVStarAPI.getPlugin())); registerApiType(new ScriptApiScheduler(PVStarAPI.getPlugin())); registerApiType(new ScriptApiRand(PVStarAPI.getPlugin())); // register PV-Star script api registerApiType(new EventsApi()); registerApiType(new PlayerApi()); registerApiType(new SchedulerApi()); registerApiType(new SpawnApi()); registerApiType(new StatsApi()); // Register scripts in global script api repository ScriptApiRepo.registerApiType(PVStarAPI.getPlugin(), PVArenasRepoApi.class); ScriptApiRepo.registerApiType(PVStarAPI.getPlugin(), PVEventsRepoApi.class); ScriptApiRepo.registerApiType(PVStarAPI.getPlugin(), PVPlayersRepoApi.class); } /* * Get the engine manager used to get script engines. */ @Override public ScriptEngineManager getEngineManager() { return _scriptRepository.getEngineManager(); } /* * Add a script to the script repository */ @Override public void addScript(Script script) { PreCon.notNull(script); _scriptRepository.addScript(script); } /* * Remove a script from the repository by script name. */ @Override public void removeScript(String scriptName) { PreCon.notNullOrEmpty(scriptName); _scriptRepository.removeScript(scriptName); } /* * Register an api to be used in all evaluated scripts. */ @Override public void registerApiType(IScriptApi api) { PreCon.notNull(api); _apiMap.put(api.getVariableName(), api); } /* * Get a script api by its variable name. */ @Override public IScriptApi getScriptApi(String apiVariableName) { PreCon.notNullOrEmpty(apiVariableName); return _apiMap.get(apiVariableName); } /* * Get all script api. */ @Override public List<IScriptApi> getScriptApis() { return new ArrayList<>(_apiMap.values()); } /* * Get a script by name */ @Nullable @Override public Script getScript(String scriptName) { PreCon.notNullOrEmpty(scriptName); IScript iScript = _scriptRepository.getScript(scriptName); return iScript instanceof Script ? (Script) iScript : null; } /* * Get the names of all scripts. */ @Override public List<String> getScriptNames() { return _scriptRepository.getScriptNames(); } /* * Get all scripts. */ @Override public List<Script> getScripts() { List<IScript> iScripts = _scriptRepository.getScripts(); List<Script> scripts = new ArrayList<>(iScripts.size()); for (IScript iScript : iScripts) { scripts.add((Script)iScript); } return scripts; } /* * Reload repository of scripts from script directory. */ @Override public void reload() { _scriptRepository.clearScripts(); _scriptRepository.loadScripts(_scriptFolder, DirectoryTraversal.RECURSIVE); } }
package lombok.javac; import static lombok.javac.handlers.JavacHandlerUtil.genJavaLangTypeRef; import java.lang.reflect.Modifier; import lombok.visitor.VisitorInvariants; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.TypeVar; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; /** * Utility class for Javac creation of visitor-related methods * @author Derek * */ public class VisitableUtils { private VisitableUtils() {} public static VisitableUtils ONLY = new VisitableUtils(); /** * Creates a method for accepting a visitor. If methodBody is supplied, then the method is implemented; * otherwise, it is abstract. * <code> * [@Override] * public [abstract] <R> R accept(RootVisitor<R> visitor) { * [methodBody] * } * </code> * @param node The node of the class that this method is for * @param rootName The name of the root visitable class, used to generate the visitor's name * @param methodBody The method body, should execute one of the visitor argument's cases, or null if the method is abstract * @return The corresponding method declaration */ public JCMethodDecl createAcceptVisitor(JavacNode node, String rootName, JCBlock methodBody) { JavacTreeMaker treeMaker = node.getTreeMaker(); Name returnTypeVarName = node.toName(VisitorInvariants.GENERIC_RETURN_TYPE_NAME); Name methodName = node.toName(VisitorInvariants.VISITOR_ACCEPT_METHOD_NAME); Name visitorClassName = node.toName(VisitorInvariants.createVisitorClassName(rootName)); Name visitorArgName = node.toName(VisitorInvariants.VISITOR_ARG_NAME); // the method is public long modifierFlags = Modifier.PUBLIC | (methodBody == null ? Modifier.ABSTRACT : 0); // create the unbounded generic return type R JCTypeParameter returnType = treeMaker.TypeParameter(returnTypeVarName, List.<JCExpression>nil()); // which is also the only generic type on the method List<JCTypeParameter> methodGenericTypes = List.<JCTypeParameter>of(returnType); // create the return type var itself TypeVar returnTypeVar = new TypeVar(returnTypeVarName, null, null); JCExpression methodReturnType = treeMaker.Type(returnTypeVar); // create the accepted visitor type, ClassNameVisitor<R> ClassType visitorType = new ClassType(Type.noType, List.<Type>of(returnTypeVar), null); TypeSymbol visitorSymbol = new TypeSymbol(0, visitorClassName, visitorType, null); visitorType.tsym = visitorSymbol; // create the visitor argument, ClassNameVisitor<R> visitor (no modifiers, no initialization) JCVariableDecl visitorArg = treeMaker.VarDef(treeMaker.Modifiers(0), visitorArgName, treeMaker.Type(visitorType), null); List<JCVariableDecl> methodParameters = List.<JCVariableDecl>of(visitorArg); List<JCExpression> methodThrows = List.<JCExpression>nil(); // if the method is not abstract, then it must be an Override method List<JCAnnotation> annotations = List.nil(); if (methodBody != null) { annotations = annotations.prepend(treeMaker.Annotation(genJavaLangTypeRef(node, "Override"), List.<JCExpression>nil())); } JCExpression defaultValue = null; return treeMaker.MethodDef(treeMaker.Modifiers(modifierFlags, annotations), methodName, methodReturnType, methodGenericTypes, methodParameters, methodThrows, methodBody, defaultValue); } }
package com.milkenknights.burgundyballista; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Talon; public class ShooterSubsystem extends Subsystem { Talon tWinch; JStick joystick; Solenoid sWinch; boolean loaded; int pullBack; public ShooterSubsystem(RobotConfig config) { tWinch = new Talon(config.getAsInt("tWinch")); joystick = JStickMultiton.getJStick(2); sWinch = new Solenoid(config.getAsInt("sWinch")); pullBack = config.getAsInt("winchPullBack"); } public void teleopPeriodic() { if (joystick.isPressed(3) && loaded == false) { //Need code Here to pull back the shooter pullBack amount loaded = true; } if (joystick.isPressed(1) && loaded == true) { //Need code here to move winch back to where it was loaded = false; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: desktop_window_manager.proto package com.opera.core.systems.scope.protos; public final class DesktopWmProtos { private DesktopWmProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public static final class DesktopWindowInfo extends com.google.protobuf.GeneratedMessage { // Use DesktopWindowInfo.newBuilder() to construct. private DesktopWindowInfo() { initFields(); } private DesktopWindowInfo(boolean noInit) {} private static final DesktopWindowInfo defaultInstance; public static DesktopWindowInfo getDefaultInstance() { return defaultInstance; } public DesktopWindowInfo getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowInfo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowInfo_fieldAccessorTable; } public enum DesktopWindowType implements com.google.protobuf.ProtocolMessageEnum { UNKNOWN(0, 0), DIALOG(1, 1), NORMAL(2, 2), ; public final int getNumber() { return value; } public static DesktopWindowType valueOf(int value) { switch (value) { case 0: return UNKNOWN; case 1: return DIALOG; case 2: return NORMAL; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<DesktopWindowType> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<DesktopWindowType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<DesktopWindowType>() { public DesktopWindowType findValueByNumber(int number) { return DesktopWindowType.valueOf(number) ; } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.getDescriptor().getEnumTypes().get(0); } private static final DesktopWindowType[] VALUES = { UNKNOWN, DIALOG, NORMAL, }; public static DesktopWindowType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private DesktopWindowType(int index, int value) { this.index = index; this.value = value; } static { com.opera.core.systems.scope.protos.DesktopWmProtos.getDescriptor(); } // @@protoc_insertion_point(enum_scope:scope.DesktopWindowInfo.DesktopWindowType) } public enum DesktopWindowState implements com.google.protobuf.ProtocolMessageEnum { RESTORED(0, 0), MINIMIZED(1, 1), MAXIMIZED(2, 2), FULLSCREEN(3, 3), ; public final int getNumber() { return value; } public static DesktopWindowState valueOf(int value) { switch (value) { case 0: return RESTORED; case 1: return MINIMIZED; case 2: return MAXIMIZED; case 3: return FULLSCREEN; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<DesktopWindowState> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<DesktopWindowState> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<DesktopWindowState>() { public DesktopWindowState findValueByNumber(int number) { return DesktopWindowState.valueOf(number) ; } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.getDescriptor().getEnumTypes().get(1); } private static final DesktopWindowState[] VALUES = { RESTORED, MINIMIZED, MAXIMIZED, FULLSCREEN, }; public static DesktopWindowState valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private DesktopWindowState(int index, int value) { this.index = index; this.value = value; } static { com.opera.core.systems.scope.protos.DesktopWmProtos.getDescriptor(); } // @@protoc_insertion_point(enum_scope:scope.DesktopWindowInfo.DesktopWindowState) } // required uint32 windowID = 1; public static final int WINDOWID_FIELD_NUMBER = 1; private boolean hasWindowID; private int windowID_ = 0; public boolean hasWindowID() { return hasWindowID; } public int getWindowID() { return windowID_; } // required string title = 2; public static final int TITLE_FIELD_NUMBER = 2; private boolean hasTitle; private java.lang.String title_ = ""; public boolean hasTitle() { return hasTitle; } public java.lang.String getTitle() { return title_; } // required string name = 3; public static final int NAME_FIELD_NUMBER = 3; private boolean hasName; private java.lang.String name_ = ""; public boolean hasName() { return hasName; } public java.lang.String getName() { return name_; } // required .scope.DesktopWindowInfo.DesktopWindowType windowType = 4; public static final int WINDOWTYPE_FIELD_NUMBER = 4; private boolean hasWindowType; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType windowType_; public boolean hasWindowType() { return hasWindowType; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType getWindowType() { return windowType_; } // required bool onScreen = 5; public static final int ONSCREEN_FIELD_NUMBER = 5; private boolean hasOnScreen; private boolean onScreen_ = false; public boolean hasOnScreen() { return hasOnScreen; } public boolean getOnScreen() { return onScreen_; } // required .scope.DesktopWindowInfo.DesktopWindowState state = 6; public static final int STATE_FIELD_NUMBER = 6; private boolean hasState; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState state_; public boolean hasState() { return hasState; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState getState() { return state_; } // required .scope.DesktopWindowRect rect = 7; public static final int RECT_FIELD_NUMBER = 7; private boolean hasRect; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect rect_; public boolean hasRect() { return hasRect; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return rect_; } // required bool active = 8; public static final int ACTIVE_FIELD_NUMBER = 8; private boolean hasActive; private boolean active_ = false; public boolean hasActive() { return hasActive; } public boolean getActive() { return active_; } private void initFields() { windowType_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType.UNKNOWN; state_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState.RESTORED; rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); } public final boolean isInitialized() { if (!hasWindowID) return false; if (!hasTitle) return false; if (!hasName) return false; if (!hasWindowType) return false; if (!hasOnScreen) return false; if (!hasState) return false; if (!hasRect) return false; if (!hasActive) return false; if (!getRect().isInitialized()) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasWindowID()) { output.writeUInt32(1, getWindowID()); } if (hasTitle()) { output.writeString(2, getTitle()); } if (hasName()) { output.writeString(3, getName()); } if (hasWindowType()) { output.writeEnum(4, getWindowType().getNumber()); } if (hasOnScreen()) { output.writeBool(5, getOnScreen()); } if (hasState()) { output.writeEnum(6, getState().getNumber()); } if (hasRect()) { output.writeMessage(7, getRect()); } if (hasActive()) { output.writeBool(8, getActive()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasWindowID()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, getWindowID()); } if (hasTitle()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(2, getTitle()); } if (hasName()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(3, getName()); } if (hasWindowType()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, getWindowType().getNumber()); } if (hasOnScreen()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, getOnScreen()); } if (hasState()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(6, getState().getNumber()); } if (hasRect()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, getRect()); } if (hasActive()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(8, getActive()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.getDefaultInstance()) return this; if (other.hasWindowID()) { setWindowID(other.getWindowID()); } if (other.hasTitle()) { setTitle(other.getTitle()); } if (other.hasName()) { setName(other.getName()); } if (other.hasWindowType()) { setWindowType(other.getWindowType()); } if (other.hasOnScreen()) { setOnScreen(other.getOnScreen()); } if (other.hasState()) { setState(other.getState()); } if (other.hasRect()) { mergeRect(other.getRect()); } if (other.hasActive()) { setActive(other.getActive()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 8: { setWindowID(input.readUInt32()); break; } case 18: { setTitle(input.readString()); break; } case 26: { setName(input.readString()); break; } case 32: { int rawValue = input.readEnum(); com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType value = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(4, rawValue); } else { setWindowType(value); } break; } case 40: { setOnScreen(input.readBool()); break; } case 48: { int rawValue = input.readEnum(); com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState value = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(6, rawValue); } else { setState(value); } break; } case 58: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(); if (hasRect()) { subBuilder.mergeFrom(getRect()); } input.readMessage(subBuilder, extensionRegistry); setRect(subBuilder.buildPartial()); break; } case 64: { setActive(input.readBool()); break; } } } } // required uint32 windowID = 1; public boolean hasWindowID() { return result.hasWindowID(); } public int getWindowID() { return result.getWindowID(); } public Builder setWindowID(int value) { result.hasWindowID = true; result.windowID_ = value; return this; } public Builder clearWindowID() { result.hasWindowID = false; result.windowID_ = 0; return this; } // required string title = 2; public boolean hasTitle() { return result.hasTitle(); } public java.lang.String getTitle() { return result.getTitle(); } public Builder setTitle(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasTitle = true; result.title_ = value; return this; } public Builder clearTitle() { result.hasTitle = false; result.title_ = getDefaultInstance().getTitle(); return this; } // required string name = 3; public boolean hasName() { return result.hasName(); } public java.lang.String getName() { return result.getName(); } public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasName = true; result.name_ = value; return this; } public Builder clearName() { result.hasName = false; result.name_ = getDefaultInstance().getName(); return this; } // required .scope.DesktopWindowInfo.DesktopWindowType windowType = 4; public boolean hasWindowType() { return result.hasWindowType(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType getWindowType() { return result.getWindowType(); } public Builder setWindowType(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType value) { if (value == null) { throw new NullPointerException(); } result.hasWindowType = true; result.windowType_ = value; return this; } public Builder clearWindowType() { result.hasWindowType = false; result.windowType_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowType.UNKNOWN; return this; } // required bool onScreen = 5; public boolean hasOnScreen() { return result.hasOnScreen(); } public boolean getOnScreen() { return result.getOnScreen(); } public Builder setOnScreen(boolean value) { result.hasOnScreen = true; result.onScreen_ = value; return this; } public Builder clearOnScreen() { result.hasOnScreen = false; result.onScreen_ = false; return this; } // required .scope.DesktopWindowInfo.DesktopWindowState state = 6; public boolean hasState() { return result.hasState(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState getState() { return result.getState(); } public Builder setState(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState value) { if (value == null) { throw new NullPointerException(); } result.hasState = true; result.state_ = value; return this; } public Builder clearState() { result.hasState = false; result.state_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.DesktopWindowState.RESTORED; return this; } // required .scope.DesktopWindowRect rect = 7; public boolean hasRect() { return result.hasRect(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return result.getRect(); } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (value == null) { throw new NullPointerException(); } result.hasRect = true; result.rect_ = value; return this; } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder builderForValue) { result.hasRect = true; result.rect_ = builderForValue.build(); return this; } public Builder mergeRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (result.hasRect() && result.rect_ != com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance()) { result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(result.rect_).mergeFrom(value).buildPartial(); } else { result.rect_ = value; } result.hasRect = true; return this; } public Builder clearRect() { result.hasRect = false; result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); return this; } // required bool active = 8; public boolean hasActive() { return result.hasActive(); } public boolean getActive() { return result.getActive(); } public Builder setActive(boolean value) { result.hasActive = true; result.active_ = value; return this; } public Builder clearActive() { result.hasActive = false; result.active_ = false; return this; } // @@protoc_insertion_point(builder_scope:scope.DesktopWindowInfo) } static { defaultInstance = new DesktopWindowInfo(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.DesktopWindowInfo) } public static final class DesktopWindowRect extends com.google.protobuf.GeneratedMessage { // Use DesktopWindowRect.newBuilder() to construct. private DesktopWindowRect() { initFields(); } private DesktopWindowRect(boolean noInit) {} private static final DesktopWindowRect defaultInstance; public static DesktopWindowRect getDefaultInstance() { return defaultInstance; } public DesktopWindowRect getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowRect_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowRect_fieldAccessorTable; } // required uint32 x = 1; public static final int X_FIELD_NUMBER = 1; private boolean hasX; private int x_ = 0; public boolean hasX() { return hasX; } public int getX() { return x_; } // required uint32 y = 2; public static final int Y_FIELD_NUMBER = 2; private boolean hasY; private int y_ = 0; public boolean hasY() { return hasY; } public int getY() { return y_; } // required uint32 width = 3; public static final int WIDTH_FIELD_NUMBER = 3; private boolean hasWidth; private int width_ = 0; public boolean hasWidth() { return hasWidth; } public int getWidth() { return width_; } // required uint32 height = 4; public static final int HEIGHT_FIELD_NUMBER = 4; private boolean hasHeight; private int height_ = 0; public boolean hasHeight() { return hasHeight; } public int getHeight() { return height_; } private void initFields() { } public final boolean isInitialized() { if (!hasX) return false; if (!hasY) return false; if (!hasWidth) return false; if (!hasHeight) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasX()) { output.writeUInt32(1, getX()); } if (hasY()) { output.writeUInt32(2, getY()); } if (hasWidth()) { output.writeUInt32(3, getWidth()); } if (hasHeight()) { output.writeUInt32(4, getHeight()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasX()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, getX()); } if (hasY()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(2, getY()); } if (hasWidth()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(3, getWidth()); } if (hasHeight()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(4, getHeight()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance()) return this; if (other.hasX()) { setX(other.getX()); } if (other.hasY()) { setY(other.getY()); } if (other.hasWidth()) { setWidth(other.getWidth()); } if (other.hasHeight()) { setHeight(other.getHeight()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 8: { setX(input.readUInt32()); break; } case 16: { setY(input.readUInt32()); break; } case 24: { setWidth(input.readUInt32()); break; } case 32: { setHeight(input.readUInt32()); break; } } } } // required uint32 x = 1; public boolean hasX() { return result.hasX(); } public int getX() { return result.getX(); } public Builder setX(int value) { result.hasX = true; result.x_ = value; return this; } public Builder clearX() { result.hasX = false; result.x_ = 0; return this; } // required uint32 y = 2; public boolean hasY() { return result.hasY(); } public int getY() { return result.getY(); } public Builder setY(int value) { result.hasY = true; result.y_ = value; return this; } public Builder clearY() { result.hasY = false; result.y_ = 0; return this; } // required uint32 width = 3; public boolean hasWidth() { return result.hasWidth(); } public int getWidth() { return result.getWidth(); } public Builder setWidth(int value) { result.hasWidth = true; result.width_ = value; return this; } public Builder clearWidth() { result.hasWidth = false; result.width_ = 0; return this; } // required uint32 height = 4; public boolean hasHeight() { return result.hasHeight(); } public int getHeight() { return result.getHeight(); } public Builder setHeight(int value) { result.hasHeight = true; result.height_ = value; return this; } public Builder clearHeight() { result.hasHeight = false; result.height_ = 0; return this; } // @@protoc_insertion_point(builder_scope:scope.DesktopWindowRect) } static { defaultInstance = new DesktopWindowRect(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.DesktopWindowRect) } public static final class QuickMenuID extends com.google.protobuf.GeneratedMessage { // Use QuickMenuID.newBuilder() to construct. private QuickMenuID() { initFields(); } private QuickMenuID(boolean noInit) {} private static final QuickMenuID defaultInstance; public static QuickMenuID getDefaultInstance() { return defaultInstance; } public QuickMenuID getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuID_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuID_fieldAccessorTable; } // required string menuName = 1; public static final int MENUNAME_FIELD_NUMBER = 1; private boolean hasMenuName; private java.lang.String menuName_ = ""; public boolean hasMenuName() { return hasMenuName; } public java.lang.String getMenuName() { return menuName_; } private void initFields() { } public final boolean isInitialized() { if (!hasMenuName) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasMenuName()) { output.writeString(1, getMenuName()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasMenuName()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(1, getMenuName()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.getDefaultInstance()) return this; if (other.hasMenuName()) { setMenuName(other.getMenuName()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { setMenuName(input.readString()); break; } } } } // required string menuName = 1; public boolean hasMenuName() { return result.hasMenuName(); } public java.lang.String getMenuName() { return result.getMenuName(); } public Builder setMenuName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasMenuName = true; result.menuName_ = value; return this; } public Builder clearMenuName() { result.hasMenuName = false; result.menuName_ = getDefaultInstance().getMenuName(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickMenuID) } static { defaultInstance = new QuickMenuID(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickMenuID) } public static final class QuickMenuList extends com.google.protobuf.GeneratedMessage { // Use QuickMenuList.newBuilder() to construct. private QuickMenuList() { initFields(); } private QuickMenuList(boolean noInit) {} private static final QuickMenuList defaultInstance; public static QuickMenuList getDefaultInstance() { return defaultInstance; } public QuickMenuList getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuList_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuList_fieldAccessorTable; } // repeated .scope.QuickMenuInfo menuList = 1; public static final int MENULIST_FIELD_NUMBER = 1; private java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo> menuList_ = java.util.Collections.emptyList(); public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo> getMenuListList() { return menuList_; } public int getMenuListCount() { return menuList_.size(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo getMenuList(int index) { return menuList_.get(index); } private void initFields() { } public final boolean isInitialized() { for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo element : getMenuListList()) { if (!element.isInitialized()) return false; } return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo element : getMenuListList()) { output.writeMessage(1, element); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo element : getMenuListList()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, element); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } if (result.menuList_ != java.util.Collections.EMPTY_LIST) { result.menuList_ = java.util.Collections.unmodifiableList(result.menuList_); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList.getDefaultInstance()) return this; if (!other.menuList_.isEmpty()) { if (result.menuList_.isEmpty()) { result.menuList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo>(); } result.menuList_.addAll(other.menuList_); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addMenuList(subBuilder.buildPartial()); break; } } } } // repeated .scope.QuickMenuInfo menuList = 1; public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo> getMenuListList() { return java.util.Collections.unmodifiableList(result.menuList_); } public int getMenuListCount() { return result.getMenuListCount(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo getMenuList(int index) { return result.getMenuList(index); } public Builder setMenuList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo value) { if (value == null) { throw new NullPointerException(); } result.menuList_.set(index, value); return this; } public Builder setMenuList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.Builder builderForValue) { result.menuList_.set(index, builderForValue.build()); return this; } public Builder addMenuList(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo value) { if (value == null) { throw new NullPointerException(); } if (result.menuList_.isEmpty()) { result.menuList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo>(); } result.menuList_.add(value); return this; } public Builder addMenuList(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.Builder builderForValue) { if (result.menuList_.isEmpty()) { result.menuList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo>(); } result.menuList_.add(builderForValue.build()); return this; } public Builder addAllMenuList( java.lang.Iterable<? extends com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo> values) { if (result.menuList_.isEmpty()) { result.menuList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo>(); } super.addAll(values, result.menuList_); return this; } public Builder clearMenuList() { result.menuList_ = java.util.Collections.emptyList(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickMenuList) } static { defaultInstance = new QuickMenuList(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickMenuList) } public static final class QuickMenuInfo extends com.google.protobuf.GeneratedMessage { // Use QuickMenuInfo.newBuilder() to construct. private QuickMenuInfo() { initFields(); } private QuickMenuInfo(boolean noInit) {} private static final QuickMenuInfo defaultInstance; public static QuickMenuInfo getDefaultInstance() { return defaultInstance; } public QuickMenuInfo getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuInfo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuInfo_fieldAccessorTable; } // required .scope.QuickMenuID menuId = 1; public static final int MENUID_FIELD_NUMBER = 1; private boolean hasMenuId; private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID menuId_; public boolean hasMenuId() { return hasMenuId; } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID getMenuId() { return menuId_; } // required .scope.DesktopWindowRect rect = 2; public static final int RECT_FIELD_NUMBER = 2; private boolean hasRect; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect rect_; public boolean hasRect() { return hasRect; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return rect_; } // required .scope.DesktopWindowID windowId = 3; public static final int WINDOWID_FIELD_NUMBER = 3; private boolean hasWindowId; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID windowId_; public boolean hasWindowId() { return hasWindowId; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID getWindowId() { return windowId_; } // repeated .scope.QuickMenuItemInfo menuItemList = 4; public static final int MENUITEMLIST_FIELD_NUMBER = 4; private java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo> menuItemList_ = java.util.Collections.emptyList(); public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo> getMenuItemListList() { return menuItemList_; } public int getMenuItemListCount() { return menuItemList_.size(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo getMenuItemList(int index) { return menuItemList_.get(index); } private void initFields() { menuId_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.getDefaultInstance(); rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); windowId_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance(); } public final boolean isInitialized() { if (!hasMenuId) return false; if (!hasRect) return false; if (!hasWindowId) return false; if (!getMenuId().isInitialized()) return false; if (!getRect().isInitialized()) return false; if (!getWindowId().isInitialized()) return false; for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo element : getMenuItemListList()) { if (!element.isInitialized()) return false; } return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasMenuId()) { output.writeMessage(1, getMenuId()); } if (hasRect()) { output.writeMessage(2, getRect()); } if (hasWindowId()) { output.writeMessage(3, getWindowId()); } for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo element : getMenuItemListList()) { output.writeMessage(4, element); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasMenuId()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getMenuId()); } if (hasRect()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getRect()); } if (hasWindowId()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, getWindowId()); } for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo element : getMenuItemListList()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, element); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } if (result.menuItemList_ != java.util.Collections.EMPTY_LIST) { result.menuItemList_ = java.util.Collections.unmodifiableList(result.menuItemList_); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.getDefaultInstance()) return this; if (other.hasMenuId()) { mergeMenuId(other.getMenuId()); } if (other.hasRect()) { mergeRect(other.getRect()); } if (other.hasWindowId()) { mergeWindowId(other.getWindowId()); } if (!other.menuItemList_.isEmpty()) { if (result.menuItemList_.isEmpty()) { result.menuItemList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo>(); } result.menuItemList_.addAll(other.menuItemList_); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.newBuilder(); if (hasMenuId()) { subBuilder.mergeFrom(getMenuId()); } input.readMessage(subBuilder, extensionRegistry); setMenuId(subBuilder.buildPartial()); break; } case 18: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(); if (hasRect()) { subBuilder.mergeFrom(getRect()); } input.readMessage(subBuilder, extensionRegistry); setRect(subBuilder.buildPartial()); break; } case 26: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.newBuilder(); if (hasWindowId()) { subBuilder.mergeFrom(getWindowId()); } input.readMessage(subBuilder, extensionRegistry); setWindowId(subBuilder.buildPartial()); break; } case 34: { com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addMenuItemList(subBuilder.buildPartial()); break; } } } } // required .scope.QuickMenuID menuId = 1; public boolean hasMenuId() { return result.hasMenuId(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID getMenuId() { return result.getMenuId(); } public Builder setMenuId(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID value) { if (value == null) { throw new NullPointerException(); } result.hasMenuId = true; result.menuId_ = value; return this; } public Builder setMenuId(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.Builder builderForValue) { result.hasMenuId = true; result.menuId_ = builderForValue.build(); return this; } public Builder mergeMenuId(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID value) { if (result.hasMenuId() && result.menuId_ != com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.getDefaultInstance()) { result.menuId_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.newBuilder(result.menuId_).mergeFrom(value).buildPartial(); } else { result.menuId_ = value; } result.hasMenuId = true; return this; } public Builder clearMenuId() { result.hasMenuId = false; result.menuId_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.getDefaultInstance(); return this; } // required .scope.DesktopWindowRect rect = 2; public boolean hasRect() { return result.hasRect(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return result.getRect(); } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (value == null) { throw new NullPointerException(); } result.hasRect = true; result.rect_ = value; return this; } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder builderForValue) { result.hasRect = true; result.rect_ = builderForValue.build(); return this; } public Builder mergeRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (result.hasRect() && result.rect_ != com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance()) { result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(result.rect_).mergeFrom(value).buildPartial(); } else { result.rect_ = value; } result.hasRect = true; return this; } public Builder clearRect() { result.hasRect = false; result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); return this; } // required .scope.DesktopWindowID windowId = 3; public boolean hasWindowId() { return result.hasWindowId(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID getWindowId() { return result.getWindowId(); } public Builder setWindowId(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID value) { if (value == null) { throw new NullPointerException(); } result.hasWindowId = true; result.windowId_ = value; return this; } public Builder setWindowId(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.Builder builderForValue) { result.hasWindowId = true; result.windowId_ = builderForValue.build(); return this; } public Builder mergeWindowId(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID value) { if (result.hasWindowId() && result.windowId_ != com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance()) { result.windowId_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.newBuilder(result.windowId_).mergeFrom(value).buildPartial(); } else { result.windowId_ = value; } result.hasWindowId = true; return this; } public Builder clearWindowId() { result.hasWindowId = false; result.windowId_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance(); return this; } // repeated .scope.QuickMenuItemInfo menuItemList = 4; public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo> getMenuItemListList() { return java.util.Collections.unmodifiableList(result.menuItemList_); } public int getMenuItemListCount() { return result.getMenuItemListCount(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo getMenuItemList(int index) { return result.getMenuItemList(index); } public Builder setMenuItemList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo value) { if (value == null) { throw new NullPointerException(); } result.menuItemList_.set(index, value); return this; } public Builder setMenuItemList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.Builder builderForValue) { result.menuItemList_.set(index, builderForValue.build()); return this; } public Builder addMenuItemList(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo value) { if (value == null) { throw new NullPointerException(); } if (result.menuItemList_.isEmpty()) { result.menuItemList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo>(); } result.menuItemList_.add(value); return this; } public Builder addMenuItemList(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.Builder builderForValue) { if (result.menuItemList_.isEmpty()) { result.menuItemList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo>(); } result.menuItemList_.add(builderForValue.build()); return this; } public Builder addAllMenuItemList( java.lang.Iterable<? extends com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo> values) { if (result.menuItemList_.isEmpty()) { result.menuItemList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo>(); } super.addAll(values, result.menuItemList_); return this; } public Builder clearMenuItemList() { result.menuItemList_ = java.util.Collections.emptyList(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickMenuInfo) } static { defaultInstance = new QuickMenuInfo(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickMenuInfo) } public static final class QuickMenuItemID extends com.google.protobuf.GeneratedMessage { // Use QuickMenuItemID.newBuilder() to construct. private QuickMenuItemID() { initFields(); } private QuickMenuItemID(boolean noInit) {} private static final QuickMenuItemID defaultInstance; public static QuickMenuItemID getDefaultInstance() { return defaultInstance; } public QuickMenuItemID getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuItemID_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuItemID_fieldAccessorTable; } // required string menuText = 1; public static final int MENUTEXT_FIELD_NUMBER = 1; private boolean hasMenuText; private java.lang.String menuText_ = ""; public boolean hasMenuText() { return hasMenuText; } public java.lang.String getMenuText() { return menuText_; } private void initFields() { } public final boolean isInitialized() { if (!hasMenuText) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasMenuText()) { output.writeString(1, getMenuText()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasMenuText()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(1, getMenuText()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID.getDefaultInstance()) return this; if (other.hasMenuText()) { setMenuText(other.getMenuText()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { setMenuText(input.readString()); break; } } } } // required string menuText = 1; public boolean hasMenuText() { return result.hasMenuText(); } public java.lang.String getMenuText() { return result.getMenuText(); } public Builder setMenuText(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasMenuText = true; result.menuText_ = value; return this; } public Builder clearMenuText() { result.hasMenuText = false; result.menuText_ = getDefaultInstance().getMenuText(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickMenuItemID) } static { defaultInstance = new QuickMenuItemID(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickMenuItemID) } public static final class QuickMenuItemInfo extends com.google.protobuf.GeneratedMessage { // Use QuickMenuItemInfo.newBuilder() to construct. private QuickMenuItemInfo() { initFields(); } private QuickMenuItemInfo(boolean noInit) {} private static final QuickMenuItemInfo defaultInstance; public static QuickMenuItemInfo getDefaultInstance() { return defaultInstance; } public QuickMenuItemInfo getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuItemInfo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickMenuItemInfo_fieldAccessorTable; } // required string text = 1; public static final int TEXT_FIELD_NUMBER = 1; private boolean hasText; private java.lang.String text_ = ""; public boolean hasText() { return hasText; } public java.lang.String getText() { return text_; } // optional string action = 2; public static final int ACTION_FIELD_NUMBER = 2; private boolean hasAction; private java.lang.String action_ = ""; public boolean hasAction() { return hasAction; } public java.lang.String getAction() { return action_; } // optional string submenu = 3; public static final int SUBMENU_FIELD_NUMBER = 3; private boolean hasSubmenu; private java.lang.String submenu_ = ""; public boolean hasSubmenu() { return hasSubmenu; } public java.lang.String getSubmenu() { return submenu_; } // optional string action_param = 4; public static final int ACTION_PARAM_FIELD_NUMBER = 4; private boolean hasActionParam; private java.lang.String actionParam_ = ""; public boolean hasActionParam() { return hasActionParam; } public java.lang.String getActionParam() { return actionParam_; } // required uint32 row = 5; public static final int ROW_FIELD_NUMBER = 5; private boolean hasRow; private int row_ = 0; public boolean hasRow() { return hasRow; } public int getRow() { return row_; } // optional string shortcutletter = 6; public static final int SHORTCUTLETTER_FIELD_NUMBER = 6; private boolean hasShortcutletter; private java.lang.String shortcutletter_ = ""; public boolean hasShortcutletter() { return hasShortcutletter; } public java.lang.String getShortcutletter() { return shortcutletter_; } // optional string shortcut = 7; public static final int SHORTCUT_FIELD_NUMBER = 7; private boolean hasShortcut; private java.lang.String shortcut_ = ""; public boolean hasShortcut() { return hasShortcut; } public java.lang.String getShortcut() { return shortcut_; } // required .scope.DesktopWindowRect rect = 8; public static final int RECT_FIELD_NUMBER = 8; private boolean hasRect; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect rect_; public boolean hasRect() { return hasRect; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return rect_; } // required bool enabled = 9; public static final int ENABLED_FIELD_NUMBER = 9; private boolean hasEnabled; private boolean enabled_ = false; public boolean hasEnabled() { return hasEnabled; } public boolean getEnabled() { return enabled_; } // required bool checked = 10; public static final int CHECKED_FIELD_NUMBER = 10; private boolean hasChecked; private boolean checked_ = false; public boolean hasChecked() { return hasChecked; } public boolean getChecked() { return checked_; } // required bool selected = 11; public static final int SELECTED_FIELD_NUMBER = 11; private boolean hasSelected; private boolean selected_ = false; public boolean hasSelected() { return hasSelected; } public boolean getSelected() { return selected_; } // required bool bold = 12; public static final int BOLD_FIELD_NUMBER = 12; private boolean hasBold; private boolean bold_ = false; public boolean hasBold() { return hasBold; } public boolean getBold() { return bold_; } // required bool separator = 13; public static final int SEPARATOR_FIELD_NUMBER = 13; private boolean hasSeparator; private boolean separator_ = false; public boolean hasSeparator() { return hasSeparator; } public boolean getSeparator() { return separator_; } private void initFields() { rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); } public final boolean isInitialized() { if (!hasText) return false; if (!hasRow) return false; if (!hasRect) return false; if (!hasEnabled) return false; if (!hasChecked) return false; if (!hasSelected) return false; if (!hasBold) return false; if (!hasSeparator) return false; if (!getRect().isInitialized()) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasText()) { output.writeString(1, getText()); } if (hasAction()) { output.writeString(2, getAction()); } if (hasSubmenu()) { output.writeString(3, getSubmenu()); } if (hasActionParam()) { output.writeString(4, getActionParam()); } if (hasRow()) { output.writeUInt32(5, getRow()); } if (hasShortcutletter()) { output.writeString(6, getShortcutletter()); } if (hasShortcut()) { output.writeString(7, getShortcut()); } if (hasRect()) { output.writeMessage(8, getRect()); } if (hasEnabled()) { output.writeBool(9, getEnabled()); } if (hasChecked()) { output.writeBool(10, getChecked()); } if (hasSelected()) { output.writeBool(11, getSelected()); } if (hasBold()) { output.writeBool(12, getBold()); } if (hasSeparator()) { output.writeBool(13, getSeparator()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasText()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(1, getText()); } if (hasAction()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(2, getAction()); } if (hasSubmenu()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(3, getSubmenu()); } if (hasActionParam()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(4, getActionParam()); } if (hasRow()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(5, getRow()); } if (hasShortcutletter()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(6, getShortcutletter()); } if (hasShortcut()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(7, getShortcut()); } if (hasRect()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, getRect()); } if (hasEnabled()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(9, getEnabled()); } if (hasChecked()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(10, getChecked()); } if (hasSelected()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(11, getSelected()); } if (hasBold()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(12, getBold()); } if (hasSeparator()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(13, getSeparator()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.getDefaultInstance()) return this; if (other.hasText()) { setText(other.getText()); } if (other.hasAction()) { setAction(other.getAction()); } if (other.hasSubmenu()) { setSubmenu(other.getSubmenu()); } if (other.hasActionParam()) { setActionParam(other.getActionParam()); } if (other.hasRow()) { setRow(other.getRow()); } if (other.hasShortcutletter()) { setShortcutletter(other.getShortcutletter()); } if (other.hasShortcut()) { setShortcut(other.getShortcut()); } if (other.hasRect()) { mergeRect(other.getRect()); } if (other.hasEnabled()) { setEnabled(other.getEnabled()); } if (other.hasChecked()) { setChecked(other.getChecked()); } if (other.hasSelected()) { setSelected(other.getSelected()); } if (other.hasBold()) { setBold(other.getBold()); } if (other.hasSeparator()) { setSeparator(other.getSeparator()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { setText(input.readString()); break; } case 18: { setAction(input.readString()); break; } case 26: { setSubmenu(input.readString()); break; } case 34: { setActionParam(input.readString()); break; } case 40: { setRow(input.readUInt32()); break; } case 50: { setShortcutletter(input.readString()); break; } case 58: { setShortcut(input.readString()); break; } case 66: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(); if (hasRect()) { subBuilder.mergeFrom(getRect()); } input.readMessage(subBuilder, extensionRegistry); setRect(subBuilder.buildPartial()); break; } case 72: { setEnabled(input.readBool()); break; } case 80: { setChecked(input.readBool()); break; } case 88: { setSelected(input.readBool()); break; } case 96: { setBold(input.readBool()); break; } case 104: { setSeparator(input.readBool()); break; } } } } // required string text = 1; public boolean hasText() { return result.hasText(); } public java.lang.String getText() { return result.getText(); } public Builder setText(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasText = true; result.text_ = value; return this; } public Builder clearText() { result.hasText = false; result.text_ = getDefaultInstance().getText(); return this; } // optional string action = 2; public boolean hasAction() { return result.hasAction(); } public java.lang.String getAction() { return result.getAction(); } public Builder setAction(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasAction = true; result.action_ = value; return this; } public Builder clearAction() { result.hasAction = false; result.action_ = getDefaultInstance().getAction(); return this; } // optional string submenu = 3; public boolean hasSubmenu() { return result.hasSubmenu(); } public java.lang.String getSubmenu() { return result.getSubmenu(); } public Builder setSubmenu(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasSubmenu = true; result.submenu_ = value; return this; } public Builder clearSubmenu() { result.hasSubmenu = false; result.submenu_ = getDefaultInstance().getSubmenu(); return this; } // optional string action_param = 4; public boolean hasActionParam() { return result.hasActionParam(); } public java.lang.String getActionParam() { return result.getActionParam(); } public Builder setActionParam(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasActionParam = true; result.actionParam_ = value; return this; } public Builder clearActionParam() { result.hasActionParam = false; result.actionParam_ = getDefaultInstance().getActionParam(); return this; } // required uint32 row = 5; public boolean hasRow() { return result.hasRow(); } public int getRow() { return result.getRow(); } public Builder setRow(int value) { result.hasRow = true; result.row_ = value; return this; } public Builder clearRow() { result.hasRow = false; result.row_ = 0; return this; } // optional string shortcutletter = 6; public boolean hasShortcutletter() { return result.hasShortcutletter(); } public java.lang.String getShortcutletter() { return result.getShortcutletter(); } public Builder setShortcutletter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasShortcutletter = true; result.shortcutletter_ = value; return this; } public Builder clearShortcutletter() { result.hasShortcutletter = false; result.shortcutletter_ = getDefaultInstance().getShortcutletter(); return this; } // optional string shortcut = 7; public boolean hasShortcut() { return result.hasShortcut(); } public java.lang.String getShortcut() { return result.getShortcut(); } public Builder setShortcut(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasShortcut = true; result.shortcut_ = value; return this; } public Builder clearShortcut() { result.hasShortcut = false; result.shortcut_ = getDefaultInstance().getShortcut(); return this; } // required .scope.DesktopWindowRect rect = 8; public boolean hasRect() { return result.hasRect(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return result.getRect(); } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (value == null) { throw new NullPointerException(); } result.hasRect = true; result.rect_ = value; return this; } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder builderForValue) { result.hasRect = true; result.rect_ = builderForValue.build(); return this; } public Builder mergeRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (result.hasRect() && result.rect_ != com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance()) { result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(result.rect_).mergeFrom(value).buildPartial(); } else { result.rect_ = value; } result.hasRect = true; return this; } public Builder clearRect() { result.hasRect = false; result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); return this; } // required bool enabled = 9; public boolean hasEnabled() { return result.hasEnabled(); } public boolean getEnabled() { return result.getEnabled(); } public Builder setEnabled(boolean value) { result.hasEnabled = true; result.enabled_ = value; return this; } public Builder clearEnabled() { result.hasEnabled = false; result.enabled_ = false; return this; } // required bool checked = 10; public boolean hasChecked() { return result.hasChecked(); } public boolean getChecked() { return result.getChecked(); } public Builder setChecked(boolean value) { result.hasChecked = true; result.checked_ = value; return this; } public Builder clearChecked() { result.hasChecked = false; result.checked_ = false; return this; } // required bool selected = 11; public boolean hasSelected() { return result.hasSelected(); } public boolean getSelected() { return result.getSelected(); } public Builder setSelected(boolean value) { result.hasSelected = true; result.selected_ = value; return this; } public Builder clearSelected() { result.hasSelected = false; result.selected_ = false; return this; } // required bool bold = 12; public boolean hasBold() { return result.hasBold(); } public boolean getBold() { return result.getBold(); } public Builder setBold(boolean value) { result.hasBold = true; result.bold_ = value; return this; } public Builder clearBold() { result.hasBold = false; result.bold_ = false; return this; } // required bool separator = 13; public boolean hasSeparator() { return result.hasSeparator(); } public boolean getSeparator() { return result.getSeparator(); } public Builder setSeparator(boolean value) { result.hasSeparator = true; result.separator_ = value; return this; } public Builder clearSeparator() { result.hasSeparator = false; result.separator_ = false; return this; } // @@protoc_insertion_point(builder_scope:scope.QuickMenuItemInfo) } static { defaultInstance = new QuickMenuItemInfo(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickMenuItemInfo) } public static final class QuickWidgetInfo extends com.google.protobuf.GeneratedMessage { // Use QuickWidgetInfo.newBuilder() to construct. private QuickWidgetInfo() { initFields(); } private QuickWidgetInfo(boolean noInit) {} private static final QuickWidgetInfo defaultInstance; public static QuickWidgetInfo getDefaultInstance() { return defaultInstance; } public QuickWidgetInfo getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickWidgetInfo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickWidgetInfo_fieldAccessorTable; } public enum QuickWidgetType implements com.google.protobuf.ProtocolMessageEnum { UNKNOWN(0, 0), BUTTON(1, 1), CHECKBOX(2, 2), DIALOGTAB(3, 3), DROPDOWN(4, 4), DROPDOWNITEM(5, 5), EDITFIELD(6, 6), LABEL(7, 7), RADIOBUTTON(8, 8), ADDRESSFIELD(9, 9), SEARCH(10, 10), TOOLBAR(11, 11), TREEVIEW(12, 12), TREEITEM(13, 13), TABBUTTON(14, 14), THUMBNAIL(15, 15), GRIDLAYOUT(16, 16), GRIDITEM(17, 17), QUICKFIND(18, 18), ; public final int getNumber() { return value; } public static QuickWidgetType valueOf(int value) { switch (value) { case 0: return UNKNOWN; case 1: return BUTTON; case 2: return CHECKBOX; case 3: return DIALOGTAB; case 4: return DROPDOWN; case 5: return DROPDOWNITEM; case 6: return EDITFIELD; case 7: return LABEL; case 8: return RADIOBUTTON; case 9: return ADDRESSFIELD; case 10: return SEARCH; case 11: return TOOLBAR; case 12: return TREEVIEW; case 13: return TREEITEM; case 14: return TABBUTTON; case 15: return THUMBNAIL; case 16: return GRIDLAYOUT; case 17: return GRIDITEM; case 18: return QUICKFIND; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<QuickWidgetType> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<QuickWidgetType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<QuickWidgetType>() { public QuickWidgetType findValueByNumber(int number) { return QuickWidgetType.valueOf(number) ; } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.getDescriptor().getEnumTypes().get(0); } private static final QuickWidgetType[] VALUES = { UNKNOWN, BUTTON, CHECKBOX, DIALOGTAB, DROPDOWN, DROPDOWNITEM, EDITFIELD, LABEL, RADIOBUTTON, ADDRESSFIELD, SEARCH, TOOLBAR, TREEVIEW, TREEITEM, TABBUTTON, THUMBNAIL, GRIDLAYOUT, GRIDITEM, QUICKFIND, }; public static QuickWidgetType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private QuickWidgetType(int index, int value) { this.index = index; this.value = value; } static { com.opera.core.systems.scope.protos.DesktopWmProtos.getDescriptor(); } // @@protoc_insertion_point(enum_scope:scope.QuickWidgetInfo.QuickWidgetType) } // required string name = 1; public static final int NAME_FIELD_NUMBER = 1; private boolean hasName; private java.lang.String name_ = ""; public boolean hasName() { return hasName; } public java.lang.String getName() { return name_; } // required .scope.QuickWidgetInfo.QuickWidgetType type = 2; public static final int TYPE_FIELD_NUMBER = 2; private boolean hasType; private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType type_; public boolean hasType() { return hasType; } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType getType() { return type_; } // required bool visible = 3; public static final int VISIBLE_FIELD_NUMBER = 3; private boolean hasVisible; private boolean visible_ = false; public boolean hasVisible() { return hasVisible; } public boolean getVisible() { return visible_; } // required string text = 4; public static final int TEXT_FIELD_NUMBER = 4; private boolean hasText; private java.lang.String text_ = ""; public boolean hasText() { return hasText; } public java.lang.String getText() { return text_; } // required uint32 value = 5; public static final int VALUE_FIELD_NUMBER = 5; private boolean hasValue; private int value_ = 0; public boolean hasValue() { return hasValue; } public int getValue() { return value_; } // required bool enabled = 6; public static final int ENABLED_FIELD_NUMBER = 6; private boolean hasEnabled; private boolean enabled_ = false; public boolean hasEnabled() { return hasEnabled; } public boolean getEnabled() { return enabled_; } // required bool defaultLook = 7; public static final int DEFAULTLOOK_FIELD_NUMBER = 7; private boolean hasDefaultLook; private boolean defaultLook_ = false; public boolean hasDefaultLook() { return hasDefaultLook; } public boolean getDefaultLook() { return defaultLook_; } // required bool focusedLook = 8; public static final int FOCUSEDLOOK_FIELD_NUMBER = 8; private boolean hasFocusedLook; private boolean focusedLook_ = false; public boolean hasFocusedLook() { return hasFocusedLook; } public boolean getFocusedLook() { return focusedLook_; } // required .scope.DesktopWindowRect rect = 9; public static final int RECT_FIELD_NUMBER = 9; private boolean hasRect; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect rect_; public boolean hasRect() { return hasRect; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return rect_; } // optional string parent = 10; public static final int PARENT_FIELD_NUMBER = 10; private boolean hasParent; private java.lang.String parent_ = ""; public boolean hasParent() { return hasParent; } public java.lang.String getParent() { return parent_; } // optional uint32 row = 11; public static final int ROW_FIELD_NUMBER = 11; private boolean hasRow; private int row_ = 0; public boolean hasRow() { return hasRow; } public int getRow() { return row_; } // optional uint32 col = 12; public static final int COL_FIELD_NUMBER = 12; private boolean hasCol; private int col_ = 0; public boolean hasCol() { return hasCol; } public int getCol() { return col_; } // optional string visible_text = 13; public static final int VISIBLE_TEXT_FIELD_NUMBER = 13; private boolean hasVisibleText; private java.lang.String visibleText_ = ""; public boolean hasVisibleText() { return hasVisibleText; } public java.lang.String getVisibleText() { return visibleText_; } // optional string additional_text = 14; public static final int ADDITIONAL_TEXT_FIELD_NUMBER = 14; private boolean hasAdditionalText; private java.lang.String additionalText_ = ""; public boolean hasAdditionalText() { return hasAdditionalText; } public java.lang.String getAdditionalText() { return additionalText_; } private void initFields() { type_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType.UNKNOWN; rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); } public final boolean isInitialized() { if (!hasName) return false; if (!hasType) return false; if (!hasVisible) return false; if (!hasText) return false; if (!hasValue) return false; if (!hasEnabled) return false; if (!hasDefaultLook) return false; if (!hasFocusedLook) return false; if (!hasRect) return false; if (!getRect().isInitialized()) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasName()) { output.writeString(1, getName()); } if (hasType()) { output.writeEnum(2, getType().getNumber()); } if (hasVisible()) { output.writeBool(3, getVisible()); } if (hasText()) { output.writeString(4, getText()); } if (hasValue()) { output.writeUInt32(5, getValue()); } if (hasEnabled()) { output.writeBool(6, getEnabled()); } if (hasDefaultLook()) { output.writeBool(7, getDefaultLook()); } if (hasFocusedLook()) { output.writeBool(8, getFocusedLook()); } if (hasRect()) { output.writeMessage(9, getRect()); } if (hasParent()) { output.writeString(10, getParent()); } if (hasRow()) { output.writeUInt32(11, getRow()); } if (hasCol()) { output.writeUInt32(12, getCol()); } if (hasVisibleText()) { output.writeString(13, getVisibleText()); } if (hasAdditionalText()) { output.writeString(14, getAdditionalText()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasName()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(1, getName()); } if (hasType()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, getType().getNumber()); } if (hasVisible()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, getVisible()); } if (hasText()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(4, getText()); } if (hasValue()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(5, getValue()); } if (hasEnabled()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(6, getEnabled()); } if (hasDefaultLook()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(7, getDefaultLook()); } if (hasFocusedLook()) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(8, getFocusedLook()); } if (hasRect()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(9, getRect()); } if (hasParent()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(10, getParent()); } if (hasRow()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(11, getRow()); } if (hasCol()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(12, getCol()); } if (hasVisibleText()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(13, getVisibleText()); } if (hasAdditionalText()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(14, getAdditionalText()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.getDefaultInstance()) return this; if (other.hasName()) { setName(other.getName()); } if (other.hasType()) { setType(other.getType()); } if (other.hasVisible()) { setVisible(other.getVisible()); } if (other.hasText()) { setText(other.getText()); } if (other.hasValue()) { setValue(other.getValue()); } if (other.hasEnabled()) { setEnabled(other.getEnabled()); } if (other.hasDefaultLook()) { setDefaultLook(other.getDefaultLook()); } if (other.hasFocusedLook()) { setFocusedLook(other.getFocusedLook()); } if (other.hasRect()) { mergeRect(other.getRect()); } if (other.hasParent()) { setParent(other.getParent()); } if (other.hasRow()) { setRow(other.getRow()); } if (other.hasCol()) { setCol(other.getCol()); } if (other.hasVisibleText()) { setVisibleText(other.getVisibleText()); } if (other.hasAdditionalText()) { setAdditionalText(other.getAdditionalText()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { setName(input.readString()); break; } case 16: { int rawValue = input.readEnum(); com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType value = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { setType(value); } break; } case 24: { setVisible(input.readBool()); break; } case 34: { setText(input.readString()); break; } case 40: { setValue(input.readUInt32()); break; } case 48: { setEnabled(input.readBool()); break; } case 56: { setDefaultLook(input.readBool()); break; } case 64: { setFocusedLook(input.readBool()); break; } case 74: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(); if (hasRect()) { subBuilder.mergeFrom(getRect()); } input.readMessage(subBuilder, extensionRegistry); setRect(subBuilder.buildPartial()); break; } case 82: { setParent(input.readString()); break; } case 88: { setRow(input.readUInt32()); break; } case 96: { setCol(input.readUInt32()); break; } case 106: { setVisibleText(input.readString()); break; } case 114: { setAdditionalText(input.readString()); break; } } } } // required string name = 1; public boolean hasName() { return result.hasName(); } public java.lang.String getName() { return result.getName(); } public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasName = true; result.name_ = value; return this; } public Builder clearName() { result.hasName = false; result.name_ = getDefaultInstance().getName(); return this; } // required .scope.QuickWidgetInfo.QuickWidgetType type = 2; public boolean hasType() { return result.hasType(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType getType() { return result.getType(); } public Builder setType(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType value) { if (value == null) { throw new NullPointerException(); } result.hasType = true; result.type_ = value; return this; } public Builder clearType() { result.hasType = false; result.type_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType.UNKNOWN; return this; } // required bool visible = 3; public boolean hasVisible() { return result.hasVisible(); } public boolean getVisible() { return result.getVisible(); } public Builder setVisible(boolean value) { result.hasVisible = true; result.visible_ = value; return this; } public Builder clearVisible() { result.hasVisible = false; result.visible_ = false; return this; } // required string text = 4; public boolean hasText() { return result.hasText(); } public java.lang.String getText() { return result.getText(); } public Builder setText(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasText = true; result.text_ = value; return this; } public Builder clearText() { result.hasText = false; result.text_ = getDefaultInstance().getText(); return this; } // required uint32 value = 5; public boolean hasValue() { return result.hasValue(); } public int getValue() { return result.getValue(); } public Builder setValue(int value) { result.hasValue = true; result.value_ = value; return this; } public Builder clearValue() { result.hasValue = false; result.value_ = 0; return this; } // required bool enabled = 6; public boolean hasEnabled() { return result.hasEnabled(); } public boolean getEnabled() { return result.getEnabled(); } public Builder setEnabled(boolean value) { result.hasEnabled = true; result.enabled_ = value; return this; } public Builder clearEnabled() { result.hasEnabled = false; result.enabled_ = false; return this; } // required bool defaultLook = 7; public boolean hasDefaultLook() { return result.hasDefaultLook(); } public boolean getDefaultLook() { return result.getDefaultLook(); } public Builder setDefaultLook(boolean value) { result.hasDefaultLook = true; result.defaultLook_ = value; return this; } public Builder clearDefaultLook() { result.hasDefaultLook = false; result.defaultLook_ = false; return this; } // required bool focusedLook = 8; public boolean hasFocusedLook() { return result.hasFocusedLook(); } public boolean getFocusedLook() { return result.getFocusedLook(); } public Builder setFocusedLook(boolean value) { result.hasFocusedLook = true; result.focusedLook_ = value; return this; } public Builder clearFocusedLook() { result.hasFocusedLook = false; result.focusedLook_ = false; return this; } // required .scope.DesktopWindowRect rect = 9; public boolean hasRect() { return result.hasRect(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect getRect() { return result.getRect(); } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (value == null) { throw new NullPointerException(); } result.hasRect = true; result.rect_ = value; return this; } public Builder setRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder builderForValue) { result.hasRect = true; result.rect_ = builderForValue.build(); return this; } public Builder mergeRect(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect value) { if (result.hasRect() && result.rect_ != com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance()) { result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.newBuilder(result.rect_).mergeFrom(value).buildPartial(); } else { result.rect_ = value; } result.hasRect = true; return this; } public Builder clearRect() { result.hasRect = false; result.rect_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.getDefaultInstance(); return this; } // optional string parent = 10; public boolean hasParent() { return result.hasParent(); } public java.lang.String getParent() { return result.getParent(); } public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasParent = true; result.parent_ = value; return this; } public Builder clearParent() { result.hasParent = false; result.parent_ = getDefaultInstance().getParent(); return this; } // optional uint32 row = 11; public boolean hasRow() { return result.hasRow(); } public int getRow() { return result.getRow(); } public Builder setRow(int value) { result.hasRow = true; result.row_ = value; return this; } public Builder clearRow() { result.hasRow = false; result.row_ = 0; return this; } // optional uint32 col = 12; public boolean hasCol() { return result.hasCol(); } public int getCol() { return result.getCol(); } public Builder setCol(int value) { result.hasCol = true; result.col_ = value; return this; } public Builder clearCol() { result.hasCol = false; result.col_ = 0; return this; } // optional string visible_text = 13; public boolean hasVisibleText() { return result.hasVisibleText(); } public java.lang.String getVisibleText() { return result.getVisibleText(); } public Builder setVisibleText(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasVisibleText = true; result.visibleText_ = value; return this; } public Builder clearVisibleText() { result.hasVisibleText = false; result.visibleText_ = getDefaultInstance().getVisibleText(); return this; } // optional string additional_text = 14; public boolean hasAdditionalText() { return result.hasAdditionalText(); } public java.lang.String getAdditionalText() { return result.getAdditionalText(); } public Builder setAdditionalText(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasAdditionalText = true; result.additionalText_ = value; return this; } public Builder clearAdditionalText() { result.hasAdditionalText = false; result.additionalText_ = getDefaultInstance().getAdditionalText(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickWidgetInfo) } static { defaultInstance = new QuickWidgetInfo(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickWidgetInfo) } public static final class DesktopWindowID extends com.google.protobuf.GeneratedMessage { // Use DesktopWindowID.newBuilder() to construct. private DesktopWindowID() { initFields(); } private DesktopWindowID(boolean noInit) {} private static final DesktopWindowID defaultInstance; public static DesktopWindowID getDefaultInstance() { return defaultInstance; } public DesktopWindowID getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowID_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowID_fieldAccessorTable; } // required uint32 windowID = 1; public static final int WINDOWID_FIELD_NUMBER = 1; private boolean hasWindowID; private int windowID_ = 0; public boolean hasWindowID() { return hasWindowID; } public int getWindowID() { return windowID_; } private void initFields() { } public final boolean isInitialized() { if (!hasWindowID) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasWindowID()) { output.writeUInt32(1, getWindowID()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasWindowID()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, getWindowID()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance()) return this; if (other.hasWindowID()) { setWindowID(other.getWindowID()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 8: { setWindowID(input.readUInt32()); break; } } } } // required uint32 windowID = 1; public boolean hasWindowID() { return result.hasWindowID(); } public int getWindowID() { return result.getWindowID(); } public Builder setWindowID(int value) { result.hasWindowID = true; result.windowID_ = value; return this; } public Builder clearWindowID() { result.hasWindowID = false; result.windowID_ = 0; return this; } // @@protoc_insertion_point(builder_scope:scope.DesktopWindowID) } static { defaultInstance = new DesktopWindowID(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.DesktopWindowID) } public static final class DesktopWindowList extends com.google.protobuf.GeneratedMessage { // Use DesktopWindowList.newBuilder() to construct. private DesktopWindowList() { initFields(); } private DesktopWindowList(boolean noInit) {} private static final DesktopWindowList defaultInstance; public static DesktopWindowList getDefaultInstance() { return defaultInstance; } public DesktopWindowList getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowList_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_DesktopWindowList_fieldAccessorTable; } // repeated .scope.DesktopWindowInfo windowList = 1; public static final int WINDOWLIST_FIELD_NUMBER = 1; private java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo> windowList_ = java.util.Collections.emptyList(); public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo> getWindowListList() { return windowList_; } public int getWindowListCount() { return windowList_.size(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo getWindowList(int index) { return windowList_.get(index); } private void initFields() { } public final boolean isInitialized() { for (com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo element : getWindowListList()) { if (!element.isInitialized()) return false; } return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo element : getWindowListList()) { output.writeMessage(1, element); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo element : getWindowListList()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, element); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } if (result.windowList_ != java.util.Collections.EMPTY_LIST) { result.windowList_ = java.util.Collections.unmodifiableList(result.windowList_); } com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList.getDefaultInstance()) return this; if (!other.windowList_.isEmpty()) { if (result.windowList_.isEmpty()) { result.windowList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo>(); } result.windowList_.addAll(other.windowList_); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addWindowList(subBuilder.buildPartial()); break; } } } } // repeated .scope.DesktopWindowInfo windowList = 1; public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo> getWindowListList() { return java.util.Collections.unmodifiableList(result.windowList_); } public int getWindowListCount() { return result.getWindowListCount(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo getWindowList(int index) { return result.getWindowList(index); } public Builder setWindowList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo value) { if (value == null) { throw new NullPointerException(); } result.windowList_.set(index, value); return this; } public Builder setWindowList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.Builder builderForValue) { result.windowList_.set(index, builderForValue.build()); return this; } public Builder addWindowList(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo value) { if (value == null) { throw new NullPointerException(); } if (result.windowList_.isEmpty()) { result.windowList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo>(); } result.windowList_.add(value); return this; } public Builder addWindowList(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.Builder builderForValue) { if (result.windowList_.isEmpty()) { result.windowList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo>(); } result.windowList_.add(builderForValue.build()); return this; } public Builder addAllWindowList( java.lang.Iterable<? extends com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo> values) { if (result.windowList_.isEmpty()) { result.windowList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo>(); } super.addAll(values, result.windowList_); return this; } public Builder clearWindowList() { result.windowList_ = java.util.Collections.emptyList(); return this; } // @@protoc_insertion_point(builder_scope:scope.DesktopWindowList) } static { defaultInstance = new DesktopWindowList(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.DesktopWindowList) } public static final class QuickWidgetInfoList extends com.google.protobuf.GeneratedMessage { // Use QuickWidgetInfoList.newBuilder() to construct. private QuickWidgetInfoList() { initFields(); } private QuickWidgetInfoList(boolean noInit) {} private static final QuickWidgetInfoList defaultInstance; public static QuickWidgetInfoList getDefaultInstance() { return defaultInstance; } public QuickWidgetInfoList getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickWidgetInfoList_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickWidgetInfoList_fieldAccessorTable; } // repeated .scope.QuickWidgetInfo quickwidgetList = 1; public static final int QUICKWIDGETLIST_FIELD_NUMBER = 1; private java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo> quickwidgetList_ = java.util.Collections.emptyList(); public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo> getQuickwidgetListList() { return quickwidgetList_; } public int getQuickwidgetListCount() { return quickwidgetList_.size(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo getQuickwidgetList(int index) { return quickwidgetList_.get(index); } private void initFields() { } public final boolean isInitialized() { for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo element : getQuickwidgetListList()) { if (!element.isInitialized()) return false; } return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo element : getQuickwidgetListList()) { output.writeMessage(1, element); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo element : getQuickwidgetListList()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, element); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } if (result.quickwidgetList_ != java.util.Collections.EMPTY_LIST) { result.quickwidgetList_ = java.util.Collections.unmodifiableList(result.quickwidgetList_); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList.getDefaultInstance()) return this; if (!other.quickwidgetList_.isEmpty()) { if (result.quickwidgetList_.isEmpty()) { result.quickwidgetList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo>(); } result.quickwidgetList_.addAll(other.quickwidgetList_); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addQuickwidgetList(subBuilder.buildPartial()); break; } } } } // repeated .scope.QuickWidgetInfo quickwidgetList = 1; public java.util.List<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo> getQuickwidgetListList() { return java.util.Collections.unmodifiableList(result.quickwidgetList_); } public int getQuickwidgetListCount() { return result.getQuickwidgetListCount(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo getQuickwidgetList(int index) { return result.getQuickwidgetList(index); } public Builder setQuickwidgetList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo value) { if (value == null) { throw new NullPointerException(); } result.quickwidgetList_.set(index, value); return this; } public Builder setQuickwidgetList(int index, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.Builder builderForValue) { result.quickwidgetList_.set(index, builderForValue.build()); return this; } public Builder addQuickwidgetList(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo value) { if (value == null) { throw new NullPointerException(); } if (result.quickwidgetList_.isEmpty()) { result.quickwidgetList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo>(); } result.quickwidgetList_.add(value); return this; } public Builder addQuickwidgetList(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.Builder builderForValue) { if (result.quickwidgetList_.isEmpty()) { result.quickwidgetList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo>(); } result.quickwidgetList_.add(builderForValue.build()); return this; } public Builder addAllQuickwidgetList( java.lang.Iterable<? extends com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo> values) { if (result.quickwidgetList_.isEmpty()) { result.quickwidgetList_ = new java.util.ArrayList<com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo>(); } super.addAll(values, result.quickwidgetList_); return this; } public Builder clearQuickwidgetList() { result.quickwidgetList_ = java.util.Collections.emptyList(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickWidgetInfoList) } static { defaultInstance = new QuickWidgetInfoList(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickWidgetInfoList) } public static final class QuickWidgetSearch extends com.google.protobuf.GeneratedMessage { // Use QuickWidgetSearch.newBuilder() to construct. private QuickWidgetSearch() { initFields(); } private QuickWidgetSearch(boolean noInit) {} private static final QuickWidgetSearch defaultInstance; public static QuickWidgetSearch getDefaultInstance() { return defaultInstance; } public QuickWidgetSearch getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickWidgetSearch_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.opera.core.systems.scope.protos.DesktopWmProtos.internal_static_scope_QuickWidgetSearch_fieldAccessorTable; } public enum QuickWidgetSearchType implements com.google.protobuf.ProtocolMessageEnum { NAME(0, 0), TEXT(1, 1), POS(2, 2), ; public final int getNumber() { return value; } public static QuickWidgetSearchType valueOf(int value) { switch (value) { case 0: return NAME; case 1: return TEXT; case 2: return POS; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<QuickWidgetSearchType> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<QuickWidgetSearchType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<QuickWidgetSearchType>() { public QuickWidgetSearchType findValueByNumber(int number) { return QuickWidgetSearchType.valueOf(number) ; } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.getDescriptor().getEnumTypes().get(0); } private static final QuickWidgetSearchType[] VALUES = { NAME, TEXT, POS, }; public static QuickWidgetSearchType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private QuickWidgetSearchType(int index, int value) { this.index = index; this.value = value; } static { com.opera.core.systems.scope.protos.DesktopWmProtos.getDescriptor(); } // @@protoc_insertion_point(enum_scope:scope.QuickWidgetSearch.QuickWidgetSearchType) } // required .scope.DesktopWindowID windowID = 1; public static final int WINDOWID_FIELD_NUMBER = 1; private boolean hasWindowID; private com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID windowID_; public boolean hasWindowID() { return hasWindowID; } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID getWindowID() { return windowID_; } // required .scope.QuickWidgetSearch.QuickWidgetSearchType searchType = 2; public static final int SEARCHTYPE_FIELD_NUMBER = 2; private boolean hasSearchType; private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType searchType_; public boolean hasSearchType() { return hasSearchType; } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType getSearchType() { return searchType_; } // required string data = 3; public static final int DATA_FIELD_NUMBER = 3; private boolean hasData; private java.lang.String data_ = ""; public boolean hasData() { return hasData; } public java.lang.String getData() { return data_; } private void initFields() { windowID_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance(); searchType_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType.NAME; } public final boolean isInitialized() { if (!hasWindowID) return false; if (!hasSearchType) return false; if (!hasData) return false; if (!getWindowID().isInitialized()) return false; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (hasWindowID()) { output.writeMessage(1, getWindowID()); } if (hasSearchType()) { output.writeEnum(2, getSearchType().getNumber()); } if (hasData()) { output.writeString(3, getData()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasWindowID()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getWindowID()); } if (hasSearchType()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, getSearchType().getNumber()); } if (hasData()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(3, getData()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> { private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch result; // Construct using com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.newBuilder() private Builder() {} private static Builder create() { Builder builder = new Builder(); builder.result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch(); return builder; } protected com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch internalGetResult() { return result; } public Builder clear() { if (result == null) { throw new IllegalStateException( "Cannot call clear() after build()."); } result = new com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch(); return this; } public Builder clone() { return create().mergeFrom(result); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.getDescriptor(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch getDefaultInstanceForType() { return com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.getDefaultInstance(); } public boolean isInitialized() { return result.isInitialized(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch build() { if (result != null && !isInitialized()) { throw newUninitializedMessageException(result); } return buildPartial(); } private com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch buildPartial() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch returnMe = result; result = null; return returnMe; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch) { return mergeFrom((com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch other) { if (other == com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.getDefaultInstance()) return this; if (other.hasWindowID()) { mergeWindowID(other.getWindowID()); } if (other.hasSearchType()) { setSearchType(other.getSearchType()); } if (other.hasData()) { setData(other.getData()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); return this; } break; } case 10: { com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.Builder subBuilder = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.newBuilder(); if (hasWindowID()) { subBuilder.mergeFrom(getWindowID()); } input.readMessage(subBuilder, extensionRegistry); setWindowID(subBuilder.buildPartial()); break; } case 16: { int rawValue = input.readEnum(); com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType value = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { setSearchType(value); } break; } case 26: { setData(input.readString()); break; } } } } // required .scope.DesktopWindowID windowID = 1; public boolean hasWindowID() { return result.hasWindowID(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID getWindowID() { return result.getWindowID(); } public Builder setWindowID(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID value) { if (value == null) { throw new NullPointerException(); } result.hasWindowID = true; result.windowID_ = value; return this; } public Builder setWindowID(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.Builder builderForValue) { result.hasWindowID = true; result.windowID_ = builderForValue.build(); return this; } public Builder mergeWindowID(com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID value) { if (result.hasWindowID() && result.windowID_ != com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance()) { result.windowID_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.newBuilder(result.windowID_).mergeFrom(value).buildPartial(); } else { result.windowID_ = value; } result.hasWindowID = true; return this; } public Builder clearWindowID() { result.hasWindowID = false; result.windowID_ = com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.getDefaultInstance(); return this; } // required .scope.QuickWidgetSearch.QuickWidgetSearchType searchType = 2; public boolean hasSearchType() { return result.hasSearchType(); } public com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType getSearchType() { return result.getSearchType(); } public Builder setSearchType(com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType value) { if (value == null) { throw new NullPointerException(); } result.hasSearchType = true; result.searchType_ = value; return this; } public Builder clearSearchType() { result.hasSearchType = false; result.searchType_ = com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType.NAME; return this; } // required string data = 3; public boolean hasData() { return result.hasData(); } public java.lang.String getData() { return result.getData(); } public Builder setData(java.lang.String value) { if (value == null) { throw new NullPointerException(); } result.hasData = true; result.data_ = value; return this; } public Builder clearData() { result.hasData = false; result.data_ = getDefaultInstance().getData(); return this; } // @@protoc_insertion_point(builder_scope:scope.QuickWidgetSearch) } static { defaultInstance = new QuickWidgetSearch(true); com.opera.core.systems.scope.protos.DesktopWmProtos.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:scope.QuickWidgetSearch) } private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_DesktopWindowInfo_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_DesktopWindowInfo_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_DesktopWindowRect_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_DesktopWindowRect_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickMenuID_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickMenuID_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickMenuList_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickMenuList_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickMenuInfo_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickMenuInfo_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickMenuItemID_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickMenuItemID_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickMenuItemInfo_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickMenuItemInfo_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickWidgetInfo_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickWidgetInfo_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_DesktopWindowID_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_DesktopWindowID_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_DesktopWindowList_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_DesktopWindowList_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickWidgetInfoList_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickWidgetInfoList_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_scope_QuickWidgetSearch_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_scope_QuickWidgetSearch_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\034desktop_window_manager.proto\022\005scope\"\224\003" + "\n\021DesktopWindowInfo\022\020\n\010windowID\030\001 \002(\r\022\r\n" + "\005title\030\002 \002(\t\022\014\n\004name\030\003 \002(\t\022>\n\nwindowType" + "\030\004 \002(\0162*.scope.DesktopWindowInfo.Desktop" + "WindowType\022\020\n\010onScreen\030\005 \002(\010\022:\n\005state\030\006 " + "\002(\0162+.scope.DesktopWindowInfo.DesktopWin" + "dowState\022&\n\004rect\030\007 \002(\0132\030.scope.DesktopWi" + "ndowRect\022\016\n\006active\030\010 \002(\010\"8\n\021DesktopWindo" + "wType\022\013\n\007UNKNOWN\020\000\022\n\n\006DIALOG\020\001\022\n\n\006NORMAL" + "\020\002\"P\n\022DesktopWindowState\022\014\n\010RESTORED\020\000\022\r", "\n\tMINIMIZED\020\001\022\r\n\tMAXIMIZED\020\002\022\016\n\nFULLSCRE" + "EN\020\003\"H\n\021DesktopWindowRect\022\t\n\001x\030\001 \002(\r\022\t\n\001" + "y\030\002 \002(\r\022\r\n\005width\030\003 \002(\r\022\016\n\006height\030\004 \002(\r\"\037" + "\n\013QuickMenuID\022\020\n\010menuName\030\001 \002(\t\"7\n\rQuick" + "MenuList\022&\n\010menuList\030\001 \003(\0132\024.scope.Quick" + "MenuInfo\"\265\001\n\rQuickMenuInfo\022\"\n\006menuId\030\001 \002" + "(\0132\022.scope.QuickMenuID\022&\n\004rect\030\002 \002(\0132\030.s" + "cope.DesktopWindowRect\022(\n\010windowId\030\003 \002(\013" + "2\026.scope.DesktopWindowID\022.\n\014menuItemList" + "\030\004 \003(\0132\030.scope.QuickMenuItemInfo\"#\n\017Quic", "kMenuItemID\022\020\n\010menuText\030\001 \002(\t\"\214\002\n\021QuickM" + "enuItemInfo\022\014\n\004text\030\001 \002(\t\022\016\n\006action\030\002 \001(" + "\t\022\017\n\007submenu\030\003 \001(\t\022\024\n\014action_param\030\004 \001(\t" + "\022\013\n\003row\030\005 \002(\r\022\026\n\016shortcutletter\030\006 \001(\t\022\020\n" + "\010shortcut\030\007 \001(\t\022&\n\004rect\030\010 \002(\0132\030.scope.De" + "sktopWindowRect\022\017\n\007enabled\030\t \002(\010\022\017\n\007chec" + "ked\030\n \002(\010\022\020\n\010selected\030\013 \002(\010\022\014\n\004bold\030\014 \002(" + "\010\022\021\n\tseparator\030\r \002(\010\"\346\004\n\017QuickWidgetInfo" + "\022\014\n\004name\030\001 \002(\t\0224\n\004type\030\002 \002(\0162&.scope.Qui" + "ckWidgetInfo.QuickWidgetType\022\017\n\007visible\030", "\003 \002(\010\022\014\n\004text\030\004 \002(\t\022\r\n\005value\030\005 \002(\r\022\017\n\007en" + "abled\030\006 \002(\010\022\023\n\013defaultLook\030\007 \002(\010\022\023\n\013focu" + "sedLook\030\010 \002(\010\022&\n\004rect\030\t \002(\0132\030.scope.Desk" + "topWindowRect\022\016\n\006parent\030\n \001(\t\022\013\n\003row\030\013 \001" + "(\r\022\013\n\003col\030\014 \001(\r\022\024\n\014visible_text\030\r \001(\t\022\027\n" + "\017additional_text\030\016 \001(\t\"\244\002\n\017QuickWidgetTy" + "pe\022\013\n\007UNKNOWN\020\000\022\n\n\006BUTTON\020\001\022\014\n\010CHECKBOX\020" + "\002\022\r\n\tDIALOGTAB\020\003\022\014\n\010DROPDOWN\020\004\022\020\n\014DROPDO" + "WNITEM\020\005\022\r\n\tEDITFIELD\020\006\022\t\n\005LABEL\020\007\022\017\n\013RA" + "DIOBUTTON\020\010\022\020\n\014ADDRESSFIELD\020\t\022\n\n\006SEARCH\020", "\n\022\013\n\007TOOLBAR\020\013\022\014\n\010TREEVIEW\020\014\022\014\n\010TREEITEM" + "\020\r\022\r\n\tTABBUTTON\020\016\022\r\n\tTHUMBNAIL\020\017\022\016\n\nGRID" + "LAYOUT\020\020\022\014\n\010GRIDITEM\020\021\022\r\n\tQUICKFIND\020\022\" "\017DesktopWindowID\022\020\n\010windowID\030\001 \002(\r\"A\n\021De" + "sktopWindowList\022,\n\nwindowList\030\001 \003(\0132\030.sc" + "ope.DesktopWindowInfo\"F\n\023QuickWidgetInfo" + "List\022/\n\017quickwidgetList\030\001 \003(\0132\026.scope.Qu" + "ickWidgetInfo\"\305\001\n\021QuickWidgetSearch\022(\n\010w" + "indowID\030\001 \002(\0132\026.scope.DesktopWindowID\022B\n" + "\nsearchType\030\002 \002(\0162..scope.QuickWidgetSea", "rch.QuickWidgetSearchType\022\014\n\004data\030\003 \002(\t\"" + "4\n\025QuickWidgetSearchType\022\010\n\004NAME\020\000\022\010\n\004TE" + "XT\020\001\022\007\n\003POS\020\002B8\n#com.opera.core.systems." + "scope.protosB\017DesktopWmProtosH\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_scope_DesktopWindowInfo_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_scope_DesktopWindowInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_DesktopWindowInfo_descriptor, new java.lang.String[] { "WindowID", "Title", "Name", "WindowType", "OnScreen", "State", "Rect", "Active", }, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.class, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo.Builder.class); internal_static_scope_DesktopWindowRect_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_scope_DesktopWindowRect_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_DesktopWindowRect_descriptor, new java.lang.String[] { "X", "Y", "Width", "Height", }, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.class, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect.Builder.class); internal_static_scope_QuickMenuID_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_scope_QuickMenuID_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickMenuID_descriptor, new java.lang.String[] { "MenuName", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuID.Builder.class); internal_static_scope_QuickMenuList_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_scope_QuickMenuList_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickMenuList_descriptor, new java.lang.String[] { "MenuList", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuList.Builder.class); internal_static_scope_QuickMenuInfo_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_scope_QuickMenuInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickMenuInfo_descriptor, new java.lang.String[] { "MenuId", "Rect", "WindowId", "MenuItemList", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuInfo.Builder.class); internal_static_scope_QuickMenuItemID_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_scope_QuickMenuItemID_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickMenuItemID_descriptor, new java.lang.String[] { "MenuText", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemID.Builder.class); internal_static_scope_QuickMenuItemInfo_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_scope_QuickMenuItemInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickMenuItemInfo_descriptor, new java.lang.String[] { "Text", "Action", "Submenu", "ActionParam", "Row", "Shortcutletter", "Shortcut", "Rect", "Enabled", "Checked", "Selected", "Bold", "Separator", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickMenuItemInfo.Builder.class); internal_static_scope_QuickWidgetInfo_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_scope_QuickWidgetInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickWidgetInfo_descriptor, new java.lang.String[] { "Name", "Type", "Visible", "Text", "Value", "Enabled", "DefaultLook", "FocusedLook", "Rect", "Parent", "Row", "Col", "VisibleText", "AdditionalText", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.Builder.class); internal_static_scope_DesktopWindowID_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_scope_DesktopWindowID_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_DesktopWindowID_descriptor, new java.lang.String[] { "WindowID", }, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.class, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowID.Builder.class); internal_static_scope_DesktopWindowList_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_scope_DesktopWindowList_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_DesktopWindowList_descriptor, new java.lang.String[] { "WindowList", }, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList.class, com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList.Builder.class); internal_static_scope_QuickWidgetInfoList_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_scope_QuickWidgetInfoList_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickWidgetInfoList_descriptor, new java.lang.String[] { "QuickwidgetList", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList.Builder.class); internal_static_scope_QuickWidgetSearch_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_scope_QuickWidgetSearch_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_scope_QuickWidgetSearch_descriptor, new java.lang.String[] { "WindowID", "SearchType", "Data", }, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.class, com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } public static void internalForceInit() {} // @@protoc_insertion_point(outer_class_scope) }
package org.voovan.network; import org.voovan.network.Event.EventName; import org.voovan.network.exception.IoFilterException; import org.voovan.network.exception.SendMessageException; import org.voovan.network.handler.SynchronousHandler; import org.voovan.network.udp.UdpSocket; import org.voovan.tools.FastThreadLocal; import org.voovan.tools.TObject; import org.voovan.tools.collection.Chain; import org.voovan.tools.buffer.TByteBuffer; import org.voovan.tools.log.Logger; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.concurrent.TimeoutException; public class EventProcess { private EventProcess(){ } /** * Accept * * @param event * * @throws IOException IO */ public static void onAccepted(Event event) throws IOException { SocketContext socketContext = event.getSession().socketContext(); socketContext.acceptStart(); } /** * * * @param event * @throws IOException IO * */ public static void onConnect(Event event) throws IOException { IoSession session = event.getSession(); // SSL , onConnect if (session.isSSLMode() && !session.getSSLParser().isHandShakeDone() && session.socketContext().connectModel == ConnectModel.CLIENT) { session.getSSLParser().doHandShake(); return; } try { session.getState().setInit(false); session.getState().setConnect(true); session.checkIdle(); SocketContext socketContext = event.getSession().socketContext(); if (socketContext != null && session != null) { Object original = socketContext.handler().onConnect(session); //null if (original != null) { sendMessage(session, original); session.flush(); } } } finally { session.getState().setConnect(false); } } /** * * * @param event * */ public static void onDisconnect(Event event) { IoSession session = event.getSession(); try { //,Close session.getState().setClose(true); session.cancelIdle(); SocketContext socketContext = event.getSession().socketContext(); if (socketContext != null) { socketContext.handler().onDisconnect(session); } } finally { session.getState().setClose(false); } } /** * * * @param event * * @throws IOException IO */ public static void onRead(Event event) throws IOException { IoSession session = event.getSession(); if (session != null) { try { // onRecive Object result; while (session.getReadByteBufferChannel().size()>0) { try { session.getState().setReceive(true); int splitLength = session.getMessageLoader().read(); if (splitLength >= 0) { result = doRecive(session, splitLength); } else { break; } } finally { session.getState().setReceive(false); } sendMessage(session, result); result = null; } } finally { // flush if(!(session.socketContext().handler instanceof SynchronousHandler)) { // onRecive if (session.getSendByteBufferChannel().size() > 0) { // flush session.flush(); } if (session.getReadByteBufferChannel().size() > 0) { EventTrigger.fireReceiveAsync(session); } } } } } /** * * @param session * @param splitLength * @return */ public static ByteBuffer loadSplitData(IoSession session, int splitLength) { if(splitLength == 0){ return TByteBuffer.EMPTY_BYTE_BUFFER; } ByteBuffer byteBuffer = TByteBuffer.allocateDirect(); byteBuffer.clear(); if (byteBuffer.capacity() < splitLength) { TByteBuffer.reallocate(byteBuffer, splitLength); } try { byteBuffer.limit(splitLength); } catch (Exception e){ Logger.error(e); } if ((session.socketContext().getConnectType() == ConnectType.UDP && session.isOpen()) || session.isConnected()) { session.getReadByteBufferChannel().readHead(byteBuffer); return byteBuffer; } else { return null; } } /** * * @param session * @param splitLength * @return * @throws IoFilterException */ public static Object doRecive(IoSession session, int splitLength) throws IOException { Object result = null; ByteBuffer byteBuffer = loadSplitData(session, splitLength); // null if (byteBuffer == null) { session.getState().setReceive(false); return null; } result = filterDecoder(session, byteBuffer); if (result != null) { IoHandler handler = session.socketContext().handler(); result = handler.onReceive(session, result); } return result; } /** * * @param session Session * @param readedBuffer * @return * @throws IoFilterException */ public static Object filterDecoder(IoSession session, ByteBuffer readedBuffer) throws IoFilterException{ Object result = readedBuffer; Chain<IoFilter> filterChain = (Chain<IoFilter>) session.socketContext().getReciveFilterChain(); filterChain.rewind(); while (filterChain.hasNext()) { IoFilter fitler = filterChain.next(); result = fitler.decode(session, result); if (result == null) { break; } } return result; } /** * * @param session Session * @param result * @return * @throws IoFilterException */ public static ByteBuffer filterEncoder(IoSession session, Object result) throws IoFilterException{ Chain<IoFilter> filterChain = (Chain<IoFilter>) session.socketContext().getSendFilterChain(); filterChain.rewind(); while (filterChain.hasPrevious()) { IoFilter fitler = filterChain.previous(); result = fitler.encode(session, result); if (result == null) { break; } } if (result == null) { return null; } else if (result instanceof ByteBuffer) { return (ByteBuffer) result; } else { throw new IoFilterException("Send object must be ByteBuffer, " + "please check you filter be sure the latest filter return Object's type is ByteBuffer."); } } /** * * * @param session Session * @param obj */ public static void sendMessage(IoSession session, Object obj) { final Object sendObj = obj; if(sendObj == null) { return; } try { session.getState().setSend(true); ByteBuffer sendBuffer = EventProcess.filterEncoder(session, sendObj); if (sendBuffer != null && session.isOpen()) { if (sendBuffer.limit() > 0) { int sendLength = session.send(sendBuffer); if(sendLength >= 0) { sendBuffer.rewind(); } else { throw new IOException("EventProcess.sendMessage faild, writeToChannel length: " + sendLength); } } } EventTrigger.fireSent(session, sendObj); } catch (IOException e) { EventTrigger.fireException(session, e); } finally { session.getState().setSend(false); } } /** * * * @param event * * @param sendObj * * @throws IOException IO */ public static void onSent(Event event, Object sendObj) throws IOException { IoSession session = event.getSession(); SocketContext socketContext = session.socketContext(); if (socketContext != null) { socketContext.handler().onSent(session, sendObj); } } /** * Socket * * @param event * * @throws IOException IO */ public static void onFlush(Event event) throws IOException { IoSession session = event.getSession(); SocketContext socketContext = session.socketContext(); if (socketContext != null) { socketContext.handler().onFlush(session); } } /** * * * @param event */ public static void onIdle(Event event) { SocketContext socketContext = event.getSession().socketContext(); if (socketContext != null) { IoSession session = event.getSession(); socketContext.handler().onIdle(session); } } /** * * * @param event * * @param e */ public static void onException(Event event, Exception e) { IoSession session = event.getSession(); SocketContext socketContext = event.getSession().socketContext(); if (socketContext != null) { if (socketContext.handler() != null) { socketContext.handler().onException(session, e); } } } /** * * @param event */ public static void process(Event event) { if (event == null) { return; } EventName eventName = event.getName(); try { if (eventName == EventName.ON_ACCEPTED) { EventProcess.onAccepted(event); } else if (eventName == EventName.ON_CONNECT) { EventProcess.onConnect(event); } else if (eventName == EventName.ON_DISCONNECT) { EventProcess.onDisconnect(event); } else if (eventName == EventName.ON_RECEIVE) { EventProcess.onRead(event); } else if (eventName == EventName.ON_SENT) { EventProcess.onSent(event, event.getOther()); } else if (eventName == EventName.ON_FLUSH) { EventProcess.onFlush(event); } else if (eventName == EventName.ON_IDLE) { EventProcess.onIdle(event); } else if (eventName == EventName.ON_EXCEPTION) { EventProcess.onException(event, (Exception)event.getOther()); } } catch (Exception e) { EventProcess.onException(event, e); } } }
package com.qmetry.qaf.automation.core; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.event.ConfigurationEvent; import org.apache.commons.configuration.event.ConfigurationListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.impl.LogFactoryImpl; import org.hamcrest.Matchers; import com.qmetry.qaf.automation.keys.ApplicationProperties; import com.qmetry.qaf.automation.step.JavaStepFinder; import com.qmetry.qaf.automation.step.TestStep; import com.qmetry.qaf.automation.step.client.ScenarioFactory; import com.qmetry.qaf.automation.step.client.csv.KwdTestFactory; import com.qmetry.qaf.automation.step.client.excel.ExcelTestFactory; import com.qmetry.qaf.automation.step.client.text.BDDTestFactory; import com.qmetry.qaf.automation.util.FileUtil; import com.qmetry.qaf.automation.util.PropertyUtil; import com.qmetry.qaf.automation.util.StringComparator; import com.qmetry.qaf.automation.util.StringMatcher; import com.qmetry.qaf.automation.util.StringUtil; /** * Configuration manager class. Singleton with early initialization. * <p> * This class loads file provided by system property * <code>application.properties.file</code> (Default value is * "resources/application.properties"). Also loads all property files form * <code>test.props.dir</code>(default value is "resources") if * <code>resources.load.subdirs</code> flag is 1. * <p> * To access any property value within automation, use following way * {@link PropertyUtil} props={@link #ConfigurationManager}. * {@link #getInstance()}.{@link#getApplicationProperties()};<br> * String sval = props.{@link PropertyUtil#getPropertyValue(String)} * * @author chirag */ public class ConfigurationManager { // early initialization static final Log log = LogFactoryImpl.getLog(ConfigurationManager.class); private static final ConfigurationManager INSTANCE = new ConfigurationManager(); /** * Private constructor, prevents instantiation from other classes */ private ConfigurationManager() { AbstractConfiguration.setDefaultListDelimiter(';'); } public static ConfigurationManager getInstance() { return INSTANCE; } private static InheritableThreadLocal<PropertyUtil> LocalProps = new InheritableThreadLocal<PropertyUtil>() { @Override protected PropertyUtil initialValue() { PropertyUtil p = new PropertyUtil( System.getProperty("application.properties.file", "resources/application.properties")); p.setProperty("isfw.build.info", getBuildInfo()); p.setEncoding(p.getString(ApplicationProperties.LOCALE_CHAR_ENCODING.key, "UTF-8")); File prjDir = new File(".").getAbsoluteFile().getParentFile(); p.setProperty("project.path", prjDir.getAbsolutePath()); if(!p.containsKey("project.name")) p.setProperty("project.name", prjDir.getName()); log.info("ISFW build info: " + p.getProperty("isfw.build.info")); String[] resources = p.getStringArray("env.resources", "resources"); for (String resource : resources) { addBundle(p, resource); } ConfigurationListener cl = new PropertyConfigurationListener(); p.addConfigurationListener(cl); return p; } @Override protected PropertyUtil childValue(PropertyUtil parentValue) { PropertyUtil cp = new PropertyUtil(parentValue); ConfigurationListener cl = new PropertyConfigurationListener(); cp.addConfigurationListener(cl); return cp; } }; /** * To add local resources. * * @param fileOrDir */ public static void addBundle(String fileOrDir) { ConfigurationManager.addBundle(getBundle(), fileOrDir); } /** * @param p * @param fileOrDir */ private static void addBundle(PropertyUtil p, String fileOrDir) { String localResources = p.getString("local.reasources", p.getString("env.local.resources", "resources")); fileOrDir = p.getSubstitutor().replace(fileOrDir); File resourceFile = new File(fileOrDir); String[] locals = p.getStringArray(ApplicationProperties.LOAD_LOCALES.key); /** * will reload existing properties value(if any) if the last loaded * dir/file is not the current one. case: suit-1 default, suit-2 : * s2-local, suit-3: default Here after suit-2 you need to reload * default. */ if (!localResources.equalsIgnoreCase(resourceFile.getAbsolutePath())) { p.addProperty("local.reasources", resourceFile.getAbsolutePath()); if (resourceFile.exists()) { if (resourceFile.isDirectory()) { boolean loadSubDirs = p.getBoolean("resources.load.subdirs", true); File[] propFiles = FileUtil.listFilesAsArray(resourceFile, ".properties", StringComparator.Suffix, loadSubDirs); log.info("Resource dir: " + resourceFile.getAbsolutePath() + ". Found property files to load: " + propFiles.length); File[] locFiles = FileUtil.listFilesAsArray(resourceFile, ".loc", StringComparator.Suffix, loadSubDirs); File[] wscFiles = FileUtil.listFilesAsArray(resourceFile, ".wsc", StringComparator.Suffix, loadSubDirs); PropertyUtil p1 = new PropertyUtil(); p1.load(propFiles); p1.load(locFiles); p1.load(wscFiles); p.copy(p1); propFiles = FileUtil.listFilesAsArray(resourceFile, ".xml", StringComparator.Suffix, loadSubDirs); log.info("Resource dir: " + resourceFile.getAbsolutePath() + ". Found property files to load: " + propFiles.length); p1 = new PropertyUtil(); p1.load(propFiles); p.copy(p1); } else { try { if (fileOrDir.endsWith(".properties") || fileOrDir.endsWith(".xml") || fileOrDir.endsWith(".loc") || fileOrDir.endsWith(".wsc")) { p.load(new File[]{resourceFile}); } } catch (Exception e) { log.error( "Unable to load " + resourceFile.getAbsolutePath() + "!", e); } } // add locals if any if (null != locals && locals.length > 0 && (locals.length == 1 || StringUtil.isBlank(p.getString( ApplicationProperties.DEFAULT_LOCALE.key, "")))) { p.setProperty(ApplicationProperties.DEFAULT_LOCALE.key, locals[0]); } for (String local : locals) { log.info("loading local: " + local); addLocal(p, local, fileOrDir); } } else { log.error(resourceFile.getAbsolutePath() + " not exist!"); } } } private static void addLocal(PropertyUtil p, String local, String fileOrDir) { String defaultLocal = p.getString(ApplicationProperties.DEFAULT_LOCALE.key, ""); File resourceFile = new File(fileOrDir); /** * will reload existing properties value(if any) if the last loaded * dir/file is not the current one. case: suit-1 default, suit-2 : * s2-local, suit-3: default Here after suit-2 you need to reload * default. */ boolean loadSubDirs = p.getBoolean("resources.load.subdirs", true); if (resourceFile.exists()) { PropertyUtil p1 = new PropertyUtil(); p1.setEncoding( p.getString(ApplicationProperties.LOCALE_CHAR_ENCODING.key, "UTF-8")); if (resourceFile.isDirectory()) { File[] propFiles = FileUtil.listFilesAsArray(resourceFile, "." + local, StringComparator.Suffix, loadSubDirs); p1.load(propFiles); } else { try { if (fileOrDir.endsWith(local)) { p1.load(fileOrDir); } } catch (Exception e) { log.error("Unable to load " + resourceFile.getAbsolutePath() + "!", e); } } if (local.equalsIgnoreCase(defaultLocal)) { p.copy(p1); } else { Iterator<?> keyIter = p1.getKeys(); Configuration localSet = p.subset(local); while (keyIter.hasNext()) { String key = (String) keyIter.next(); localSet.addProperty(key, p1.getObject(key)); } } } else { log.error(resourceFile.getAbsolutePath() + " not exist!"); } } public static void addAll(Map<String, ?> props) { ConfigurationManager.getBundle().addAll(props); } public static PropertyUtil getBundle() { return ConfigurationManager.LocalProps.get(); } private static Map<String, String> getBuildInfo() { Manifest manifest = null; Map<String, String> buildInfo = new HashMap<String, String>(); JarFile jar = null; try { URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource() .getLocation(); File file = new File(url.toURI()); jar = new JarFile(file); manifest = jar.getManifest(); } catch (NullPointerException ignored) { } catch (URISyntaxException ignored) { } catch (IOException ignored) { } catch (IllegalArgumentException ignored) { } finally { if (null != jar) try { jar.close(); } catch (IOException e) { log.warn(e.getMessage()); } } if (manifest == null) { return buildInfo; } try { Attributes attributes = manifest.getAttributes("Build-Info"); Set<Entry<Object, Object>> entries = attributes.entrySet(); for (Entry<Object, Object> e : entries) { buildInfo.put(String.valueOf(e.getKey()), String.valueOf(e.getValue())); } } catch (NullPointerException e) { // Fall through } return buildInfo; } /** * Get test-step mapping for current configuration * * @return */ @SuppressWarnings("unchecked") public static Map<String, TestStep> getStepMapping() { if (!ConfigurationManager.getBundle().containsKey("teststep.mapping")) { ConfigurationManager.getBundle().setProperty("teststep.mapping", JavaStepFinder.getAllJavaSteps()); if (ConfigurationManager.getBundle() .containsKey(ApplicationProperties.STEP_PROVIDER_PKG.key)) { for (String pkg : ConfigurationManager.getBundle() .getStringArray(ApplicationProperties.STEP_PROVIDER_PKG.key)) { for (ScenarioFactory factory : getStepFactories()) { factory.process(pkg.replaceAll("\\.", "/")); } } } } return (Map<String, TestStep>) ConfigurationManager.getBundle() .getObject("teststep.mapping"); } private static ScenarioFactory[] getStepFactories() { return new ScenarioFactory[]{new BDDTestFactory(Arrays.asList("bdl")), new KwdTestFactory(Arrays.asList("kwl")), new ExcelTestFactory()}; } private static class PropertyConfigurationListener implements ConfigurationListener { String oldValue; @SuppressWarnings("unchecked") @Override public void configurationChanged(ConfigurationEvent event) { if ((event.getType() == AbstractConfiguration.EVENT_CLEAR_PROPERTY || event.getType() == AbstractConfiguration.EVENT_SET_PROPERTY) && event.isBeforeUpdate()) { oldValue = String.format("%s", getBundle().getObject(event.getPropertyName())); } if ((event.getType() == AbstractConfiguration.EVENT_ADD_PROPERTY || event.getType() == AbstractConfiguration.EVENT_SET_PROPERTY) && !event.isBeforeUpdate()) { String key = event.getPropertyName(); Object value = event.getPropertyValue(); if (null != oldValue && Matchers.equalTo(oldValue).matches(value)) { // do nothing return; } // driver reset if (key.equalsIgnoreCase(ApplicationProperties.DRIVER_NAME.key) // single capability or set of capabilities change || StringMatcher.containsIgnoringCase(".capabilit").match(key) || key.equalsIgnoreCase(ApplicationProperties.REMOTE_SERVER.key) || key.equalsIgnoreCase(ApplicationProperties.REMOTE_PORT.key)) { TestBaseProvider.instance().get().tearDown(); if(key.equalsIgnoreCase(ApplicationProperties.DRIVER_NAME.key)){ TestBaseProvider.instance().get().setDriver((String)value); } } String[] bundles = null; // Resource loading if (key.equalsIgnoreCase("env.resources")) { if (event.getPropertyValue() instanceof ArrayList<?>) { ArrayList<String> bundlesArray = ((ArrayList<String>) event.getPropertyValue()); bundles = bundlesArray.toArray(new String[bundlesArray.size()]); } else { String resourcesBundle = (String) value; if (StringUtil.isNotBlank(resourcesBundle)) bundles = resourcesBundle.split(String .valueOf(PropertyUtil.getDefaultListDelimiter())); } if (null != bundles && bundles.length > 0) { for (String res : bundles) { log.info("Adding resources from: " + res); ConfigurationManager.addBundle(res); } } } // Locale loading if (key.equalsIgnoreCase(ApplicationProperties.DEFAULT_LOCALE.key)) { String[] resources = getBundle().getStringArray("env.resources", "resources"); for (String resource : resources) { String fileOrDir = getBundle().getSubstitutor().replace(resource); addLocal(getBundle(), (String) event.getPropertyValue(), fileOrDir); } } // step provider package re-load if (key.equalsIgnoreCase(ApplicationProperties.STEP_PROVIDER_PKG.key)) { // has loaded steps and adding more or override java // steps.... // for example suite level parameter has common steps and // test level parameter has test specific steps if (ConfigurationManager.getBundle() .containsKey("teststep.mapping")) { ConfigurationManager.getStepMapping() .putAll(JavaStepFinder.getAllJavaSteps()); for (ScenarioFactory factory : getStepFactories()) { if (event.getPropertyValue() instanceof ArrayList<?>) { ArrayList<String> bundlesArray = ((ArrayList<String>) event.getPropertyValue()); bundles = bundlesArray .toArray(new String[bundlesArray.size()]); for (String pkg : bundlesArray) { factory.process(pkg.replaceAll("\\.", "/")); } } else { String resourcesBundle = (String) value; if (StringUtil.isNotBlank(resourcesBundle)) { factory.process( resourcesBundle.replaceAll("\\.", "/")); } } } } } } } } }
package dk.aau.sw402F15.CodeGenerator; import dk.aau.sw402F15.Symboltable.Scope; import dk.aau.sw402F15.Symboltable.ScopeDepthFirstAdapter; import dk.aau.sw402F15.Symboltable.Symbol; import dk.aau.sw402F15.Symboltable.SymbolArray; import dk.aau.sw402F15.Symboltable.SymbolFunction; import dk.aau.sw402F15.Symboltable.Type.SymbolType; import dk.aau.sw402F15.parser.node.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.awt.geom.FlatteningPathIterator; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.EmptyStackException; public class CodeGenerator extends ScopeDepthFirstAdapter { private int jumpLabel = 0; private int returnlabel; private int nextDAddress = -4; private double nextWAddress = 0.00; private int nextHAddress = 0; private int startFunctionNumber = -1; PrintWriter instructionWriter; PrintWriter symbolWriter; public String getNextDAddress(boolean increment) { if (nextDAddress > 32763) throw new OutOfMemoryError(); if (increment) return "D" + (nextDAddress += 4); else return "D" + nextDAddress; } public String getPreviousDAddress() { int tmp = nextDAddress; return "D" + (nextDAddress - 4); } public String getNextWAddress(boolean increment) { if (nextWAddress > 508) throw new OutOfMemoryError(); if (increment) return "W" + (nextWAddress += 0.1); else return "W" + nextWAddress; } public String stackPointer(boolean increment) { if (nextHAddress > 4091) throw new OutOfMemoryError(); int currentAddress = nextHAddress; nextHAddress += 4; if (increment) return "H" + (currentAddress); else return "H" + currentAddress; } public int getFunctionNumber(boolean increment) { if (increment) return startFunctionNumber += 1; else return startFunctionNumber; } public < T > void push(T value) { if (value.getClass() == Integer.class) Emit("MOV(021) &" + value + " " + stackPointer(true), true); else if (value.getClass() == Float.class || value.getClass() == Double.class) Emit("+F(454) +0,0 +" + value.toString().replace(".", ",") + " " + stackPointer(true) + "", true); else if (value.getClass() == String.class) Emit("MOV(021) " + value + " " + stackPointer(true), true); else throw new ClassFormatError(); } public String pop() { if (nextHAddress < 0) throw new EmptyStackException(); return "H" + (nextHAddress -= 4); } public String peek() { return "H" + nextHAddress; } public CodeGenerator(Scope scope) { super(scope, scope); try { // create writer instances instructionWriter = new PrintWriter("InstructionList.txt", "UTF-8"); symbolWriter = new PrintWriter("SymbolList.txt", "UTF-8"); // here we call the init method Emit("LD P_First_Cycle", true); // reset all addresses Emit("SSET(630) " + getNextDAddress(true) + " &32767", true); Emit("SSET(630) " + stackPointer(true) + " &1535", true); Emit("SBS(091) 0", true); // here we call the run Method Emit("LD P_On", true); Emit("SBS(091) 1", true); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void outStart(Start node){ Emit("END(001)", true); instructionWriter.close(); symbolWriter.close(); } @Override public void outAAssignmentExpr(AAssignmentExpr node) { super.outAAssignmentExpr(node); if(node.getLeft().getClass() == AArrayExpr.class){ String address = pop(); Emit("MOV(021) " + pop() + " @" + address, true); } else{ Emit("MOV(021) " + pop() + " " + node.getLeft(), true); } } @Override public void caseAArrayExpr(AArrayExpr node){ node.getExpr().apply(this); SymbolArray symbol = (SymbolArray) currentScope.getSymbolOrThrow(node.getName().getText(), node.getName()); push(node.getName().getText()); int size = 1; if (symbol.getContainedType().getType() == SymbolType.Type.Int || symbol.getContainedType().getType() == SymbolType.Type.Decimal) { size = 2; } node.getExpr().apply(this); Emit("*(420) " + pop() + " &" + size + " " + stackPointer(true), true); // index * size = offset Emit("+(400) " + pop() + " " + node.getName().getText() + " " + stackPointer(true), true); // offset + start = location Node parent = node.parent(); if(parent.getClass() == AAssignmentExpr.class && ((AAssignmentExpr)parent).getLeft() == node) { Emit("MOV(021) " + pop() + " " + stackPointer(true), true); // push pointer to stack } else{ Emit("MOV(021) @" + pop() + " " + stackPointer(true), true); // push value to stack } } @Override public void caseADeclaration(ADeclaration node){ super.caseADeclaration(node); } @Override public void outABreakStatement(ABreakStatement node){ super.outABreakStatement(node); Emit("BREAK(514)", true); } @Override public void outACaseStatement(ACaseStatement node){ //throw new NotImplementedException(); } @Override public void outAIncrementExpr(AIncrementExpr node) { super.outAIncrementExpr(node); Emit("++(590) " + node.getName(), true); } @Override public void outADecrementExpr(ADecrementExpr node) { super.outADecrementExpr(node); Emit("--(592) " + node.getName(), true); } @Override public void outACompareAndExpr(ACompareAndExpr node){ super.outACompareAndExpr(node); Emit("ANDW(034) D" + (nextDAddress - 4) + " " + getNextDAddress(false) + " " + getNextDAddress(true), true); } @Override public void outACompareOrExpr(ACompareOrExpr node){ super.outACompareOrExpr(node); Emit("ORW(035) D" + (nextDAddress - 4) + " " + getNextDAddress(false) + " " + getNextDAddress(true), true); } @Override public void outACompareEqualExpr(ACompareEqualExpr node){ super.outACompareEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND=(300)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareGreaterExpr(ACompareGreaterExpr node){ super.outACompareGreaterExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND>(320)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node){ super.outACompareGreaterOrEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND>=(325)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareLessExpr(ACompareLessExpr node){ super.outACompareLessExpr(node); String arg1 = pop(); String arg2 = pop(); if (node.parent().getClass() == AWhileStatement.class) { Emit("AND<(310)" + " " + arg1 + " " + arg2, true); Emit("SET " + getNextWAddress(false), true); Emit("AND<(310)" + " " + arg2 + " " + arg1, true); Emit("RSET " + getNextWAddress(false), true); } else { Emit("AND<(310)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(false), true); } } @Override public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node) { super.outACompareLessOrEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND<=(315)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareNotEqualExpr(ACompareNotEqualExpr node) { super.outACompareNotEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND<>(305)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outAContinueStatement(AContinueStatement node){ //throw new NotImplementedException(); } @Override public void outADeclaration(ADeclaration node) { Symbol symbol = currentScope.getSymbolOrThrow(node.getName().getText(), node); if (symbol.getType().equals(SymbolType.Boolean())) { declareBool(node.getName().getText(), false); } else if (symbol.getType().equals(SymbolType.Int())) { declareInt(node.getName().getText(), 0); } else if (symbol.getType().equals(SymbolType.Char())) { throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Decimal())) { Emit(node.getName().getText() + "\tREAL\tD" + node.getName() + "\t\t0\t", false); } else if (symbol.getType().equals(SymbolType.Timer())) { Emit(node.getName().getText() + "\tTIMER\tD" + node.getName() + "\t\t0\t", false); } else if (symbol.getType().equals(SymbolType.Array())) { declareArray((SymbolArray)symbol); } else if (symbol.getType().equals(SymbolType.Void())){ // Method is a void function throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Type.Function)) { throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Type.Struct)) { throw new NotImplementedException(); } else { // throw new RuntimeException(); // TODO Need new Exception. Pretty unknown error though } } private void declareArray(SymbolArray symbol){ ADeclaration node = (ADeclaration) symbol.getNode(); AArrayDefinition array = (AArrayDefinition) node.getArray(); int size = Integer.parseInt(array.getNumber().getText()); int address = nextDAddress; for (int i = 0; i < size; i++){ getNextDAddress(true); } String name = symbol.getName(); Emit(name + "\tINT\t &"+ address + "\t\t0\t", false); } private void declareInt(String name, int value){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tINT\t" + address + "\t\t0\t", false); // Assign Emit("MOV(021) &" + value + " " + name, true); } private void declareBool(String name, boolean value){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tBOOL\t" + address + ".00\t\t0\t", false); // Assign if (value) Emit("SET " + name, true); else Emit("RSET " + name, true); } private void declareDecimal(String name, int value){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tBOOL\t" + address + ".00\t\t0\t", false); // Assign Emit("MOV(021) &" + value + " " + address, true); } private void declareTimer(String name, int value){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tBOOL\t" + address + ".00\t\t0\t", false); // Assign Emit("MOV(021) &" + value + " " + address, true); } @Override public void outADefaultStatement(ADefaultStatement node){ //throw new NotImplementedException(); } @Override public void inAFunctionCallExpr(AFunctionCallExpr node){ SymbolFunction function = (SymbolFunction) currentScope.getSymbolOrThrow(node.getName().getText(), node); if (function.getReturnType().equals(SymbolType.Type.Void)) { Emit("SBS(091) " + getFunctionNumber(true), true); } else { Emit("MCRO(099) " + (getFunctionNumber(false) + 1) + " " + getNextDAddress(true) + " " + pop(), true); } //Emit("SBS(091) " + getFunctionNumber(true), true); } @Override public void inAFunctionRootDeclaration(AFunctionRootDeclaration node){ super.inAFunctionRootDeclaration(node); Emit("SBN(092) " + getFunctionNumber(true), true); if (!node.getStatements().isEmpty()) Emit("LD P_First_Cycle", true); //returnlabel = getNextJump(); } @Override public void outAFunctionRootDeclaration(AFunctionRootDeclaration node) { super.outAFunctionRootDeclaration(node); //Emit("JME(005) #" + returnlabel, true); Emit("RET(093)", true); //Emit("END(001)", true); } @Override public void outAIdentifierExpr(AIdentifierExpr node){ push(node.getName().getText()); } @Override public void outAMemberExpr(AMemberExpr node){ //throw new NotImplementedException(); } @Override public void outANegationExpr(ANegationExpr node){ super.outANegationExpr(node); Emit("NOT " + getNextDAddress(false), true); } @Override public void outAPortAnalogInputExpr(APortAnalogInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortAnalogOutputExpr(APortAnalogOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortInputExpr(APortInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortOutputExpr(APortOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAReturnStatement(AReturnStatement node){ super.outAReturnStatement(node); //Emit("JMP(004) #" + returnlabel, true); //Emit("RET(093)", true); } @Override public void outASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void outATrueExpr(ATrueExpr node){ super.outATrueExpr(node); Emit("MOV(021) #1 " + getNextDAddress(true), true); } @Override public void outAFalseExpr(AFalseExpr node){ super.outAFalseExpr(node); Emit("MOV(021) #0 " + getNextDAddress(true), true); } @Override public void outATypeCastExpr(ATypeCastExpr node){ //throw new NotImplementedException(); } @Override public void caseABranchStatement(ABranchStatement node) { //Do not call super as this function handles calls of the child classes if (node.getRight() != null) { // If - else statement int ifLabel = getNextJump(); int elseLabel = getNextJump(); node.getCondition().apply(this); Emit("CJP(510) #" + ifLabel, true); node.getRight().apply(this); Emit("JMP(004) #" + elseLabel, true); Emit("JME(005) #" + ifLabel, true); node.getLeft().apply(this); Emit("JME(005) #" + elseLabel, true); } else { // If statement int label = getNextJump(); node.getCondition().apply(this); Emit("CJPN(511) #" + label, true); node.getLeft().apply(this); Emit("JME(005) #" + label, true); } } @Override public void caseASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void caseAWhileStatement(AWhileStatement node){ int jumpLabel = getNextJump(); int loopLabel = getNextJump(); //node.getCondition().apply(this); Emit("LDNOT " + getNextWAddress(true), true); Emit("JMP(004) #" + jumpLabel, true); node.getStatement().apply(this); node.getCondition().apply(this); Emit("JME(005) #" + jumpLabel, true); } @Override public void outAIntegerExpr(AIntegerExpr node) { super.outAIntegerExpr(node); push(Integer.parseInt(node.getIntegerLiteral().getText())); // TODO Ouch, a hack... } @Override public void outADecimalExpr(ADecimalExpr node) { super.outADecimalExpr(node); push(node.getDecimalLiteral()); } @Override public void outAAddExpr(AAddExpr node) { super.outAAddExpr(node); // TODO Different if float Emit("+(400) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outADivExpr(ADivExpr node) { super.outADivExpr(node); // TODO Different if float Emit("/(430) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outAMultiExpr(AMultiExpr node) { super.outAMultiExpr(node); // TODO Different if float Emit("*(420) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outASubExpr(ASubExpr node) { super.outASubExpr(node); // TODO Different if float Emit("-(410) " + pop() + " " + pop() + " " + stackPointer(true), true); } private int getNextJump(){ jumpLabel = jumpLabel + 1; if(jumpLabel > 255) throw new IndexOutOfBoundsException(); return jumpLabel; } protected void Emit(String s, boolean instruction){ if (instruction == true) { // Write to InstructionList, if instruction instructionWriter.println(s); } else { // Otherwise it's a symbol, then write to SymbolList symbolWriter.println(s); } } }
package dyvilx.tools.compiler.ast.header; import dyvil.reflect.Modifiers; import dyvilx.tools.compiler.DyvilCompiler; import dyvilx.tools.compiler.ast.classes.IClass; import dyvilx.tools.compiler.ast.consumer.IClassConsumer; import dyvilx.tools.compiler.ast.structure.Package; import dyvilx.tools.compiler.parser.DyvilSymbols; import dyvilx.tools.compiler.parser.header.SourceFileParser; import dyvilx.tools.compiler.sources.DyvilFileType; import dyvilx.tools.parsing.ParserManager; import java.io.File; public class ClassUnit extends SourceHeader implements IClassConsumer { public ClassUnit(DyvilCompiler compiler, Package pack, File input, File output) { super(compiler, pack, input, output); } @Override protected boolean needsDefaultHeaderDeclaration() { // class units need an implicit header declaration if they contain at least one extension class or a class with // a custom bytecode name, otherwise those classes cannot be resolved correctly by the external class resolution // algorithms in the Package class. for (IClass iclass : this.classes) { if (iclass.hasModifier(Modifiers.EXTENSION) || !iclass.getInternalName().endsWith('/' + iclass.getName().qualified)) { return true; } } return false; } @Override protected int getDefaultHeaderDeclarationVisibility() { return Modifiers.PRIVATE; } @Override public void parse() { new ParserManager(DyvilSymbols.INSTANCE, this.tokens.iterator(), this.markers) .parse(new SourceFileParser(this)); this.tokens = null; } @Override protected boolean printMarkers() { return ICompilationUnit .printMarkers(this.compiler, this.markers, DyvilFileType.DYVIL_UNIT, this.name, this.fileSource); } }
package dk.aau.sw402F15.CodeGenerator; import dk.aau.sw402F15.parser.analysis.DepthFirstAdapter; import dk.aau.sw402F15.parser.node.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class CodeGenerator extends DepthFirstAdapter { int jumpLabel = 0; PrintWriter instructionWriter; PrintWriter symbolWriter; public CodeGenerator() { try { instructionWriter = new PrintWriter("InstructionList.txt", "UTF-8"); symbolWriter = new PrintWriter("SymbolList.txt", "UTF-8"); Emit("LD P_First_Cycle", true); Emit("SSET(630) W0 5", true); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void outStart(Start node){ instructionWriter.close(); symbolWriter.close(); } @Override public void caseAArrayDefinition(AArrayDefinition node){ //throw new NotImplementedException(); } @Override public void caseAArrayExpr(AArrayExpr node){ //throw new NotImplementedException(); } @Override public void caseADeclaration(ADeclaration node){ super.caseADeclaration(node); } @Override public void outABreakStatement(ABreakStatement node){ //throw new NotImplementedException(); } @Override public void outACaseStatement(ACaseStatement node){ //throw new NotImplementedException(); } @Override public void outACompareAndExpr(ACompareAndExpr node){ super.outACompareAndExpr(node); PopFromStack(); Emit("LD b1", true); Emit("AND b2", true); Emit("SET b1", true); } @Override public void outACompareEqualExpr(ACompareEqualExpr node){ super.outACompareEqualExpr(node); PopFromStack(); Emit("=(300) r1 r2", true); } @Override public void outACompareGreaterExpr(ACompareGreaterExpr node){ super.outACompareGreaterExpr(node); PopFromStack(); Emit(">(320) r1 r2", true); } @Override public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node){ super.outACompareGreaterOrEqualExpr(node); PopFromStack(); Emit(">=(325) r1 r2", true); } @Override public void outACompareLessExpr(ACompareLessExpr node){ super.outACompareLessExpr(node); PopFromStack(); Emit("<(310) r1 r2", true); } @Override public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node){ super.outACompareLessOrEqualExpr(node); PopFromStack(); Emit("<=(315) r1 r2", true); } @Override public void outACompareNotEqualExpr(ACompareNotEqualExpr node){ super.outACompareNotEqualExpr(node); PopFromStack(); Emit("<>(305) r1 r2", true); } @Override public void outACompareOrExpr(ACompareOrExpr node){ super.outACompareOrExpr(node); PopFromStack(); Emit("LD b1", true); Emit("OR b2", true); Emit("SET b1", true); } @Override public void outAContinueStatement(AContinueStatement node){ //throw new NotImplementedException(); } @Override public void outADeclaration(ADeclaration node){ //throw new NotImplementedException(); } @Override public void outADefaultStatement(ADefaultStatement node){ //throw new NotImplementedException(); } @Override public void outAFalseExpr(AFalseExpr node){ //throw new NotImplementedException(); } @Override public void outAFunctionCallExpr(AFunctionCallExpr node){ //throw new NotImplementedException(); } @Override public void outAFunctionRootDeclaration(AFunctionRootDeclaration node){ //throw new NotImplementedException(); } @Override public void outAIdentifierExpr(AIdentifierExpr node){ //throw new NotImplementedException(); } @Override public void outAMemberExpr(AMemberExpr node){ //throw new NotImplementedException(); } @Override public void outANegationExpr(ANegationExpr node){ super.outANegationExpr(node); PopFromStack(); Emit("NOT r1", true); } @Override public void outAPortAnalogInputExpr(APortAnalogInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortAnalogOutputExpr(APortAnalogOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortInputExpr(APortInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortMemoryExpr(APortMemoryExpr node){ //throw new NotImplementedException(); } @Override public void outAPortOutputExpr(APortOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAReturnStatement(AReturnStatement node){ //throw new NotImplementedException(); } @Override public void outASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void outATrueExpr(ATrueExpr node){ //throw new NotImplementedException(); } @Override public void outATypeCastExpr(ATypeCastExpr node){ //throw new NotImplementedException(); } @Override public void outAWhileStatement(AWhileStatement node) { //throw new NotImplementedException(); } @Override public void caseABranchStatement(ABranchStatement node) { super.caseABranchStatement(node); if (node.getRight() != null) { // If - else statement int ifLabel = getNextJump(); int elseLabel = getNextJump(); node.getCondition().apply(this); Emit("CJP(510) #" + ifLabel, true); node.getRight().apply(this); Emit("JMP(004) #" + elseLabel, true); Emit("JME(005) #" + ifLabel, true); node.getLeft().apply(this); Emit("JME(005) #" + elseLabel, true); } else { // If statement int label = getNextJump(); node.getCondition().apply(this); Emit("CJPN(511) #" + label, true); node.getLeft().apply(this); Emit("JME(005) #" + label, true); } } @Override public void caseAForStatement(AForStatement node){ int jumpLabel = getNextJump(); int loopLabel = getNextJump(); { List<PExpr> copy = new ArrayList<PExpr>(node.getInitilizer()); for(PExpr e : copy) { e.apply(this); } } Emit("JMP(004) #" + jumpLabel, true); Emit("JME(005) #" + loopLabel, true); node.getStatement().apply(this); { List<PExpr> copy = new ArrayList<PExpr>(node.getIterator()); for(PExpr e : copy) { e.apply(this); } } Emit("JME(005) #" + jumpLabel, true); node.getCondition().apply(this); Emit("CJP(510) #" + loopLabel, true); } @Override public void caseASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void caseAWhileStatement(AWhileStatement node){ int jumpLabel = getNextJump(); int loopLabel = getNextJump(); Emit("JMP(004) #" + jumpLabel, true); Emit("JME(005) #" + loopLabel, true); node.getStatement().apply(this); Emit("JME(005) #" + jumpLabel, true); node.getCondition().apply(this); Emit("CJP(510) #" + loopLabel, true); } @Override public void outAIntegerExpr(AIntegerExpr node) { super.outAIntegerExpr(node); Emit("PUSH(632) W0 #" + node.getIntegerLiteral().getText(), true); } @Override public void outADecimalExpr(ADecimalExpr node) { super.outADecimalExpr(node); Emit("PUSH(632) W0 #" + node.getDecimalLiteral().getText(), true); } @Override public void outAAddExpr(AAddExpr node) { super.outAAddExpr(node); PopFromStack(); Emit("+(400) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } @Override public void outADivExpr(ADivExpr node) { super.outADivExpr(node); PopFromStack(); Emit("/(430) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } @Override public void outAMultiExpr(AMultiExpr node) { super.outAMultiExpr(node); PopFromStack(); Emit("*(420) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } @Override public void outASubExpr(ASubExpr node) { super.outASubExpr(node); PopFromStack(); Emit("-(410) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } private void PopFromStack() { Emit("r1\tINT\tW4\t\t0", false); Emit("r2\tINT\tW5\t\t0", false); Emit("LIFO(634) W0 r1", true); Emit("LIFO(634) W0 r2", true); } private int getNextJump(){ jumpLabel = jumpLabel + 1; if(jumpLabel > 255) throw new IndexOutOfBoundsException(); return jumpLabel; } protected void Emit(String s, boolean inst){ if (inst == true) { instructionWriter.println(s); } else { symbolWriter.println(s); } } }
package com.example.androidhive; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.androidhive.library.DatabaseHandler; import com.example.androidhive.library.UserFunctions; public class RoomsActivity extends Activity { List<Button> rooms; Button btnNewRoom; Button btnChangeAddr; Button btnLogout; EditText inputAddr; UserFunctions userFunctions; private static String address; private static String dbID; private static String KEY_SUCCESS = "success"; private static String KEY_ERROR = "error"; private static String KEY_ERROR_MSG = "error_msg"; private static String KEY_TUPLE = "tuples"; private static String KEY_IDROOM = "idRoom"; private static String KEY_ROOMNAME = "name"; private static String KEY_ROOMURL = "roomURL"; private static String KEY_IDPROPERTY = "idProperty"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rooms); rooms = new ArrayList<Button>(); // may need to account for newly registered user here Intent intent = getIntent(); // pull info from previous page address = intent.getStringExtra("addr"); inputAddr = (EditText) findViewById(R.id.addr); inputAddr.setText(address); userFunctions = new UserFunctions(); dbID = intent.getStringExtra("id"); btnChangeAddr = (Button) findViewById(R.id.btnUpdateP); // make database call final UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.getRooms(dbID); //lists of recieved data List<Integer> idRoom = new ArrayList<Integer>(); List<String> roomName = new ArrayList<String>(); List<String> roomURL = new ArrayList<String>(); try { if (json.getString(KEY_SUCCESS) != null) { //loginErrorMsg.setText(""); String res = json.getString(KEY_SUCCESS); if(Integer.parseInt(res) == 1){ JSONArray tuples = json.getJSONArray(KEY_TUPLE); for(int i = 0; i< tuples.length(); i++){ JSONObject curTuple = tuples.getJSONObject(i); idRoom.add(curTuple.getInt(KEY_IDROOM)); roomName.add(curTuple.getString(KEY_ROOMNAME)); roomURL.add(curtuple.getString(KEY_ROOMURL)); } } } } catch (JSONException e) { e.printStackTrace(); } // fill xml based on db call LinearLayout ll = (LinearLayout) findViewById(R.id.roomsLayout); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // may need separate file for(int i = 0; i < idRoom.size(); i++) { Button btn = new Button(this); btn.setId(i); final int id_ = btn.getId(); // set text to address btn.setText(roomName.get(i).toString()); ll.addView(btn, params); // fill properties based on db call rooms.add((Button) findViewById(id_)); } //new room button Button newRoom = new Button(this); newRoom.setId(idRoom.size()); newRoom.setText("Add new room +"); ll.addView(newRoom, params); btnNewRoom = (Button) findViewById(idRoom.size()); //logout button Button logout = new Button(this); logout.setId(idRoom.size()+1); logout.setText("Logout"); ll.addView(logout, params); btnLogout = (Button) findViewById(idRoom.size()+1); btnChangeAddr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // change address name in database String newAddr = inputAddr.getText().toString(); userFunctions.renameHome(dbID,newAddr); } }); for(int i = 0; i < rooms.size(); i++) { final String name = roomName.get(i); final Integer id = idRoom.get(i); rooms.get(i).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // go to next page with given room selected Intent next = new Intent(getApplicationContext(), EditActivity.class); next.putExtra("name", name); next.putExtra("id",id.toString()); startActivity(next); } }); } btnNewRoom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // create new room and go to edit page JSONObject jsonID = userFunctions.addRoom("New Room",dbID,null); Integer value = -1; try { value = jsonID.getJSONArray(KEY_TUPLE).getJSONObject(0).getInt(KEY_IDROOM); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent next = new Intent(getApplicationContext(), EditActivity.class); next.putExtra("name", "New Room"); next.putExtra("id",value.toString()); startActivity(next); } }); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { userFunctions.logoutUser(getApplicationContext()); Intent login = new Intent(getApplicationContext(), LoginActivity.class); login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(login); // Closing rooms screen finish(); } }); } }
package dr.app.tools; import dr.app.util.Arguments; import dr.inference.trace.TraceException; import jebl.evolution.io.ImportException; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Andrew Rambaut * @author Marc A. Suchard * @version $Id$ */ public class JumpHistoryAnalyser { private int binCount; private double minTime; private double maxTime; private double ageOfYoungest; public JumpHistoryAnalyser(String inputFileName, Set<String> fromStates, Set<String> toStates, boolean iterateFrom, boolean iterateTo, int burnin, int binCount, double minTime, double maxTime, boolean backwardsTime, double ageOfYoungest) throws IOException, ImportException, TraceException { this.binCount = binCount; this.minTime = minTime; this.maxTime = maxTime; this.ageOfYoungest = ageOfYoungest; double delta = (maxTime - minTime) / (binCount - 1); Set<Set<String>> fromSets = new HashSet<Set<String>>(); // if a particular set of from states is specified then use them if (fromStates.size() > 0) { if (iterateFrom) { for (String state : fromStates) { Set<String> set = new HashSet<String>(); set.add(state); fromSets.add(set); } } else { fromSets.add(fromStates); } } // if a particular set of to states is specified then use them Set<Set<String>> toSets = new HashSet<Set<String>>(); if (toStates.size() > 0) { if (iterateTo) { for (String state : toStates) { Set<String> set = new HashSet<String>(); set.add(state); toSets.add(set); } } else { toSets.add(toStates); } } Pattern pattern = Pattern.compile("\\[([^:]+):([^:]+):([^\\]]+)\\]"); Set<String> allStates = new HashSet<String>(); if (fromSets.size() == 0 || toSets.size() == 0) { // from or to states have not been specified so parse file to get full set. BufferedReader reader = new BufferedReader(new FileReader(inputFileName)); String line = reader.readLine(); while (line != null && line.startsWith(" line = reader.readLine(); } // read heading line line = reader.readLine(); // read next line line = reader.readLine(); while (line != null) { String[] columns = line.split("\t"); if (columns.length == 3) { Matcher matcher = pattern.matcher(columns[2]); while (matcher.find()) { String fromState = matcher.group(1); allStates.add(fromState); String toState = matcher.group(2); allStates.add(toState); } } line = reader.readLine(); } reader.close(); } if (fromStates.size() == 0) { // if particular from states have not been specified, use them all if (iterateFrom) { for (String state : allStates) { Set<String> set = new HashSet<String>(); set.add(state); fromSets.add(set); } } else { fromSets.add(allStates); } } if (toStates.size() == 0) { // if particular to states have not been specified, use them all if (iterateTo) { for (String state : allStates) { Set<String> set = new HashSet<String>(); set.add(state); toSets.add(set); } } else { toSets.add(allStates); } } int fromSetCount = fromSets.size(); int toSetCount = toSets.size(); int[][][] bins = new int[fromSetCount][toSetCount][binCount]; Set<Double>[][] allTimes = new Set[fromSetCount][toSetCount]; for (int i = 0; i < fromSetCount; ++i) { for (int j = 0; j < toSetCount; ++j) { allTimes[i][j] = new HashSet<Double>(); } } int index = 0; Map<Set<String>, Integer> fromSetIndices = new HashMap<Set<String>, Integer>(); for (Set<String> fromSet : fromSets) { fromSetIndices.put(fromSet, index); index++; } index = 0; Map<Set<String>, Integer> toSetIndices = new HashMap<Set<String>, Integer>(); for (Set<String> toSet : toSets) { toSetIndices.put(toSet, index); index++; } BufferedReader reader = new BufferedReader(new FileReader(inputFileName)); String line = reader.readLine(); while (line != null && line.startsWith(" line = reader.readLine(); } // read heading line line = reader.readLine(); // read next line line = reader.readLine(); while (line != null) { String[] columns = line.split("\t"); if (columns.length == 3) { int state = Integer.parseInt(columns[0]); int count = (int)Double.parseDouble(columns[1]); if (state >= burnin) { Matcher matcher = pattern.matcher(columns[2]); while (matcher.find()) { String fromState = matcher.group(1); String toState = matcher.group(2); String timeString = matcher.group(3); Set<String> fromSet = null; for (Set<String> set : fromSets) { if (set.contains(fromState)) { fromSet = set; break; } } if (fromSet != null) { int fromIndex = fromSetIndices.get(fromSet); Set<String> toSet = null; for (Set<String> set : toSets) { if (set.contains(toState)) { toSet = set; break; } } if (toSet != null) { int toIndex = toSetIndices.get(toSet); double time = Double.parseDouble(timeString); if (!backwardsTime) { time = ageOfYoungest - time; } (allTimes[fromIndex][toIndex]).add(time); double binTime = minTime; int bin = -1; while (time > binTime) { binTime += delta; bin ++; } try { bins[fromIndex][toIndex][bin] ++; } catch (Exception e) { System.err.println("Caught error: " + e.getMessage()); System.err.println(fromState + " ->" + toState + ": " + timeString); System.err.println("Min time: " + minTime); System.err.println("Max time: " + maxTime); System.err.println("Bin est : " + bin); System.err.println("Delta : " + delta); } } } // System.out.println(fromState + " ->" + toState + ": " + timeString); } } } line = reader.readLine(); } reader.close(); boolean allToAllCounts = false; boolean useBinning = true; System.out.print("time"); for (Set<String> fromSet : fromSets) { String fromLabel = "all"; if (fromSet.size() == 1) { fromLabel = fromSet.toArray(new String[1])[0]; } else if (!fromSet.equals(allStates)) { StringBuilder sb = new StringBuilder("{"); boolean first = true; for (String state : fromSet) { if (!first) { sb.append(","); } else { first = false; } sb.append(state); } sb.append("}"); fromLabel = sb.toString(); } for (Set<String> toSet : toSets) { String toLabel = "all"; if (toSet.size() == 1) { toLabel = toSet.toArray(new String[1])[0]; } else if (!toSet.equals(allStates)) { StringBuilder sb = new StringBuilder("{"); boolean first = true; for (String state : toSet) { if (!first) { sb.append(","); } else { first = false; } sb.append(state); } sb.append("}"); toLabel = sb.toString(); } allToAllCounts = (fromLabel.equals("all") && toLabel.equals("all")); if (!fromLabel.equals(toLabel) || allToAllCounts ) { System.out.print("\t" + fromLabel + "->" + toLabel); } } } System.out.println(); if (useBinning) { double time = minTime; for (int bin = 0; bin < binCount; bin++) { System.out.print(time); for (Set<String> fromSet : fromSets) { int fromIndex = fromSetIndices.get(fromSet); for (Set<String> toSet : toSets) { int toIndex = toSetIndices.get(toSet); if ((fromIndex != toIndex) || allToAllCounts) { System.out.print("\t" + bins[fromIndex][toIndex][bin]); } } } System.out.println(); time += delta; } } else { for (Set<String> fromSet : fromSets) { int fromIndex = fromSetIndices.get(fromSet); for (Set<String> toSet: toSets) { int toIndex = toSetIndices.get(toSet); for (Double time : (allTimes[fromIndex][toIndex])) { System.out.println(time); } } } } } public static void printUsage(Arguments arguments) { arguments.printUsage("jumphistoryanalyser", "<input-file-name> [<output-file-name>]"); System.out.println(); System.out.println(" Example: jumphistoryanalyser -burnin 100000 -min 1950 -max 2010 -mrsd 2009.9 jumps.txt"); System.out.println(" Example: jumphistoryanalyser -burnin 100000 -from \"usa\" -to \"uk,fr\" -min 1950 -max 2010 -mrsd 2009.9 jumps.txt"); System.out.println(); } public static void main(String[] args) { String inputFileName = null; // printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.StringOption("from", "from_states", "set of 'from' states to limit the history [default all states]"), new Arguments.StringOption("to", "to_states", "set of 'to' states to limit the history [default all states]"), new Arguments.Option("iterateFrom", "iterate over 'from' states [default combine states]"), new Arguments.Option("iterateTo", "iterate over 'to' states [default combine states]"), new Arguments.Option("backwardsTime", "time runs backwards [default false]"), new Arguments.IntegerOption("bins", "the number of discrete bins [default 100]"), new Arguments.RealOption("min", "the minimum bound of the time range"), new Arguments.RealOption("max", "the maximum bound of the time range"), new Arguments.RealOption("mrsd", "the date of the most recently sampled tip"), new Arguments.Option("help", "option to print this message"), }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.err.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } int burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } int binCount = 100; if (arguments.hasOption("bins")) { binCount = arguments.getIntegerOption("bins"); } double minTime = arguments.getRealOption("min"); double maxTime = arguments.getRealOption("max"); if (minTime >= maxTime) { System.err.println("The minimum time must be less than the maximum time"); printUsage(arguments); System.exit(1); } double mrsd = arguments.getRealOption("mrsd"); Set<String> fromStates = new HashSet<String>(); Set<String> toStates = new HashSet<String>(); if (arguments.hasOption("from")) { String stateString = arguments.getStringOption("from"); String[] states = stateString.split("[\"\\s,]"); for (String state : states) { if (state.length() > 0) { fromStates.add(state); } } } if (arguments.hasOption("to")) { String stateString = arguments.getStringOption("to"); String[] states = stateString.split("[\"\\s,]"); for (String state : states) { if (state.length() > 0) { toStates.add(state); } } } boolean iterateFrom = arguments.hasOption("iterateFrom"); boolean iterateTo = arguments.hasOption("iterateTo"); boolean backwardsTime = arguments.hasOption("backwardsTime"); final String[] args2 = arguments.getLeftoverArguments(); switch (args2.length) { case 1: inputFileName = args2[0]; break; default: { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } } // command line options to follow shortly... try { JumpHistoryAnalyser jumpHistory = new JumpHistoryAnalyser( inputFileName, fromStates, toStates, iterateFrom, iterateTo, burnin, binCount, minTime, maxTime, backwardsTime, mrsd ); } catch (IOException e) { e.printStackTrace(); } catch (ImportException e) { e.printStackTrace(); } catch (TraceException e) { e.printStackTrace(); } System.exit(0); } }
/* Currently managed by: Levi Rabi * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.ames.frc.robot; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Watchdog; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; // test public class Communication { }
package edu.jhu.thrax.util; import java.util.Scanner; import java.util.HashSet; import java.io.IOException; import java.io.File; import edu.jhu.thrax.ThraxConfig; public class TestSetFilter { private static HashSet<String> testSentences; private static final String NT_REGEX = "\\[[^\\]]+?\\]"; private static void getTestSentences(String filename) throws IOException { if (testSentences == null) { testSentences = new HashSet<String>(); } Scanner scanner = new Scanner(new File(filename), "UTF-8"); while (scanner.hasNextLine()) { testSentences.add(scanner.nextLine()); } } private static boolean inTestSet(String rule) { String [] parts = rule.split(ThraxConfig.DELIMITER_REGEX); if (parts.length != 4) { System.err.printf("malformed rule: %s\n", rule); return false; } String source = parts[1].trim(); String pattern = source.replaceAll(NT_REGEX, "\\\\E.+\\\\Q"); pattern = "(.+ )?\\Q" + pattern + "\\E( .+)?"; // System.err.println("pattern is " + pattern); for (String s : testSentences) { if (s.matches(pattern)) { return true; } } return false; } public static void main(String [] argv) throws IOException { // do some setup if (argv.length < 1) { System.err.println("usage: TestSetFilter <test set1> [test set2 ...]"); return; } for (int i = 0; i < argv.length; i++) { getTestSentences(argv[i]); } Scanner scanner = new Scanner(System.in, "UTF-8"); int rulesIn = 0; int rulesOut = 0; while (scanner.hasNextLine()) { rulesIn++; String rule = scanner.nextLine(); if (inTestSet(rule)) { System.out.println(rule); rulesOut++; } } System.err.println("[INFO] Total rules read: " + rulesIn); System.err.println("[INFO] Rules kept: " + rulesOut); System.err.println("[INFO] Rules dropped: " + (rulesIn - rulesOut)); return; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mod.fin.form; import erp.client.SClientInterface; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.data.SDataReadDescriptions; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.lib.SLibTimeUtilities; import erp.lib.SLibUtilities; import erp.lib.table.STableCellEditorOptions; import erp.lib.table.STableConstants; import erp.mbps.data.SDataBizPartner; import erp.mbps.data.SDataBizPartnerBranch; import erp.mbps.data.SDataBizPartnerBranchBankAccount; import erp.mfin.data.SDataAccountCash; import erp.mfin.data.SDataRecord; import erp.mfin.data.SFinUtilities; import erp.mfin.form.SDialogRecordPicker; import erp.mod.SModConsts; import erp.mod.SModSysConsts; import erp.mod.fin.db.SDbBankLayout; import erp.mod.fin.db.SFinConsts; import erp.mod.fin.db.SFinRecordLayout; import erp.mod.fin.db.SLayoutBankDps; import erp.mod.fin.db.SLayoutBankPayment; import erp.mod.fin.db.SLayoutBankPaymentRow; import erp.mod.fin.db.SLayoutBankRecord; import erp.mod.fin.db.SLayoutBankRow; import erp.mod.fin.db.SLayoutBankXmlRow; import erp.mod.fin.db.SMoney; import erp.mod.fin.db.SXmlBankLayout; import erp.mod.fin.db.SXmlBankLayoutPayment; import erp.mod.fin.db.SXmlBankLayoutPaymentDoc; import erp.mtrn.data.SDataDps; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Vector; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableRowSorter; import sa.gui.util.SUtilConsts; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.grid.SGridColumnForm; import sa.lib.grid.SGridConsts; import sa.lib.grid.SGridPaneForm; import sa.lib.grid.SGridRow; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiItem; import sa.lib.gui.SGuiParams; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; import sa.lib.gui.bean.SBeanForm; import sa.lib.srv.SSrvLock; import sa.lib.srv.SSrvUtils; import sa.lib.xml.SXmlElement; public class SFormLayoutBank extends SBeanForm implements ActionListener, ItemListener, CellEditorListener { private static final int COL_APP_PAY = 2; //Used for advance payments and acounting moves private static final int COL_APP = 5; private static final int COL_BAL = 7; private static final int COL_TC = 9; private static final int COL_APP_PAY_BANK = 10; private int mnLayout; private int mnLayoutType; private int mnLayoutSubtype; private int mnLayoutBank; private int mnCurrencyId; private double mdBalanceTot; private double mdBalancePayed; private int mnNumberDocs; private int mnNumberRecordDistint; private java.lang.String msAccountDebit; private java.lang.String msDebitFiscalId; private java.lang.String msAccountCredit; private ArrayList<SGuiItem> maAccountCredit; private ArrayList<SDataBizPartnerBranchBankAccount> maBranchBankAccountsCredit; private List<ArrayList<SGuiItem>> mltAccountCredit; private ArrayList<SLayoutBankXmlRow> maXmlRows = null; private erp.lib.table.STableCellEditorOptions moTableCellEditorOptions; private SLayoutBankRow moRow; private Vector<SLayoutBankRow> mvLayoutRows; private Vector<SGuiItem> mvLayoutTypes; private JButton jbActualExR; private JButton jbRefreshExR; private JButton jbSelectAll; private JButton jbCleanAll; private JCheckBox jckDateMaturityRo; private JCheckBox jckAccountAll; private SDbBankLayout moRegistry; private erp.mbps.data.SDataBizPartner moDataBizPartner; private erp.mfin.data.SDataAccountCash moDataAccountCash; private erp.mbps.data.SDataBizPartnerBranchBankAccount moDataBizPartnerBranchBankAccount; private erp.mfin.form.SDialogRecordPicker moDialogRecordPicker; private erp.mfin.data.SDataRecord moCurrentRecord; protected ArrayList<SLayoutBankRecord> maBankRecords; private SGridPaneForm moGridPayments; private HashMap<Integer, Object> moParamsMap; private ArrayList<SSrvLock> maLocks; /** * Creates new form SFormLayoutBank * @param client * @param formSubtype * @param title */ public SFormLayoutBank(SGuiClient client, int formSubtype, String title) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.FIN_LAY_BANK, formSubtype, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel23 = new javax.swing.JPanel(); jPanel24 = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jlDate = new javax.swing.JLabel(); moDateDate = new sa.lib.gui.bean.SBeanFieldDate(); jPanel12 = new javax.swing.JPanel(); jlFolio = new javax.swing.JLabel(); jtfRegistryNumber = new javax.swing.JTextField(); jPanel5 = new javax.swing.JPanel(); jlPkLayouId = new javax.swing.JLabel(); moKeyLayouId = new sa.lib.gui.bean.SBeanFieldKey(); jPanel6 = new javax.swing.JPanel(); jlPkBankLayoutTypeId = new javax.swing.JLabel(); moKeyBankLayoutType = new sa.lib.gui.bean.SBeanFieldKey(); jPanel8 = new javax.swing.JPanel(); jlCurrencyBank = new javax.swing.JLabel(); moKeyCurrencyBank = new sa.lib.gui.bean.SBeanFieldKey(); jPanel9 = new javax.swing.JPanel(); jlAccountDebit = new javax.swing.JLabel(); moKeyAccountDebit = new sa.lib.gui.bean.SBeanFieldKey(); jPanel10 = new javax.swing.JPanel(); jlExchangeRate = new javax.swing.JLabel(); moCurExchangeRate = new sa.lib.gui.bean.SBeanCompoundFieldCurrency(); jbExchangeRateSystemOrigin = new javax.swing.JButton(); jPanel11 = new javax.swing.JPanel(); jlRecord = new javax.swing.JLabel(); jtfRecordDate = new javax.swing.JTextField(); jtfRecordBranch = new javax.swing.JTextField(); jtfRecordBkc = new javax.swing.JTextField(); jtfRecordNumber = new javax.swing.JTextField(); jbPickRecord = new javax.swing.JButton(); jPanel15 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jlConsecutiveDay = new javax.swing.JLabel(); moIntConsecutiveDay = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel16 = new javax.swing.JPanel(); jlConcept = new javax.swing.JLabel(); moTextConcept = new sa.lib.gui.bean.SBeanFieldText(); jPanel17 = new javax.swing.JPanel(); jlLayoutPath = new javax.swing.JLabel(); moTextLayoutPath = new sa.lib.gui.bean.SBeanFieldText(); jbLayoutPath = new javax.swing.JButton(); jPanel18 = new javax.swing.JPanel(); jlCurrencyDoc = new javax.swing.JLabel(); moKeyCurrencyDoc = new sa.lib.gui.bean.SBeanFieldKey(); jPanel19 = new javax.swing.JPanel(); jlDateDue = new javax.swing.JLabel(); moDateDateDue = new sa.lib.gui.bean.SBeanFieldDate(); jPanel20 = new javax.swing.JPanel(); jPanel21 = new javax.swing.JPanel(); jbShowDocs = new javax.swing.JButton(); jbCleanDocs = new javax.swing.JButton(); jpSettings = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jtfRows = new javax.swing.JTextField(); jlDummy = new javax.swing.JLabel(); jlBalanceTot = new javax.swing.JLabel(); moDecBalanceTot = new sa.lib.gui.bean.SBeanFieldDecimal(); jlBalanceTotPay = new javax.swing.JLabel(); moDecBalanceTotPay = new sa.lib.gui.bean.SBeanFieldDecimal(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jPanel1.setLayout(new java.awt.BorderLayout(0, 5)); jPanel23.setPreferredSize(new java.awt.Dimension(511, 230)); jPanel23.setLayout(new java.awt.GridLayout(1, 0)); jPanel24.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:")); jPanel24.setPreferredSize(new java.awt.Dimension(511, 225)); jPanel24.setRequestFocusEnabled(false); jPanel24.setLayout(new java.awt.GridLayout(1, 0)); jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jPanel13.setPreferredSize(new java.awt.Dimension(411, 120)); jPanel13.setRequestFocusEnabled(false); jPanel13.setLayout(new java.awt.GridLayout(7, 1, 0, 5)); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDate.setText("Fecha apliación:"); jlDate.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel4.add(jlDate); moDateDate.setPreferredSize(new java.awt.Dimension(140, 23)); jPanel4.add(moDateDate); jPanel12.setPreferredSize(new java.awt.Dimension(77, 23)); jPanel12.setRequestFocusEnabled(false); jPanel4.add(jPanel12); jlFolio.setText("Folio: "); jPanel4.add(jlFolio); jtfRegistryNumber.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel4.add(jtfRegistryNumber); jPanel13.add(jPanel4); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlPkLayouId.setText("Layout: *"); jlPkLayouId.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel5.add(jlPkLayouId); moKeyLayouId.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel5.add(moKeyLayouId); jPanel13.add(jPanel5); jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlPkBankLayoutTypeId.setText("Tipo layout: *"); jlPkBankLayoutTypeId.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel6.add(jlPkBankLayoutTypeId); moKeyBankLayoutType.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel6.add(moKeyBankLayoutType); jPanel13.add(jPanel6); jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCurrencyBank.setText("Moneda: *"); jlCurrencyBank.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel8.add(jlCurrencyBank); moKeyCurrencyBank.setPreferredSize(new java.awt.Dimension(140, 23)); jPanel8.add(moKeyCurrencyBank); jPanel13.add(jPanel8); jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlAccountDebit.setText("Cuenta bancaria: *"); jlAccountDebit.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel9.add(jlAccountDebit); moKeyAccountDebit.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel9.add(moKeyAccountDebit); jPanel13.add(jPanel9); jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlExchangeRate.setText("Tipo de cambio:"); jlExchangeRate.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel10.add(jlExchangeRate); jPanel10.add(moCurExchangeRate); jbExchangeRateSystemOrigin.setText("..."); jbExchangeRateSystemOrigin.setToolTipText("Seleccionar tipo de cambio"); jbExchangeRateSystemOrigin.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel10.add(jbExchangeRateSystemOrigin); jPanel13.add(jPanel10); jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlRecord.setText("Póliza contable:"); jlRecord.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel11.add(jlRecord); jtfRecordDate.setEditable(false); jtfRecordDate.setText("01/01/2000"); jtfRecordDate.setToolTipText("Fecha de la póliza contable"); jtfRecordDate.setFocusable(false); jtfRecordDate.setPreferredSize(new java.awt.Dimension(65, 23)); jPanel11.add(jtfRecordDate); jtfRecordBranch.setEditable(false); jtfRecordBranch.setText("BRA"); jtfRecordBranch.setToolTipText("Sucursal de la empresa"); jtfRecordBranch.setFocusable(false); jtfRecordBranch.setPreferredSize(new java.awt.Dimension(32, 23)); jPanel11.add(jtfRecordBranch); jtfRecordBkc.setEditable(false); jtfRecordBkc.setText("BKC"); jtfRecordBkc.setToolTipText("Centro contable"); jtfRecordBkc.setFocusable(false); jtfRecordBkc.setPreferredSize(new java.awt.Dimension(32, 23)); jPanel11.add(jtfRecordBkc); jtfRecordNumber.setEditable(false); jtfRecordNumber.setText("TP-000001"); jtfRecordNumber.setToolTipText("Número de póliza contable"); jtfRecordNumber.setFocusable(false); jtfRecordNumber.setPreferredSize(new java.awt.Dimension(60, 23)); jPanel11.add(jtfRecordNumber); jbPickRecord.setText("..."); jbPickRecord.setToolTipText("Seleccionar póliza contable"); jbPickRecord.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel11.add(jbPickRecord); jPanel13.add(jPanel11); jPanel24.add(jPanel13); jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jPanel15.setPreferredSize(new java.awt.Dimension(511, 120)); jPanel15.setLayout(new java.awt.GridLayout(7, 1, 0, 5)); jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlConsecutiveDay.setText("Consecutivo día: *"); jlConsecutiveDay.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel7.add(jlConsecutiveDay); moIntConsecutiveDay.setPreferredSize(new java.awt.Dimension(140, 23)); jPanel7.add(moIntConsecutiveDay); jPanel15.add(jPanel7); jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlConcept.setText("Concepto/descripción:"); jlConcept.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel16.add(jlConcept); moTextConcept.setText("sBeanFieldText1"); moTextConcept.setPreferredSize(new java.awt.Dimension(275, 23)); jPanel16.add(moTextConcept); jPanel15.add(jPanel16); jPanel17.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlLayoutPath.setText("Ruta layout:*"); jlLayoutPath.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel17.add(jlLayoutPath); moTextLayoutPath.setEditable(false); moTextLayoutPath.setText("sBeanFieldText1"); moTextLayoutPath.setMaxLength(230); moTextLayoutPath.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel17.add(moTextLayoutPath); jbLayoutPath.setText("..."); jbLayoutPath.setToolTipText("Seleccionar ruta de archivo layout..."); jbLayoutPath.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel17.add(jbLayoutPath); jPanel15.add(jPanel17); jPanel18.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCurrencyDoc.setText("Moneda:*"); jlCurrencyDoc.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel18.add(jlCurrencyDoc); moKeyCurrencyDoc.setPreferredSize(new java.awt.Dimension(140, 23)); jPanel18.add(moKeyCurrencyDoc); jPanel15.add(jPanel18); jPanel19.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateDue.setText("Vencimiento:"); jlDateDue.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel19.add(jlDateDue); moDateDateDue.setPreferredSize(new java.awt.Dimension(140, 23)); jPanel19.add(moDateDateDue); jPanel15.add(jPanel19); jPanel20.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jPanel15.add(jPanel20); jPanel21.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jbShowDocs.setText("Mostar documentos"); jbShowDocs.setMargin(new java.awt.Insets(2, 0, 2, 0)); jbShowDocs.setPreferredSize(new java.awt.Dimension(115, 23)); jPanel21.add(jbShowDocs); jbCleanDocs.setText("Limpiar documentos"); jbCleanDocs.setMargin(new java.awt.Insets(2, 0, 2, 0)); jbCleanDocs.setPreferredSize(new java.awt.Dimension(115, 23)); jPanel21.add(jbCleanDocs); jPanel15.add(jPanel21); jPanel24.add(jPanel15); jPanel23.add(jPanel24); jPanel1.add(jPanel23, java.awt.BorderLayout.NORTH); jpSettings.setBorder(javax.swing.BorderFactory.createTitledBorder("Documentos con saldo:")); jpSettings.setLayout(new java.awt.BorderLayout()); jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jtfRows.setEditable(false); jtfRows.setText("000,000/000,000"); jtfRows.setToolTipText("Renglón actual"); jtfRows.setFocusable(false); jtfRows.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel2.add(jtfRows); jlDummy.setPreferredSize(new java.awt.Dimension(525, 23)); jPanel2.add(jlDummy); jlBalanceTot.setText("Total layout:"); jlBalanceTot.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel2.add(jlBalanceTot); jPanel2.add(moDecBalanceTot); jlBalanceTotPay.setText("Total pago:"); jlBalanceTotPay.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel2.add(jlBalanceTotPay); jPanel2.add(moDecBalanceTotPay); jpSettings.add(jPanel2, java.awt.BorderLayout.SOUTH); jPanel1.add(jpSettings, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); getAccessibleContext().setAccessibleDescription(""); }// </editor-fold>//GEN-END:initComponents private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing actionCancel(); }//GEN-LAST:event_formWindowClosing // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel16; private javax.swing.JPanel jPanel17; private javax.swing.JPanel jPanel18; private javax.swing.JPanel jPanel19; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel20; private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel23; private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JButton jbCleanDocs; private javax.swing.JButton jbExchangeRateSystemOrigin; private javax.swing.JButton jbLayoutPath; private javax.swing.JButton jbPickRecord; private javax.swing.JButton jbShowDocs; private javax.swing.JLabel jlAccountDebit; private javax.swing.JLabel jlBalanceTot; private javax.swing.JLabel jlBalanceTotPay; private javax.swing.JLabel jlConcept; private javax.swing.JLabel jlConsecutiveDay; private javax.swing.JLabel jlCurrencyBank; private javax.swing.JLabel jlCurrencyDoc; private javax.swing.JLabel jlDate; private javax.swing.JLabel jlDateDue; private javax.swing.JLabel jlDummy; private javax.swing.JLabel jlExchangeRate; private javax.swing.JLabel jlFolio; private javax.swing.JLabel jlLayoutPath; private javax.swing.JLabel jlPkBankLayoutTypeId; private javax.swing.JLabel jlPkLayouId; private javax.swing.JLabel jlRecord; private javax.swing.JPanel jpSettings; private javax.swing.JTextField jtfRecordBkc; private javax.swing.JTextField jtfRecordBranch; private javax.swing.JTextField jtfRecordDate; private javax.swing.JTextField jtfRecordNumber; private javax.swing.JTextField jtfRegistryNumber; private javax.swing.JTextField jtfRows; private sa.lib.gui.bean.SBeanCompoundFieldCurrency moCurExchangeRate; private sa.lib.gui.bean.SBeanFieldDate moDateDate; private sa.lib.gui.bean.SBeanFieldDate moDateDateDue; private sa.lib.gui.bean.SBeanFieldDecimal moDecBalanceTot; private sa.lib.gui.bean.SBeanFieldDecimal moDecBalanceTotPay; private sa.lib.gui.bean.SBeanFieldInteger moIntConsecutiveDay; private sa.lib.gui.bean.SBeanFieldKey moKeyAccountDebit; private sa.lib.gui.bean.SBeanFieldKey moKeyBankLayoutType; private sa.lib.gui.bean.SBeanFieldKey moKeyCurrencyBank; private sa.lib.gui.bean.SBeanFieldKey moKeyCurrencyDoc; private sa.lib.gui.bean.SBeanFieldKey moKeyLayouId; private sa.lib.gui.bean.SBeanFieldText moTextConcept; private sa.lib.gui.bean.SBeanFieldText moTextLayoutPath; // End of variables declaration//GEN-END:variables private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 1024, 640); moDialogRecordPicker = new SDialogRecordPicker((SClientInterface) miClient, SDataConstants.FINX_REC_USER); moDateDate.setDateSettings(miClient, SGuiUtils.getLabelName(jlDate.getText()), true); moKeyLayouId.setKeySettings(miClient, SGuiUtils.getLabelName(jlPkLayouId.getText()), true); moKeyBankLayoutType.setKeySettings(miClient, SGuiUtils.getLabelName(jlPkBankLayoutTypeId.getText()), true); moKeyAccountDebit.setKeySettings(miClient, SGuiUtils.getLabelName(jlAccountDebit.getText()), true); moTextConcept.setTextSettings(SGuiUtils.getLabelName(jlConcept), 255); moIntConsecutiveDay.setIntegerSettings(SGuiUtils.getLabelName(jlConsecutiveDay), SGuiConsts.GUI_TYPE_INT, true); moTextLayoutPath.setTextSettings(SGuiUtils.getLabelName(jlLayoutPath), 255); moDecBalanceTot.setDecimalSettings(SGuiUtils.getLabelName(jlBalanceTot), SGuiConsts.GUI_TYPE_DEC_AMT, false); moDecBalanceTotPay.setDecimalSettings(SGuiUtils.getLabelName(jlBalanceTotPay), SGuiConsts.GUI_TYPE_DEC_AMT, false); moDateDateDue.setDateSettings(miClient, SGuiUtils.getLabelName(jlDateDue.getText()), true); moKeyCurrencyDoc.setKeySettings(miClient, SGuiUtils.getLabelName(jlCurrencyDoc.getText()), true); moCurExchangeRate.setCompoundFieldSettings(miClient); moCurExchangeRate.getField().setDecimalSettings(SGuiUtils.getLabelName(jlExchangeRate.getText()), SGuiConsts.GUI_TYPE_DEC_EXC_RATE, true); moCurExchangeRate.getField().setValue(0d); moTableCellEditorOptions = new STableCellEditorOptions((SClientInterface) miClient); jbActualExR = new JButton("TC Original"); jbActualExR.setToolTipText("Poner de cambio original del documento"); jbActualExR.setMargin(new Insets (2,2,2,2)); jbActualExR.setPreferredSize(new java.awt.Dimension(85, 23)); jbRefreshExR = new JButton("TC Actualizar"); jbRefreshExR.setToolTipText("Poner tipo de cambio actual"); jbRefreshExR.setMargin(new Insets (2,2,2,2)); jbRefreshExR.setPreferredSize(new java.awt.Dimension(85, 23)); jbSelectAll = new JButton("Todo"); jbSelectAll.setToolTipText("Pagar"); jbSelectAll.setPreferredSize(new java.awt.Dimension(85, 23)); jbSelectAll = new JButton("Todo"); jbSelectAll.setToolTipText("Seleccionar todo"); jbSelectAll.setPreferredSize(new java.awt.Dimension(85, 23)); jbCleanAll = new JButton("Nada"); jbCleanAll.setToolTipText("Selecionar nada"); jbCleanAll.setPreferredSize(new java.awt.Dimension(85, 23)); jckDateMaturityRo = new JCheckBox("Solo documentos del vecimiento"); jckDateMaturityRo.setPreferredSize(new Dimension(200, 23)); jckAccountAll = new JCheckBox("Solo cuentas bancarias configuradas"); jckAccountAll.setPreferredSize(new Dimension(200, 23)); jtfRegistryNumber.setEditable(false); jtfRegistryNumber.setFocusable(false); moFields.addField(moDateDate); moFields.addField(moKeyLayouId); moFields.addField(moKeyBankLayoutType); moFields.addField(moKeyCurrencyBank); moFields.addField(moKeyAccountDebit); moFields.addField(moTextConcept); moFields.addField(moIntConsecutiveDay); moFields.addField(moTextLayoutPath); moFields.setFormButton(jbLayoutPath); moFields.addField(moKeyCurrencyDoc); moFields.addField(moDateDateDue); moFields.setFormButton(jbShowDocs); moFields.setFormButton(jbSave); moGridPayments = new SGridPaneForm(miClient, SModConsts.FIN_LAY_BANK, mnFormSubtype, "Documentos con saldo") { @Override public void initGrid() { setRowButtonsEnabled(false); } @Override public ArrayList<SGridColumnForm> createGridColumns() { ArrayList<SGridColumnForm> gridColumnsForm = new ArrayList<SGridColumnForm>(); SGridColumnForm column = null; if (mnFormSubtype == SModConsts.FIN_REC) { gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Proveedor", 300)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Clave proveedor", 50)); column = new SGridColumnForm(SGridConsts.COL_TYPE_BOOL_S, "Aplicar pago", moGridPayments.getTable().getDefaultEditor(Boolean.class)); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Monto pagar $")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CUR, "Moneda")); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "No. cuenta", 125); column.setApostropheOnCsvRequired(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_REG_PER, "Período póliza")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CO, "Centro contable")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CO, "Sucursal empresa")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CAT, "Folio póliza", 65)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Fecha póliza")); } else if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS) { gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Proveedor", 250)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_REG_NUM, "Tipo doc", 40)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Folio doc", 80)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Fecha doc")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Sucursal empresa", STableConstants.WIDTH_CODE_COB)); column = new SGridColumnForm(SGridConsts.COL_TYPE_BOOL_S, "Aplicar pago", 30); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Saldo mon $", STableConstants.WIDTH_VALUE_2X)); column = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Pago mon $", STableConstants.WIDTH_VALUE_2X); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CUR, "Moneda")); column = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_EXC_RATE, "TC", 60); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Pago mon cta $", STableConstants.WIDTH_VALUE_2X)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CUR, "Moneda cta")); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "No. cuenta", 125, moTableCellEditorOptions); column.setEditable(true); column.setApostropheOnCsvRequired(true); gridColumnsForm.add(column); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "E-mail", 100, moGridPayments.getTable().getDefaultEditor(String.class)); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "RFC", 100)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Subtotal $")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Impuesto trasladado $")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Impuesto retenido $")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Total doc $")); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_DATE, "Fecha vencimiento")); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Observaciones", 100, moGridPayments.getTable().getDefaultEditor(String.class)); column.setEditable(true); gridColumnsForm.add(column); } else { gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Proveedor", 300)); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Clave proveedor", 50)); column = new SGridColumnForm(SGridConsts.COL_TYPE_DEC_2D, "Monto pagar $", moGridPayments.getTable().getDefaultEditor(Double.class)); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT_CODE_CUR, "Moneda")); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "No. cuenta", 125, moTableCellEditorOptions); column.setEditable(true); column.setApostropheOnCsvRequired(true); gridColumnsForm.add(column); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "E-mail", 100, moGridPayments.getTable().getDefaultEditor(String.class)); column.setEditable(true); gridColumnsForm.add(column); gridColumnsForm.add(new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "RFC", 100)); column = new SGridColumnForm(SGridConsts.COL_TYPE_TEXT, "Observaciones", 100, moGridPayments.getTable().getDefaultEditor(String.class)); column.setEditable(true); gridColumnsForm.add(column); } moGridPayments.getTable().getDefaultEditor(Double.class).addCellEditorListener(SFormLayoutBank.this); moGridPayments.getTable().getDefaultEditor(Boolean.class).addCellEditorListener(SFormLayoutBank.this); moGridPayments.getTable().getDefaultEditor(String.class).addCellEditorListener(SFormLayoutBank.this); moTableCellEditorOptions.addCellEditorListener(SFormLayoutBank.this); return gridColumnsForm; } }; moGridPayments.getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jckDateMaturityRo); moGridPayments.getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jckAccountAll); moGridPayments.getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbActualExR); moGridPayments.getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbRefreshExR); moGridPayments.getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbSelectAll); moGridPayments.getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbCleanAll); jpSettings.add(moGridPayments, BorderLayout.CENTER); populateCatalogues(); } private boolean validateDebtsToPay() throws Exception { boolean isError = false; boolean isFound = false; int visibleRows = 0; double total = 0; Vector<SLayoutBankRow> vLayoutRows = new Vector<SLayoutBankRow>(); SLayoutBankRow row = null; updateLayoutRow(); for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { row = (SLayoutBankRow) rowAux; visibleRows = visibleRows + 1; for (int i = 0; i < mvLayoutRows.size(); i++) { if (SLibUtilities.compareKeys(row.getRowPrimaryKey(), mvLayoutRows.get(i).getRowPrimaryKey()) && mvLayoutRows.get(i).getIsForPayment()) { if (mvLayoutRows.get(i).getAccountCredit().length() > 0) { for (SLayoutBankRow layoutRow : vLayoutRows) { isFound = false; if (SLibUtilities.compareKeys(new int[] { layoutRow.getBizPartnerId(), }, new int[] { mvLayoutRows.get(i).getBizPartnerId() }) && layoutRow.getAccountCredit().compareTo(mvLayoutRows.get(i).getAccountCredit()) == 0) { total = layoutRow.getBalanceTotByBizPartner(); layoutRow.setBalanceTotByBizPartner(total + mvLayoutRows.get(i).getBalanceTotByBizPartner()); isFound = true; } if (isFound) { break; } } if (!isFound) { vLayoutRows.add(mvLayoutRows.get(i)); } } else { isError = true; throw new Exception("No ha especificado la cuenta de abono para uno o mas pagos."); } if (mvLayoutRows.get(i).getBalanceTot().getExchangeRate() == 0) { isError = true; throw new Exception("No ha especificado el tipo de cambio el renglon : " + visibleRows); } if (SLibUtilities.textTrim(mvLayoutRows.get(i).getObservation()).isEmpty() && mnFormSubtype == SModSysConsts.FIN_LAY_BANK_ADV) { isError = true; throw new Exception("No ha especificado observaciones para el renglon : " + visibleRows); } } } if (isError) { break; } } // Validate "alias" for payment with BanBajio Bank if (mnLayout == SFinConsts.LAY_BANK_BANBAJIO) { for (SLayoutBankRow layoutRow : vLayoutRows) { if (layoutRow.getBajioBankAlias().isEmpty()) { isError = true; throw new Exception("No se ha especificado el 'alias ' de la cuenta de abono '" + layoutRow.getAccountCredit() + "' del proveedor '" + layoutRow.getBizPartner() + "'."); } } } if (vLayoutRows.size() <= 0) { throw new Exception("No ha especificado ningún documento para pago."); } return true; } private boolean validateRecord(final boolean isSelectedAll) throws Exception { SLayoutBankPaymentRow payRow = null; mnNumberRecordDistint = 0; if (moCurrentRecord == null) { jbPickRecord.requestFocus(); throw new Exception(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(jlRecord) + "'."); } else if (isSelectedAll) { for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { payRow = (SLayoutBankPaymentRow) rowAux; if (payRow.getIsForPayment()) { if (payRow.getFinRecordLayout() != null) { if (!SLibUtils.compareKeys(payRow.getFinRecordLayout().getPrimaryKey(), moCurrentRecord.getPrimaryKey())) { mnNumberRecordDistint++; } } } } for (SLayoutBankRecord bankRecordRow : maBankRecords) { if (!SLibUtils.compareKeys(bankRecordRow.getFinRecordLayout().getPrimaryKey(), moCurrentRecord.getPrimaryKey())) { mnNumberRecordDistint++; } } if (mnNumberRecordDistint != 0) { if (miClient.showMsgBoxConfirm("Existen '" + mnNumberRecordDistint + "' transferencias en pólizas distintas, a las cuáles se la reemplazará la póliza por la '" + moCurrentRecord.getRecordPeriod() + "-" + moCurrentRecord.getRecordNumber() + "'.\n" + SGuiConsts.MSG_CNF_CONT) == JOptionPane.NO_OPTION) { throw new Exception("Existen '" + mnNumberRecordDistint + "' transferencias en pólizas distintas."); } } } return true; } private void enableGeneralFields(boolean enable) { jbPickRecord.setEnabled(false); moDateDate.setEnabled(true); moKeyCurrencyBank.setEnabled(!enable); moKeyLayouId.setEnabled(enable); moKeyBankLayoutType.setEnabled(enable); jbShowDocs.setEnabled(enable); jbCleanDocs.setEnabled(!enable); jckDateMaturityRo.setEnabled(!enable); jckAccountAll.setEnabled(!enable); moDateDateDue.setEditable(enable); moKeyCurrencyDoc.setEnabled(enable); moTextConcept.setEditable(enable); moIntConsecutiveDay.setEditable(enable); if (mnFormSubtype == SModConsts.FIN_REC) { jbPickRecord.setEnabled(true); moDateDate.setEditable(false); moKeyAccountDebit.setEnabled(false); moTextConcept.setEditable(false); moIntConsecutiveDay.setEditable(false); jbLayoutPath.setEnabled(false); jbCleanDocs.setEnabled(false); jckDateMaturityRo.setEnabled(false); jckAccountAll.setEnabled(false); moCurExchangeRate.setEnabled(false); jbExchangeRateSystemOrigin.setEnabled(false); jbActualExR.setEnabled(false); jbRefreshExR.setEnabled(false); moKeyCurrencyDoc.setEnabled(false); } else if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_ADV) { jckDateMaturityRo.setEnabled(false); jckAccountAll.setEnabled(false); jbExchangeRateSystemOrigin.setEnabled(false); jbActualExR.setEnabled(false); jbRefreshExR.setEnabled(false); jbSelectAll.setEnabled(false); jbCleanAll.setEnabled(false); moCurExchangeRate.setEnabled(false); moKeyCurrencyDoc.setEnabled(false); } } private void renderBankLayoutSettings() { moTextConcept.setText(""); if (moKeyBankLayoutType.getSelectedIndex() > 0) { mnLayout = ((int[]) ((SGuiItem) moKeyLayouId.getSelectedItem()).getPrimaryKey())[0]; mnLayoutSubtype = ((int[]) ((SGuiItem) moKeyBankLayoutType.getSelectedItem()).getPrimaryKey())[0]; mnLayoutType = ((int[]) ((SGuiItem) moKeyBankLayoutType.getSelectedItem()).getForeignKey())[0]; mnLayoutBank = ((int[]) ((SGuiItem) moKeyBankLayoutType.getSelectedItem()).getForeignKey())[1]; switch (mnLayoutType) { case SDataConstantsSys.FINS_TP_PAY_BANK_THIRD: moTextConcept.setEnabled(mnLayout == SFinConsts.LAY_BANK_SANTANDER || mnLayout == SFinConsts.LAY_BANK_HSBC); break; case SDataConstantsSys.FINS_TP_PAY_BANK_TEF: moTextConcept.setEnabled(mnLayout == SFinConsts.LAY_BANK_SANTANDER); break; case SDataConstantsSys.FINS_TP_PAY_BANK_SPEI_FD_N: moTextConcept.setEnabled(mnLayout == SFinConsts.LAY_BANK_SANTANDER); break; case SDataConstantsSys.FINS_TP_PAY_BANK_SPEI_FD_Y: moTextConcept.setEnabled(mnLayout == SFinConsts.LAY_BANK_SANTANDER); break; default : break; } moIntConsecutiveDay.setEnabled(mnLayout == SFinConsts.LAY_BANK_BANBAJIO); moKeyCurrencyBank.setEnabled(true); } else { moTextConcept.setEnabled(false); moIntConsecutiveDay.setEnabled(false); moKeyCurrencyBank.resetField(); moKeyCurrencyBank.setEnabled(false); } } private void renderAccountSettings(final int[] KeyAccountDebit ) { if (KeyAccountDebit.length > 0) { moDataAccountCash = (SDataAccountCash) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.FIN_ACC_CASH, KeyAccountDebit, SLibConstants.EXEC_MODE_SILENT); moDataBizPartnerBranchBankAccount = (SDataBizPartnerBranchBankAccount) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.BPSU_BANK_ACC, new int[] { moDataAccountCash.getFkBizPartnerBranchId_n(), moDataAccountCash.getFkBankAccountId_n() }, SLibConstants.EXEC_MODE_SILENT); mnCurrencyId = moDataBizPartnerBranchBankAccount.getFkCurrencyId(); msAccountDebit = moDataBizPartnerBranchBankAccount.getBankAccountNumber(); moKeyCurrencyBank.setEnabled(true); moParamsMap = new HashMap<Integer, Object>(); moParamsMap.put(SDataConstants.FIN_ACC_COB_ENT, moDataAccountCash.getPkCompanyBranchId()); moParamsMap.put(SDataConstants.FIN_ACC_CASH, moDataAccountCash.getPkAccountCashId()); } else { moDataBizPartnerBranchBankAccount = null; mnCurrencyId = 0; } } private void renderCurrencyDoc(){ double excchangeRate = 0d; if (moKeyCurrencyDoc.getValue().length > 0d) { if (miClient.getSession().getSessionCustom().isLocalCurrency(new int[] { moKeyCurrencyDoc.getValue()[0] })) { excchangeRate = SDataConstantsSys.FINX_EXC_RATE_CUR_SYS; moCurExchangeRate.setEnabled(false); jbExchangeRateSystemOrigin.setEnabled(false); jbActualExR.setEnabled(false); jbRefreshExR.setEnabled(false); } else { try { excchangeRate = SDataUtilities.obtainExchangeRate((SClientInterface) miClient, moKeyCurrencyDoc.getValue()[0], moDateDate.getValue()); } catch (Exception e) { SLibUtilities.renderException(this, e); } moCurExchangeRate.setEnabled(true); jbExchangeRateSystemOrigin.setEnabled(true); jbActualExR.setEnabled(true); jbRefreshExR.setEnabled(true); } } if (excchangeRate != 0d) { mnCurrencyId = moKeyCurrencyDoc.getValue()[0]; moCurExchangeRate.getField().setValue(excchangeRate); } else{ moCurExchangeRate.getField().setValue(excchangeRate); } } private void renderCurrencyBank(final boolean load) { if (load) { if (mnCurrencyId != SLibConsts.UNDEFINED) { moKeyCurrencyBank.setValue(new int[] { mnCurrencyId }); } } if (moKeyCurrencyBank.getValue().length != SLibConstants.UNDEFINED) { moKeyCurrencyDoc.setValue(moKeyCurrencyBank.getValue()); if (moKeyBankLayoutType.getSelectedItem().getPrimaryKey()[0] != SLibConstants.UNDEFINED) { miClient.getSession().populateCatalogue(moKeyAccountDebit, SModConsts.FIN_ACC_CASH, SModConsts.FINX_ACC_CASH_BANK, new SGuiParams( new int[] { moKeyCurrencyBank.getValue()[0], ((int[]) ((SGuiItem) moKeyBankLayoutType.getSelectedItem()).getForeignKey())[1] })); moCurExchangeRate.setCompoundText(SDataReadDescriptions.getCatalogueDescription(((SClientInterface) miClient), SDataConstants.CFGU_CUR, new int[] { moKeyCurrencyBank.getValue()[0] }, SLibConstants.DESCRIPTION_CODE)); moKeyAccountDebit.setEnabled(true); } } else { moKeyAccountDebit.removeAllItems(); moKeyAccountDebit.setEnabled(false); } } private void actionActualExchangeRate() { int rowIndex = SLibConsts.UNDEFINED; SLayoutBankRow row = null; rowIndex = moGridPayments.getTable().getSelectedRow(); row = (SLayoutBankRow) moGridPayments.getGridRow(rowIndex); if (row.getBalanceTot().getAmountOriginal() > 0) { row.setIsForPayment(true); row.setExchangeRate(row.getBalance().getExchangeRate()); } else { row.setIsForPayment(false); } computeBalancePayment(); moGridPayments.renderGridRows(); moGridPayments.getTable().setRowSelectionInterval(rowIndex, rowIndex); } private void actionRefreshExchangeRate() { int rowIndex = SLibConsts.UNDEFINED; SLayoutBankRow row = null; rowIndex = moGridPayments.getTable().getSelectedRow(); row = (SLayoutBankRow) moGridPayments.getGridRow(rowIndex); if (row.getBalanceTot().getAmountOriginal() > 0) { row.setIsForPayment(true); row.setExchangeRate(moCurExchangeRate.getField().getValue()); } else { row.setIsForPayment(false); } computeBalancePayment(); moGridPayments.renderGridRows(); moGridPayments.getTable().setRowSelectionInterval(rowIndex, rowIndex); } private void actionExchangeRateSystemOrigin() { double exchangeRate = 0d; exchangeRate =((SClientInterface) miClient).pickExchangeRate(moKeyCurrencyDoc.getValue()[0], moDateDate.getDefaultValue()); if (exchangeRate != 0d) { moCurExchangeRate.getField().setValue(exchangeRate); } else { moCurExchangeRate.getField().setValue(0d); } jbExchangeRateSystemOrigin.requestFocus(); } @SuppressWarnings("unchecked") private void renderBankAccountCredit(int nBizPartnerBranch, int nBankId) { String sql = ""; ResultSet resultSet = null; Statement statementAux; SDataBizPartnerBranchBankAccount bizPartnerBranchBankAccount = null; msAccountCredit = ""; HashSet<String> oAccountCreditAux; String accountCredit = ""; int bpbId = 0; int bpbBankAccId = 0; try { sql = "SELECT b.id_bpb, b.id_bank_acc, b.acc_num, b.acc_num_std, b.fid_bank, b.b_def, COALESCE(lay.fid_tp_pay_bank, 0) AS f_tp_pay, " + "COALESCE(lay.id_tp_lay_bank, 0) AS f_tp_lay, bp.code_bank_san, bp.code_bank_baj, b.alias_baj " + "FROM erp.bpsu_bank_acc AS b " + "LEFT OUTER JOIN erp.bpsu_bank_acc_lay_bank AS l ON b.id_bpb = l.id_bpb AND b.id_bank_acc = l.id_bank_acc " + "LEFT OUTER JOIN erp.finu_tp_lay_bank AS lay ON l.id_tp_lay_bank = lay.id_tp_lay_bank " + "LEFT OUTER JOIN erp.bpsu_bp AS bp ON bp.id_bp = b.fid_bank " + "WHERE b.b_del = 0 AND b.fid_cur = " + moKeyCurrencyBank.getValue()[0] + " AND b.id_bpb = " + nBizPartnerBranch + (mnLayoutType == SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? " AND b.fid_bank = " + nBankId : " AND b.fid_bank <> " + nBankId) + " AND lay.id_tp_lay_bank = " + mnLayoutSubtype + " "; oAccountCreditAux = new HashSet<String>(); maBranchBankAccountsCredit = new ArrayList<SDataBizPartnerBranchBankAccount>(); maAccountCredit = new ArrayList<SGuiItem>(); statementAux = miClient.getSession().getStatement().getConnection().createStatement(); resultSet = statementAux.executeQuery(sql); while (resultSet.next()) { bpbId = resultSet.getInt(1); bpbBankAccId = resultSet.getInt(2); if (resultSet.getBoolean(6) && resultSet.getInt(7) == mnLayoutType) { msAccountCredit = (mnLayoutType != SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? resultSet.getString(4) : resultSet.getString(3)); } if (msAccountCredit.length() == 0 && resultSet.getInt(7) == mnLayoutType) { msAccountCredit = (mnLayoutType != SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? resultSet.getString(4) : resultSet.getString(3)); } accountCredit = mnLayoutType != SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? resultSet.getString(4) : resultSet.getString(3); if (resultSet.getInt(7) == mnLayoutType && resultSet.getInt(8) == mnLayoutSubtype) { oAccountCreditAux.add(accountCredit); } moRow.getCodeBankAccountCredit().put(mnLayoutType != SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? resultSet.getString(4) : resultSet.getString(3), mnLayout == SFinConsts.LAY_BANK_BANBAJIO ? resultSet.getString(10) : resultSet.getString(9)); moRow.getAliasBankAccountCredit().put(mnLayoutType != SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? resultSet.getString(4) : resultSet.getString(3), resultSet.getString(11)); bizPartnerBranchBankAccount = (SDataBizPartnerBranchBankAccount) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.BPSU_BANK_ACC, new int[] { bpbId, bpbBankAccId }, SLibConstants.EXEC_MODE_SILENT); maBranchBankAccountsCredit.add(bizPartnerBranchBankAccount); } for (String s : oAccountCreditAux) { maAccountCredit.add(new SGuiItem(new int[] { bpbId, bpbBankAccId }, s)); } } catch (Exception e) { SLibUtilities.renderException(this, e); } } private boolean readRecord(Object key) { moCurrentRecord = (SDataRecord) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.FIN_REC, key, SLibConstants.EXEC_MODE_VERBOSE); return true; } private void renderRecord() { if (moCurrentRecord == null) { jtfRecordDate.setText(""); jtfRecordBkc.setText(""); jtfRecordBranch.setText(""); jtfRecordNumber.setText(""); } else { jtfRecordDate.setText(((SClientInterface) miClient).getSessionXXX().getFormatters().getDateFormat().format(moCurrentRecord.getDate())); jtfRecordBkc.setText(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.FIN_BKC, new int[] { moCurrentRecord.getPkBookkeepingCenterId() }, SLibConstants.DESCRIPTION_CODE)); jtfRecordBranch.setText(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.BPSU_BPB, new int[] { moCurrentRecord.getFkCompanyBranchId() }, SLibConstants.DESCRIPTION_CODE)); jtfRecordNumber.setText(moCurrentRecord.getRecordNumber()); } } private void renderBizPartner(int bizPartnerId) { moDataBizPartner = (SDataBizPartner) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.BPSU_BP, new int[] { bizPartnerId }, SLibConstants.EXEC_MODE_SILENT); if (moDataBizPartner != null) { msDebitFiscalId = moDataBizPartner.getFiscalId(); } } private void renderLayoutTypeBank() { String sql = ""; ResultSet resultSet = null; try { sql = "SELECT id_tp_lay_bank AS f_id_1, tp_lay_bank AS f_item, fid_tp_pay_bank AS f_fid_1, fid_bank AS f_fid_2, lay_bank AS f_fid_3 " + "FROM erp.finu_tp_lay_bank " + "WHERE b_del = 0 " + "ORDER BY tp_lay_bank, id_tp_lay_bank "; mvLayoutTypes = new Vector<SGuiItem>(); mvLayoutTypes.add(new SGuiItem(new int[] { SLibConsts.UNDEFINED }, "(" + SUtilConsts.TXT_SELECT + " layout)")); resultSet = miClient.getSession().getStatement().executeQuery(sql); while (resultSet.next()) { mvLayoutTypes.add(new SGuiItem(new int[] { resultSet.getInt("f_id_1") }, resultSet.getString("f_item"), new int[] { resultSet.getInt("f_fid_1"), resultSet.getInt("f_fid_2") }, new int[] { resultSet.getInt("f_fid_3") })); } moKeyBankLayoutType.removeAllItems(); for (int i = 0; i < mvLayoutTypes.size(); i++) { moKeyBankLayoutType.addItem(mvLayoutTypes.get(i)); } } catch (Exception e) { SLibUtilities.renderException(this, e); } } private void populateCatalogues(){ miClient.getSession().populateCatalogue(moKeyCurrencyBank, SModConsts.CFGU_CUR, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyCurrencyDoc, SModConsts.CFGU_CUR, SLibConsts.UNDEFINED, null); populateLayoutBank(); } private void populateLayoutType() { SGuiItem item = null; if (moKeyLayouId.getSelectedIndex() > 0) { moKeyBankLayoutType.removeAllItems(); for (int i = 0; i < mvLayoutTypes.size(); i++) { item = mvLayoutTypes.get(i); if (SLibUtils.compareKeys(item.getPrimaryKey(), new int[] { SLibConsts.UNDEFINED }) || SLibUtils.compareKeys((int[]) item.getComplement(), new int[] { moKeyLayouId.getValue()[0] })) { moKeyBankLayoutType.addItem(item); } } moKeyBankLayoutType.setEnabled(true); moKeyCurrencyBank.resetField(); } else { moKeyBankLayoutType.resetField(); moKeyBankLayoutType.setEnabled(false); moKeyCurrencyBank.resetField(); renderBankLayoutSettings(); } } private void populateLayoutBank() { Vector<SGuiItem> layouts = new Vector<SGuiItem>(); layouts.add(new SGuiItem(new int[] { SLibConsts.UNDEFINED }, "(" + SUtilConsts.TXT_SELECT + " layout)")); layouts.add(new SGuiItem(new int[] { SFinConsts.LAY_BANK_HSBC }, SFinConsts.TXT_LAY_BANK_HSBC)); layouts.add(new SGuiItem(new int[] { SFinConsts.LAY_BANK_SANTANDER }, SFinConsts.TXT_LAY_BANK_SANTANDER)); layouts.add(new SGuiItem(new int[] { SFinConsts.LAY_BANK_BANBAJIO }, SFinConsts.TXT_LAY_BANK_BANBAJIO)); layouts.add(new SGuiItem(new int[] { SFinConsts.LAY_BANK_BBVA }, SFinConsts.TXT_LAY_BANK_BBVA)); layouts.add(new SGuiItem(new int[] { SFinConsts.LAY_BANK_BANAMEX }, SFinConsts.TXT_LAY_BANK_BANAMEX)); moKeyLayouId.removeAllItems(); for (int i = 0; i < layouts.size(); i++) { moKeyLayouId.addItem(layouts.get(i)); } } private void itemStateChangedBankLayoutTypeId() { moTextLayoutPath.setText(""); renderBankLayoutSettings(); itemStateChangedCurrencyBank(); } private void itemStateChangedAccountDebit() { renderAccountSettings(moKeyAccountDebit.getValue()); } private void itemStateChangedLayout() { populateLayoutType(); } private void itemStateChangedCurrencyBank() { renderCurrencyBank(false); } private void itemStateChangedCurrencyDock() { renderCurrencyDoc(); } private void actionSelectAll() { SLayoutBankRow row = null; SLayoutBankPaymentRow payRow = null; SFinRecordLayout recordLayout = null; SLayoutBankPayment bankPayment = null; SLayoutBankPayment bankPaymentAux = null; SGuiValidation validation = validateForm(); try { if (validation.isValid()) { if (mnFormSubtype == SModConsts.FIN_REC) { if (validateRecord(true)) { for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { payRow = (SLayoutBankPaymentRow) rowAux; bankPaymentAux = payRow.getLayoutBankPayment().clone(); bankPayment = payRow.getLayoutBankPayment().clone(); bankPaymentAux.setAction(2); // 1: make payment, 2: remove payment computeBankRecords(bankPaymentAux, payRow.getFinRecordLayout()); payRow.setIsForPayment(true); payRow.setRecordPeriod(moCurrentRecord.getRecordPeriod()); payRow.setRecordBkc(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.FIN_BKC, new int[] { moCurrentRecord.getPkBookkeepingCenterId() }, SLibConstants.DESCRIPTION_CODE)); payRow.setRecordCob(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.BPSU_BPB, new int[] { moCurrentRecord.getFkCompanyBranchId() }, SLibConstants.DESCRIPTION_CODE)); payRow.setRecordNumber(moCurrentRecord.getRecordNumber()); payRow.setRecordDate(moCurrentRecord.getDate()); bankPayment.setAction(1); // 1: make payment, 2: remove payment recordLayout = new SFinRecordLayout(moCurrentRecord.getPkYearId(), moCurrentRecord.getPkPeriodId(), moCurrentRecord.getPkBookkeepingCenterId(), moCurrentRecord.getPkRecordTypeId(), moCurrentRecord.getPkNumberId()); payRow.setFinRecordLayout(recordLayout); computeBankRecords(bankPayment, recordLayout); } } } else { for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { row = (SLayoutBankRow) rowAux; row.setIsForPayment(true); } } computeBalancePayment(); moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); } else { if (validation.getComponent() != null) { validation.getComponent().requestFocus(); } if (validation.getMessage().length() > 0) { miClient.showMsgBoxWarning(validation.getMessage()); } } } catch (Exception e) { SLibUtils.showException(this, e); } } private void actionCleanAll() { SLayoutBankRow row = null; SLayoutBankPaymentRow payRow = null; SFinRecordLayout recordLayout = null; SLayoutBankPayment bankPayment = null; try { if (mnFormSubtype == SModConsts.FIN_REC) { for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { payRow = (SLayoutBankPaymentRow) rowAux; bankPayment = payRow.getLayoutBankPayment().clone(); payRow.setIsForPayment(false); payRow.setRecordPeriod(""); payRow.setRecordBkc(""); payRow.setRecordCob(""); payRow.setRecordNumber(""); payRow.setRecordDate(null); payRow.setFinRecordLayout(null); bankPayment.setAction(payRow.getIsToPayed() ? 2 : SLibConsts.UNDEFINED); // 1: make payment, 2: remove payment recordLayout = payRow.getFinRecordLayout(); computeBankRecords(bankPayment, recordLayout); } } else { for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { row = (SLayoutBankRow) rowAux; row.setIsForPayment(false); } } computeBalancePayment(); moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); } catch (Exception e) { SLibUtils.showException(this, e); } } private void actionLoadLayoutPath() { SimpleDateFormat fileNameDatetimeFormat = new SimpleDateFormat("yyMMdd HHmm"); //String nameFile = (moKeyBankLayoutType.getSelectedIndex() <= 0 ? "" : SLibUtils.textToAscii(moKeyBankLayoutType.getSelectedItem().getItem().toLowerCase().replaceAll("/", " "))); String nameFile = ""; try { nameFile = (moKeyBankLayoutType.getSelectedIndex() <= 0 ? "" : SLibUtils.textToAscii(SFinUtilities.getFileNameLayout(miClient.getSession(), moKeyBankLayoutType.getSelectedItem().getPrimaryKey()[0]).toLowerCase().replaceAll("/", " "))); nameFile = SLibUtils.validateSafePath(fileNameDatetimeFormat.format(new java.util.Date()) + " " + nameFile + ".txt"); miClient.getFileChooser().setSelectedFile(new File(nameFile)); if (miClient.getFileChooser().showSaveDialog(miClient.getFrame()) == JFileChooser.APPROVE_OPTION) { moTextLayoutPath.setValue(miClient.getFileChooser().getSelectedFile().getAbsolutePath()); } } catch (Exception e) { SLibUtils.showException(this, e); } } private void actionShowDocs() { SGuiValidation validation = validateForm(); if (validation.isValid()) { enableGeneralFields(false); moKeyCurrencyBank.setEnabled(false); moKeyAccountDebit.setEnabled(false); if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS) { showDps(true); } else { showSupplier(true); } } else { if (validation.getComponent() != null) { validation.getComponent().requestFocus(); } if (validation.getMessage().length() > 0) { miClient.showMsgBoxWarning(validation.getMessage()); } } } private void actionCleanDocs() { enableGeneralFields(true); moKeyCurrencyBank.setEnabled(true); moKeyAccountDebit.setEnabled(true); jckDateMaturityRo.setSelected(true); jckAccountAll.setSelected(true); jckDateMaturityRo.setEnabled(false); jckAccountAll.setEnabled(false); renderBankLayoutSettings(); moGridPayments.clearGridRows(); } public void actionPickRecord() { Object key = null; String message = ""; moDialogRecordPicker.formReset(); moDialogRecordPicker.setFilterKey(moDateDate.getValue()); moDialogRecordPicker.setParams(moParamsMap); moDialogRecordPicker.formRefreshOptionPane(); if (moCurrentRecord != null) { moDialogRecordPicker.setSelectedPrimaryKey(moCurrentRecord.getPrimaryKey()); } moDialogRecordPicker.setFormVisible(true); if (moDialogRecordPicker.getFormResult() == SLibConstants.FORM_RESULT_OK) { key = moDialogRecordPicker.getSelectedPrimaryKey(); // XXX set registry lock to accounting record if (readRecord(key)) { if (moCurrentRecord != null) { if (moCurrentRecord.getIsSystem()) { message = "No puede seleccionarse esta póliza contable porque es de sistema."; } else if (moCurrentRecord.getIsAudited()) { message = "No puede seleccionarse esta póliza contable porque está auditada."; } else if (moCurrentRecord.getIsAuthorized()) { message = "No puede seleccionarse esta póliza contable porque está autorizada."; } else if (!SDataUtilities.isPeriodOpen((SClientInterface) miClient, moCurrentRecord.getDate())) { message = "No puede seleccionarse esta póliza contable porque su período contable correspondiente está cerrado."; } if (message.length() > 0) { miClient.showMsgBoxWarning(message); moCurrentRecord = null; } else { renderRecord(); } } } } } private void createLayoutXml() { SLayoutBankRow row = null; SLayoutBankXmlRow xmlRow = null; updateLayoutRow(); maXmlRows = new ArrayList<SLayoutBankXmlRow>(); for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { row = (SLayoutBankRow) rowAux; for (int i = 0; i < mvLayoutRows.size(); i++) { if (SLibUtilities.compareKeys(row.getRowPrimaryKey(), mvLayoutRows.get(i).getRowPrimaryKey()) && (mvLayoutRows.get(i).getIsForPayment() || mvLayoutRows.get(i).getIsToPayed())) { xmlRow = new SLayoutBankXmlRow(); xmlRow.setLayoutXmlRowType(mvLayoutRows.get(i).getLayoutRowType()); xmlRow.setDpsYear(row.getPkYearId()); xmlRow.setDpsDoc(row.getPkDocId()); xmlRow.setAmount(row.getBalanceTot().getAmountLocal()); xmlRow.setAmountCy(row.getBalanceTot().getAmountOriginal()); xmlRow.setAmountPayed(row.getBalancePayed()); xmlRow.setCurrencyId(row.getBalanceTot().getCurrencyOriginalId()); xmlRow.setExchangeRate(row.getBalanceTot().getExchangeRate()); xmlRow.setIsToPayed(false); xmlRow.setBizPartner(row.getBizPartnerId()); xmlRow.setBizPartnerBranch(row.getBranchBankAccountCreditId(row.getAccountCredit(), mnLayoutType)[0]); xmlRow.setBizPartnerBranchAccount(row.getBranchBankAccountCreditId(row.getAccountCredit(), mnLayoutType)[1]); xmlRow.setHsbcBankCode(row.getBankKey()); xmlRow.setHsbcAccountType(row.getAccType()); xmlRow.setHsbcFiscalIdDebit(row.getBizPartnerDebitFiscalId()); xmlRow.setHsbcFiscalIdCredit(row.getBizPartnerCreditFiscalId()); xmlRow.setHsbcFiscalVoucher(row.getCf()); xmlRow.setSantanderBankCode(row.getSantanderBankCode()); xmlRow.setConcept(row.getConcept()); xmlRow.setDescription(row.getDescription()); xmlRow.setReference(row.getReference()); xmlRow.setBajioBankCode(row.getBajioBankCode()); xmlRow.setBajioBankNick(row.getBajioBankAlias()); xmlRow.setBankKey(row.getBankKey()); xmlRow.setRecYear(SLibConsts.UNDEFINED); xmlRow.setRecPeriod(SLibConsts.UNDEFINED); xmlRow.setRecBookkeepingCenter(SLibConsts.UNDEFINED); xmlRow.setRecRecordType(""); xmlRow.setRecNumber(SLibConsts.UNDEFINED); xmlRow.setBookkeepingYear(SLibConsts.UNDEFINED); xmlRow.setBookkeepingNumber(SLibConsts.UNDEFINED); xmlRow.setObservation(row.getObservation()); if (mvLayoutRows.get(i).getIsForPayment()) { maXmlRows.add(xmlRow); } } } } } private void loadPaymentsXml() { double balancePayment = 0; double balanceDoc = 0; double balanceCyDoc = 0; double excRate = 0; String observation = ""; int dpsYearId = 0; int dpsDocId = 0; int recUserId = 0; SXmlBankLayoutPayment layoutPay = null; SXmlBankLayoutPaymentDoc layoutPayDoc = null; Vector<SGridRow> rows = new Vector<SGridRow>(); Vector<SLayoutBankPaymentRow> rowsAux = new Vector<SLayoutBankPaymentRow>(); SXmlBankLayout gridXml = new SXmlBankLayout(); SDataRecord record = null; SDataBizPartnerBranch bizPartnerBranchCob = null; SDataBizPartnerBranchBankAccount branchBankAccount = null; SDataBizPartner bizPartner = null; SDataDps dps = null; SLayoutBankPaymentRow moRow = null; SLayoutBankPayment moPayment = null; SLayoutBankDps moDps = null; SLayoutBankXmlRow xmlRow = null; SFinRecordLayout recordLayout = null; try { gridXml.processXml(moRegistry.getLayoutXml()); for (SXmlElement element : gridXml.getXmlElements()) { if (element instanceof SXmlBankLayoutPayment) { // Payment: layoutPay = (SXmlBankLayoutPayment) element; bizPartnerBranchCob = (SDataBizPartnerBranch) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.BPSU_BPB, new int[] { (int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BANK_BP).getValue() }, SLibConstants.EXEC_MODE_SILENT); branchBankAccount = (SDataBizPartnerBranchBankAccount) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.BPSU_BANK_ACC, new int[] { (int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BANK_BP).getValue(), (int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BANK_BANK).getValue() }, SLibConstants.EXEC_MODE_SILENT); bizPartner = (SDataBizPartner) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.BPSU_BP, new int[] { bizPartnerBranchCob.getFkBizPartnerId() }, SLibConstants.EXEC_MODE_SILENT); balancePayment = (double) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_AMT).getValue(); moRow = new SLayoutBankPaymentRow(miClient); moRow.setBizPartnerId(bizPartner.getPkBizPartnerId()); moRow.setBizPartnerBranchId(branchBankAccount.getPkBizPartnerBranchId()); moRow.setBizPartnerBranchAccountId(branchBankAccount.getPkBankAccountId()); moRow.setBizPartner(bizPartner.getBizPartner()); moRow.setBizPartnerKey(bizPartner.getDbmsCategorySettingsSup().getKey()); moRow.setBalance(balancePayment); moRow.setBalanceTot(0); moRow.setCurrencyKey(branchBankAccount.getDbmsCurrencyKey()); moRow.setAccountCredit(mnLayoutType != SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? branchBankAccount.getBankAccountNumberStd(): branchBankAccount.getBankAccountNumber()); moRow.setIsForPayment((boolean) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_APPLIED).getValue()); moRow.setIsToPayed((boolean) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_APPLIED).getValue()); if ((Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_REC_YEAR).getValue() != 0) { recordLayout = new SFinRecordLayout((Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_REC_YEAR).getValue(), (Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_REC_PER).getValue(), (Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_REC_BKC).getValue(), (String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_REC_REC_TP).getValue(), (Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_REC_NUM).getValue()); moRow.setFinRecordLayout(recordLayout); moRow.setFinRecordLayoutOld(recordLayout); record = (SDataRecord) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.FIN_REC, recordLayout.getPrimaryKey(), SLibConstants.EXEC_MODE_SILENT); moRow.setRecordPeriod(record.getRecordPeriod()); moRow.setRecordBkc(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.FIN_BKC, new int[] { record.getPkBookkeepingCenterId() }, SLibConstants.DESCRIPTION_CODE)); moRow.setRecordCob(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.BPSU_BPB, new int[] { record.getFkCompanyBranchId() }, SLibConstants.DESCRIPTION_CODE)); moRow.setRecordNumber(record.getRecordNumber()); moRow.setRecordDate(record.getDate()); } else { recordLayout = null; } moPayment = new SLayoutBankPayment(SLibConsts.UNDEFINED, bizPartner.getPkBizPartnerId(), branchBankAccount.getPkBizPartnerBranchId(), branchBankAccount.getPkBankAccountId()); moPayment.setAmount(new SMoney(balancePayment, branchBankAccount.getFkCurrencyId())); moPayment.setFkBookkeepingYearId_n((Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BKK_YEAR).getValue()); moPayment.setFkBookkeepingNumberId_n((Integer) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BKK_NUM).getValue()); moPayment.setAction(SLibConsts.UNDEFINED); // create layout bank document: for (SXmlElement elementDoc : layoutPay.getXmlElements()) { if (elementDoc instanceof SXmlBankLayoutPaymentDoc) { layoutPayDoc = (SXmlBankLayoutPaymentDoc) elementDoc; dpsYearId = (Integer) layoutPayDoc.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_DPS_YEAR).getValue(); dpsDocId = (Integer) layoutPayDoc.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_DPS_DOC).getValue(); dps = (SDataDps) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_DPS, new int[] { dpsYearId, dpsDocId }, SLibConstants.EXEC_MODE_SILENT); balanceCyDoc = (double) layoutPayDoc.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_AMT_CY).getValue(); balanceDoc = (double) layoutPayDoc.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_AMT).getValue(); excRate = (double) layoutPayDoc.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_EXT_RATE).getValue(); observation = (String) layoutPayDoc.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_OBS).getValue(); if (dps != null) { moDps = new SLayoutBankDps(dpsYearId, dpsDocId, dps.getFkDpsCategoryId(), dps.getFkDpsClassId(), dps.getFkDpsTypeId(), dps.getFkCurrencyId(), recUserId, balanceDoc, dps.getExchangeRate()); } if (dpsYearId != SLibConsts.UNDEFINED && dpsDocId != SLibConsts.UNDEFINED) { moPayment.setLayoutRowType(SModSysConsts.FIN_LAY_BANK_DPS); } else { moPayment.setLayoutRowType(SModSysConsts.FIN_LAY_BANK_ADV); } moPayment.getAmount().setExchangeRate(dps != null ? dps.getExchangeRate() : SLibConsts.UNDEFINED); moPayment.getLayoutBankDps().add(moDps); xmlRow = new SLayoutBankXmlRow(); xmlRow.setLayoutXmlRowType(moPayment.getLayoutPaymentType()); xmlRow.setDpsYear(dps != null ? dps.getPkYearId() : SLibConsts.UNDEFINED); xmlRow.setDpsDoc(dps != null ? dps.getPkDocId() : SLibConsts.UNDEFINED); xmlRow.setAmount(balanceDoc); xmlRow.setAmountCy(balanceCyDoc); xmlRow.setAmountPayed(balanceDoc); xmlRow.setExchangeRate(excRate); xmlRow.setIsToPayed(moRow.getIsToPayed()); xmlRow.setBizPartner(bizPartner.getPkBizPartnerId()); xmlRow.setBizPartnerBranch(branchBankAccount.getPkBizPartnerBranchId()); xmlRow.setBizPartnerBranchAccount(branchBankAccount.getPkBankAccountId()); xmlRow.setHsbcBankCode(SLibUtils.parseInt((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_HSBC_BANK_CODE).getValue())); xmlRow.setHsbcAccountType((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_HSBC_ACC_TP).getValue()); xmlRow.setHsbcFiscalIdDebit((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_HSBC_FIS_ID_DBT).getValue()); xmlRow.setHsbcFiscalIdCredit((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_HSBC_FIS_ID_CRD).getValue()); xmlRow.setHsbcFiscalVoucher(SLibUtils.parseInt((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_HSBC_FIS_VOU).getValue())); xmlRow.setSantanderBankCode((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_SAN_BANK_CODE).getValue()); xmlRow.setConcept((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_CPT).getValue()); xmlRow.setDescription((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_HSBC_DCRP).getValue()); xmlRow.setReference(dps != null ? ((dps.getNumberSeries().length() == 0 ? "" : dps.getNumberSeries() + "-") + dps.getNumber()) : ""); xmlRow.setBajioBankCode((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BAJIO_BANK_CODE).getValue()); xmlRow.setBajioBankNick((String) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BAJIO_NICK).getValue()); xmlRow.setBankKey((int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BANK_KEY).getValue()); xmlRow.setObservation(observation); if (recordLayout != null) { xmlRow.setRecYear(recordLayout.getPkYearId()); xmlRow.setRecPeriod(recordLayout.getPkPeriodId()); xmlRow.setRecBookkeepingCenter(recordLayout.getPkBookkeepingCenterId()); xmlRow.setRecRecordType(recordLayout.getPkRecordTypeId()); xmlRow.setRecNumber(recordLayout.getPkNumberId()); xmlRow.setBookkeepingYear(moPayment.getFkBookkeepingYearId_n()); xmlRow.setBookkeepingNumber(moPayment.getFkBookkeepingNumberId_n()); } else { xmlRow.setRecYear(SLibConsts.UNDEFINED); xmlRow.setRecPeriod(SLibConsts.UNDEFINED); xmlRow.setRecBookkeepingCenter(SLibConsts.UNDEFINED); xmlRow.setRecRecordType(""); xmlRow.setRecNumber(SLibConsts.UNDEFINED); xmlRow.setBookkeepingYear(SLibConsts.UNDEFINED); xmlRow.setBookkeepingNumber(SLibConsts.UNDEFINED); } maXmlRows.add(xmlRow); } } moRow.setLayoutBankPayment(moPayment); rowsAux.add(moRow); } } rows.addAll(rowsAux); moGridPayments.populateGrid(rows); moGridPayments.createGridColumns(); moGridPayments.getTable().setColumnSelectionAllowed(false); moGridPayments.getTable().getTableHeader().setReorderingAllowed(false); moGridPayments.getTable().getTableHeader().setResizingAllowed(true); moGridPayments.getTable().setRowSorter(new TableRowSorter<AbstractTableModel>(moGridPayments.getModel())); moGridPayments.getTable().getTableHeader().setEnabled(false); if (moGridPayments.getTable().getRowCount() > 0) { moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); moTableCellEditorOptions.setAccounts(mltAccountCredit); } } catch (Exception e) { SLibUtils.showException(this, e); } } private void updateDocsXml() throws Exception { int[] key = new int[] { SLibConsts.UNDEFINED }; int num = 0; int foundNum = 0; SXmlBankLayout gridXml = new SXmlBankLayout(); gridXml.processXml(moRegistry.getLayoutXml()); for (SXmlElement elementPay : gridXml.getXmlElements()) { if (elementPay instanceof SXmlBankLayoutPayment) { SXmlBankLayoutPayment layoutPay = (SXmlBankLayoutPayment) elementPay; for (SXmlElement elementDoc : layoutPay.getXmlElements()) { if (elementDoc instanceof SXmlBankLayoutPaymentDoc) { num++; // Dps: SXmlBankLayoutPaymentDoc layoutDps = (SXmlBankLayoutPaymentDoc) elementDoc; if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS) { key = new int[] { (Integer) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_DPS_YEAR).getValue(), (Integer) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_DPS_DOC).getValue() }; } else if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_ADV) { key = new int[] { (int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BP).getValue() }; } if (mvLayoutRows != null) { for (int i = 0; i < mvLayoutRows.size(); i++) { if (SLibUtilities.compareKeys(key, mvLayoutRows.get(i).getRowPrimaryKey())) { foundNum++; mvLayoutRows.get(i).setIsForPayment(true); mvLayoutRows.get(i).setIsToPayed((boolean) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_APPLIED).getValue()); mvLayoutRows.get(i).getBalanceTot().setAmountOriginal((double) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_AMT_CY).getValue()); if ((moKeyCurrencyBank.getValue()[0] == moKeyCurrencyDoc.getValue()[0]) && ((double) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_EXT_RATE).getValue() == 0)){ mvLayoutRows.get(i).setExchangeRate(1); } else { mvLayoutRows.get(i).setExchangeRate((double) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_EXT_RATE).getValue() ); } mvLayoutRows.get(i).setBalancePayed((double) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_AMT).getValue()); mvLayoutRows.get(i).setAccountCredit(mvLayoutRows.get(i).getBranchBankAccountCreditNumber(new int[] { (int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BANK_BP).getValue(), (int) layoutPay.getAttribute(SXmlBankLayoutPayment.ATT_LAY_PAY_BANK_BANK).getValue() }, mnLayoutType)); mvLayoutRows.get(i).setObservation((String) layoutDps.getAttribute(SXmlBankLayoutPaymentDoc.ATT_LAY_ROW_OBS).getValue()); } } } } } } } if (foundNum != num) { if (miClient.showMsgBoxConfirm("No se encontraron todas las cuentas por pagar del layout.\n¿Desea cargar el layout sólo con las cuentas que sea posible?") == JOptionPane.NO_OPTION) { throw new Exception("¡No se encontraron todas las cuentas por pagar del layout!"); } } moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); } private void computeBankRecords(SLayoutBankPayment bankPayment, SFinRecordLayout recordLayout) throws Exception { boolean found = false; SDataRecord record = null; SLayoutBankRecord bankRecord = null; SSrvLock lock = null; if (recordLayout == null) { for (SLayoutBankRecord bankRecordRow : maBankRecords) { bankRecordRow.removeLayoutBankPayment(bankPayment.getBizPartnerId(), bankPayment.getBizPartnerBranchId(), bankPayment.getBizPartnerBranchAccountId()); } } else { for (SLayoutBankRecord bankRecordRow : maBankRecords) { if (SLibUtils.compareKeys(bankRecordRow.getFinRecordLayout().getPrimaryKey(), recordLayout.getPrimaryKey())) { bankRecordRow.getLayoutBankPayments().add(bankPayment); found = true; break; } } if (!found) { record = (SDataRecord) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.FIN_REC, recordLayout.getPrimaryKey(), SLibConstants.EXEC_MODE_SILENT); lock = SSrvUtils.gainLock(miClient.getSession(), ((SClientInterface) miClient).getSessionXXX().getCompany().getPkCompanyId(), SDataConstants.FIN_REC, recordLayout.getPrimaryKey(), record.getRegistryTimeout()); maLocks.add(lock); bankRecord = new SLayoutBankRecord(recordLayout); bankRecord.getLayoutBankPayments().add(bankPayment); maBankRecords.add(bankRecord); } } } private void computeBalancePayment() { SLayoutBankRow row = null; SLayoutBankPaymentRow payRow = null; mdBalanceTot = 0; mdBalancePayed = 0; mnNumberDocs = 0; jtfRows.setText(SLibUtils.DecimalFormatInteger.format(mnNumberDocs) + "/" + SLibUtils.DecimalFormatInteger.format(moGridPayments.getModel().getRowCount())); if (mnFormSubtype == SModConsts.FIN_REC) { moDecBalanceTotPay.setValue(mdBalancePayed); for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { payRow = (SLayoutBankPaymentRow) rowAux; if (payRow.getIsForPayment()) { if (payRow.getBalanceTot() == 0) { payRow.setBalanceTot(payRow.getBalance()); } mdBalancePayed += payRow.getBalanceTot(); mnNumberDocs++; } else { payRow.setBalanceTot(0d); mdBalancePayed -= payRow.getBalanceTot(); } moDecBalanceTotPay.setValue(mdBalancePayed); jtfRows.setText(SLibUtils.DecimalFormatInteger.format(mnNumberDocs) + "/" + SLibUtils.DecimalFormatInteger.format(moGridPayments.getModel().getRowCount())); } } else { moDecBalanceTot.setValue(mdBalanceTot); for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { row = (SLayoutBankRow) rowAux; if (row.getIsForPayment()) { if (row.getBalanceTot().getAmountOriginal() == 0) { row.getBalanceTot().setAmountOriginal(row.getBalance().getAmountOriginal()); } mdBalanceTot += row.getBalanceTot().getAmountLocal(); mnNumberDocs++; } else { row.getBalanceTot().setAmountOriginal(0d); mdBalanceTot -= row.getBalanceTot().getAmountLocal(); } moDecBalanceTot.setValue(mdBalanceTot); jtfRows.setText(SLibUtils.DecimalFormatInteger.format(mnNumberDocs) + "/" + SLibUtils.DecimalFormatInteger.format(moGridPayments.getModel().getRowCount())); } } } private void processEditingAppPayment() { int index = -1; boolean addRecord = false; SLayoutBankRow row = null; SLayoutBankPaymentRow payRow = null; SFinRecordLayout recordLayout = null; SLayoutBankPayment bankPayment = null; index = moGridPayments.getTable().getSelectedRow(); if (mnFormSubtype == SModConsts.FIN_REC) { payRow = (SLayoutBankPaymentRow) moGridPayments.getGridRow(index); } else { row = (SLayoutBankRow) moGridPayments.getGridRow(index); } try { if (mnFormSubtype == SModConsts.FIN_REC) { bankPayment = payRow.getLayoutBankPayment().clone(); if (payRow.getIsForPayment()) { if (validateRecord(false)) { payRow.setIsForPayment(true); payRow.setRecordPeriod(moCurrentRecord.getRecordPeriod()); payRow.setRecordBkc(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.FIN_BKC, new int[] { moCurrentRecord.getPkBookkeepingCenterId() }, SLibConstants.DESCRIPTION_CODE)); payRow.setRecordCob(SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.BPSU_BPB, new int[] { moCurrentRecord.getFkCompanyBranchId() }, SLibConstants.DESCRIPTION_CODE)); payRow.setRecordNumber(moCurrentRecord.getRecordNumber()); payRow.setRecordDate(moCurrentRecord.getDate()); bankPayment.setAction(1); // 1: make payment, 2: remove payment recordLayout = new SFinRecordLayout(moCurrentRecord.getPkYearId(), moCurrentRecord.getPkPeriodId(), moCurrentRecord.getPkBookkeepingCenterId(), moCurrentRecord.getPkRecordTypeId(), moCurrentRecord.getPkNumberId()); addRecord = true; payRow.setFinRecordLayout(recordLayout); } } else { payRow.setIsForPayment(false); payRow.setRecordPeriod(""); payRow.setRecordBkc(""); payRow.setRecordCob(""); payRow.setRecordNumber(""); payRow.setRecordDate(null); payRow.setFinRecordLayout(null); bankPayment.setAction(payRow.getIsToPayed() ? 2 : SLibConsts.UNDEFINED); // 1: make payment, 2: remove payment recordLayout = payRow.getFinRecordLayout(); addRecord = true; } if (addRecord) { computeBankRecords(bankPayment, recordLayout); } } else { if (row.getIsForPayment()) { row.setIsForPayment(true); } else { row.setIsForPayment(false); } } computeBalancePayment(); moGridPayments.renderGridRows(); moGridPayments.getTable().setRowSelectionInterval(index, index); } catch (Exception e) { if (mnFormSubtype == SModConsts.FIN_REC) { payRow.setIsForPayment(false); payRow.setRecordPeriod(""); payRow.setRecordBkc(""); payRow.setRecordCob(""); payRow.setRecordNumber(""); payRow.setRecordDate(null); } else { row.setIsForPayment(false); } SLibUtils.showException(this, e); } } private void processEditingStoppedBalance() { int index = 0; mdBalanceTot = 0; SLayoutBankRow row = null; index = moGridPayments.getTable().getSelectedRow(); row = (SLayoutBankRow) moGridPayments.getGridRow(index); if (row.getBalanceTot().getAmountOriginal() > 0) { row.setIsForPayment(true); } else { row.setIsForPayment(false); } computeBalancePayment(); moGridPayments.renderGridRows(); moGridPayments.getTable().setRowSelectionInterval(index, index); } private void updateLayoutRow() { SLayoutBankRow row = null; for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { row = (SLayoutBankRow) rowAux; for (int i = 0; i < mvLayoutRows.size(); i++) { if (SLibUtilities.compareKeys(row.getRowPrimaryKey(), mvLayoutRows.get(i).getRowPrimaryKey())) { mvLayoutRows.get(i).setIsForPayment(row.getIsForPayment()); mvLayoutRows.get(i).setAccountCredit(row.getAccountCredit()); mvLayoutRows.get(i).setBalanceTot(row.getBalanceTot()); mvLayoutRows.get(i).setBalanceTotByBizPartner(row.getBalanceTot().getAmountOriginal()); mvLayoutRows.get(i).setBankKey(SLibUtilities.parseInt((row.getAccountCredit().length() > 10 ? row.getAccountCredit().substring(0, 3) : "000"))); mvLayoutRows.get(i).setEmail(row.getEmail()); mvLayoutRows.get(i).setSantanderBankCode(mvLayoutRows.get(i).getCodeBankAccountCredit().get(row.getAccountCredit())); mvLayoutRows.get(i).setBajioBankCode(mvLayoutRows.get(i).getCodeBankAccountCredit().get(row.getAccountCredit())); mvLayoutRows.get(i).setBajioBankAlias(mvLayoutRows.get(i).getAliasBankAccountCredit().get(row.getAccountCredit())); mvLayoutRows.get(i).setObservation(row.getObservation()); } } } } private void loadLayoutRow() { updateLayoutRow(); moGridPayments.clearGridRows(); if (mvLayoutRows != null) { mltAccountCredit.clear(); if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS) { for (int i = 0; i < mvLayoutRows.size(); i++) { if (!jckDateMaturityRo.isSelected()) { if (!jckAccountAll.isSelected()) { mltAccountCredit.add(mvLayoutRows.get(i).getAccountCreditArray()); moGridPayments.addGridRow(mvLayoutRows.get(i)); } else { if (mvLayoutRows.get(i).getAccountCreditArray().size() > 0) { mltAccountCredit.add(mvLayoutRows.get(i).getAccountCreditArray()); moGridPayments.addGridRow(mvLayoutRows.get(i)); } } } else if (moDateDateDue.getValue().equals(mvLayoutRows.get(i).getDateMaturityRo())) { if (!jckAccountAll.isSelected()) { mltAccountCredit.add(mvLayoutRows.get(i).getAccountCreditArray()); moGridPayments.addGridRow(mvLayoutRows.get(i)); } else { if (mvLayoutRows.get(i).getAccountCreditArray().size() > 0) { mltAccountCredit.add(mvLayoutRows.get(i).getAccountCreditArray()); moGridPayments.addGridRow(mvLayoutRows.get(i)); } } } } } else if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_ADV) { for (int i = 0; i < mvLayoutRows.size(); i++) { if (!jckAccountAll.isSelected()) { mltAccountCredit.add(mvLayoutRows.get(i).getAccountCreditArray()); moGridPayments.addGridRow(mvLayoutRows.get(i)); } else { if (mvLayoutRows.get(i).getAccountCreditArray().size() > 0) { mltAccountCredit.add(mvLayoutRows.get(i).getAccountCreditArray()); moGridPayments.addGridRow(mvLayoutRows.get(i)); } } } } } computeBalancePayment(); moTableCellEditorOptions.setAccounts(mltAccountCredit); moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); } private String createSqlQuery() { String sSql = ""; if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS) { sSql = "SELECT b.id_bp, b.bp, b.fiscal_id, d.id_year, d.id_doc, d.dt AS dt, " + "CONCAT(d.num_ser, IF(length(d.num_ser) = 0, '', '-'), d.num) AS f_num, " + "d.stot_r AS f_stot, d.stot_cur_r AS f_stot_cur, d.tax_charged_r AS f_tax, d.tax_charged_cur_r AS f_tax_cur, " + "d.tax_retained_r AS f_ret, d.tax_retained_cur_r AS f_ret_cur, d.tot_r AS f_tot, d.tot_cur_r AS f_tot_cur, c.id_cur AS f_id_cur, " + "SUM(re.credit - re.debit) AS f_bal, SUM(re.credit_cur - re.debit_cur) AS f_bal_cur, bcon.email_01, d.fid_bpb, bct.bp_key, " + "dt.code, bpb.bpb, cob.code AS cob_code, c.cur_key, d.exc_rate AS f_ext_rate, " + "COALESCE((SELECT SUM(tax.tax) FROM trn_dps_ety AS de " + "INNER JOIN trn_dps_ety_tax AS tax ON de.id_year = tax.id_year AND de.id_doc = tax.id_doc AND de.id_ety = tax.id_ety AND tax.id_tax_bas = " + SDataConstantsSys.FINU_TAX_BAS_VAT + " " + "WHERE d.id_year = de.id_year AND d.id_doc = de.id_doc AND de.b_del = 0), 0) AS f_iva ,"+ "COALESCE((SELECT SUM(tax.tax_cur) FROM trn_dps_ety AS de " + "INNER JOIN trn_dps_ety_tax AS tax ON de.id_year = tax.id_year AND de.id_doc = tax.id_doc AND de.id_ety = tax.id_ety AND tax.id_tax_bas = " + SDataConstantsSys.FINU_TAX_BAS_VAT + " " + "WHERE d.id_year = de.id_year AND d.id_doc = de.id_doc AND de.b_del = 0), 0) AS f_iva_cur, ADDDATE(d.dt_start_cred, d.days_cred) AS dt_mat " + "FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " + "r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " + "r.id_year = " + SLibTimeUtilities.digestYear(moDateDateDue.getValue())[0] + " AND r.b_del = 0 AND re.b_del = 0 AND " + "re.fid_ct_sys_mov_xxx = " + SDataConstantsSys.FINS_TP_SYS_MOV_BPS_SUP[0] + " AND re.fid_tp_sys_mov_xxx = " + SDataConstantsSys.FINS_TP_SYS_MOV_BPS_SUP[1] + " " + "INNER JOIN erp.bpsu_bp AS b ON re.fid_bp_nr = b.id_bp " + "INNER JOIN erp.bpsu_bp_ct AS bct ON re.fid_bp_nr = bct.id_bp AND bct.id_ct_bp = re.fid_tp_sys_mov_xxx " + "INNER JOIN trn_dps AS d ON re.fid_dps_year_n = d.id_year AND re.fid_dps_doc_n = d.id_doc AND d.b_del = 0 AND d.fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_EMITED + " " + "INNER JOIN erp.trnu_tp_dps AS dt ON d.fid_ct_dps = dt.id_ct_dps AND d.fid_cl_dps = dt.id_cl_dps AND d.fid_tp_dps = dt.id_tp_dps " + "INNER JOIN erp.bpsu_bpb AS bpb ON d.fid_bpb = bpb.id_bpb " + "INNER JOIN erp.cfgu_cur AS c ON d.fid_cur = c.id_cur AND c.id_cur = " + (moKeyCurrencyDoc.getValue().length == 0 ? "0" : ((int []) moKeyCurrencyDoc.getValue())[0]) + " " + "INNER JOIN erp.bpsu_bpb AS cob ON d.fid_cob = cob.id_bpb " + "LEFT OUTER JOIN erp.bpsu_bpb_con AS bcon ON bpb.id_bpb = bcon.id_bpb AND bcon.id_con = " + SDataConstantsSys.BPSS_TP_CON_ADM + " " + "WHERE EXISTS(SELECT * FROM erp.bpsu_bank_acc AS ac WHERE bpb.id_bpb = ac.id_bpb " + (mnLayoutType == SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? "AND ac.fid_bank = " + mnLayoutBank : "AND ac.fid_bank <> " + mnLayoutBank) + ") " + "GROUP BY b.id_bp, b.bp, b.fiscal_id, d.id_year, d.id_doc, d.dt, d.stot_r, d.tax_charged_r, d.tax_retained_r, d.tot_r, c.id_cur, bcon.email_01, d.fid_bpb, bct.bp_key, dt.code, bpb.bpb, cob.code " + "HAVING f_bal > 0 " + "ORDER BY bp, id_bp, f_num, dt, id_year, id_doc; "; } else { sSql = "SELECT b.id_bp, b.bp, bcon.email_01, b.fiscal_id, " + "(SELECT cur_key FROM erp.cfgu_cur WHERE id_cur = (IF(bct.fid_cur_n IS NULL, (SELECT fid_cur FROM erp.cfg_param_erp), bct.fid_cur_n))) AS _cur, bct.bp_key, bpb.id_bpb " + "FROM erp.bpsu_bp AS b " + "INNER JOIN erp.bpsu_bp_ct AS bct ON bct.id_bp = b.id_bp AND bct.id_ct_bp = " + SDataConstantsSys.BPSS_CT_BP_SUP + " AND " + (mnCurrencyId == SLibConsts.UNDEFINED ? "bct.fid_cur_n = " + mnCurrencyId + " " : "(bct.fid_cur_n IS NULL OR bct.fid_cur_n = " + mnCurrencyId + ") ") + "INNER JOIN erp.bpsu_bpb AS bpb ON bpb.fid_bp = b.id_bp AND bpb.fid_tp_bpb = " + SDataConstantsSys.BPSS_TP_BPB_HQ + " " + "LEFT OUTER JOIN erp.bpsu_bpb_con AS bcon ON bpb.id_bpb = bcon.id_bpb AND bcon.id_con = " + SDataConstantsSys.BPSS_TP_CON_ADM + " " + "WHERE EXISTS(SELECT * FROM erp.bpsu_bank_acc AS ac WHERE bpb.id_bpb = ac.id_bpb " + (mnLayoutType == SDataConstantsSys.FINS_TP_PAY_BANK_THIRD ? "AND ac.fid_bank = " + mnLayoutBank : "AND ac.fid_bank <> " + mnLayoutBank) + ") " + "AND b.b_del = 0 AND bct.b_del = 0 " + "ORDER BY bp, id_bp; "; } return sSql; } /** * Initializate fields for a new layout * @throws Exception */ private void initializateNewLayout() throws Exception { jtfRegistryNumber.setText(""); jtfRegistryKey.setText(""); moDateDate.setValue(miClient.getSession().getCurrentDate()); moDateDateDue.setValue(miClient.getSession().getCurrentDate()); mnCurrencyId = SLibConsts.UNDEFINED; moIntConsecutiveDay.setValue(0); moKeyLayouId.resetField(); moKeyCurrencyBank.resetField(); moKeyCurrencyBank.setEnabled(true); moKeyCurrencyDoc.setEnabled(false); moKeyCurrencyDoc.resetField(); moKeyAccountDebit.setEnabled(false); jbActualExR.setEnabled(false); jbRefreshExR.setEnabled(false); moCurExchangeRate.setEnabled(false); jbExchangeRateSystemOrigin.setEnabled(false); jckDateMaturityRo.setSelected(true); } public void actionDateMaturityRo() { loadLayoutRow(); } public void actionAccountAll() { loadLayoutRow(); } @SuppressWarnings("unchecked") public void showDps(final boolean isNeedValidateRows) { String sql = ""; ResultSet resulSet = null; Vector<SGridRow> rows = new Vector<SGridRow>(); mvLayoutRows = new Vector<SLayoutBankRow>(); mltAccountCredit = new ArrayList<>(); Cursor cursor = getCursor(); try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); sql = createSqlQuery(); resulSet = miClient.getSession().getStatement().executeQuery(sql); while (resulSet.next()) { moRow = new SLayoutBankRow(miClient); moRow.setLayoutRowType(SModSysConsts.FIN_LAY_BANK_DPS); moRow.setPkYearId(resulSet.getInt("id_year")); moRow.setPkDocId(resulSet.getInt("id_doc")); moRow.setBizPartnerId(resulSet.getInt("id_bp")); moRow.setBizPartner(resulSet.getString("bp")); moRow.setBizPartnerCreditFiscalId(resulSet.getString("fiscal_id")); moRow.setBizPartnerBranch(resulSet.getString("bpb")); moRow.setTypeDps(resulSet.getString("code")); moRow.setNumberSer(resulSet.getString("f_num")); moRow.setDate(resulSet.getDate("dt")); moRow.setBizPartnerBranchCob(resulSet.getString("cob_code")); moRow.setSubTotal(resulSet.getDouble("f_stot_cur")); moRow.setTaxCharged(resulSet.getDouble("f_tax_cur")); moRow.setTaxRetained(resulSet.getDouble("f_ret_cur")); moRow.setTotal(resulSet.getDouble("f_tot_cur")); moRow.setBalance(new SMoney(resulSet.getDouble("f_bal_cur"), resulSet.getInt("f_id_cur"), resulSet.getDouble("f_ext_rate"),((int []) miClient.getSession().getSessionCustom().getLocalCurrencyKey())[0] )); moRow.setBalanceTot(new SMoney(0, resulSet.getInt("f_id_cur"), 0, ((int []) miClient.getSession().getSessionCustom().getLocalCurrencyKey())[0] )); moRow.setBalanceTotByBizPartner(0); moRow.setCurrencyKey((moKeyCurrencyBank.getValue().length == 0 ? SDataReadDescriptions.getCatalogueDescription(((SClientInterface) miClient), SDataConstants.CFGU_CUR, miClient.getSession().getSessionCustom().getLocalCurrencyKey(), SLibConstants.DESCRIPTION_CODE) : SDataReadDescriptions.getCatalogueDescription(((SClientInterface) miClient), SDataConstants.CFGU_CUR, moKeyCurrencyBank.getValue(), SLibConstants.DESCRIPTION_CODE))); moRow.setCurrencyKeyCy(resulSet.getString("cur_key")); moRow.setTotalVat(resulSet.getDouble("f_iva_cur")); moRow.setDateMaturityRo(resulSet.getDate("dt_mat")); moRow.setCurrencyId(mnCurrencyId); renderBankAccountCredit(resulSet.getInt("fid_bpb"), mnLayoutBank); renderBizPartner(miClient.getSession().getConfigCompany().getCompanyId()); moRow.setAccountCredit(msAccountCredit); moRow.setEmail(resulSet.getString("email_01")); moRow.setCf(0); moRow.setApply(1); moRow.setAccountDebit(msAccountDebit); moRow.setBizPartnerDebitFiscalId(msDebitFiscalId); moRow.setIsForPayment(false); moRow.setIsToPayed(false); moRow.setReference(resulSet.getString("f_num")); moRow.setAccType("CLA"); moRow.setConcept(moTextConcept.getValue()); moRow.setDescription(moTextConcept.getValue()); moRow.setAccountCreditArray(maAccountCredit); moRow.setBranchBankAccountCreditArray(maBranchBankAccountsCredit); moRow.setObservation(""); if (moDateDateDue.getValue().equals(resulSet.getDate("dt_mat")) && maBranchBankAccountsCredit.size() > 0) { rows.add(moRow); mltAccountCredit.add(maAccountCredit); } mvLayoutRows.add(moRow); } moGridPayments.populateGrid(rows); moGridPayments.createGridColumns(); moGridPayments.getTable().getTableHeader().setEnabled(false); moGridPayments.getTable().setColumnSelectionAllowed(false); moGridPayments.getTable().getTableHeader().setReorderingAllowed(false); moGridPayments.getTable().getTableHeader().setResizingAllowed(true); moGridPayments.getTable().setRowSorter(new TableRowSorter<AbstractTableModel>(moGridPayments.getModel())); moGridPayments.getTable().getColumnModel().getColumn(COL_APP_PAY_BANK).setCellEditor(null); if (moGridPayments.getTable().getRowCount() > 0) { moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); moTableCellEditorOptions.setAccounts(mltAccountCredit); } } catch (Exception e) { SLibUtils.showException(this, e); } finally { if (isNeedValidateRows && moGridPayments.getTable().getRowCount() <= 0) { miClient.showMsgBoxInformation("No se encontró ningún documento para los parámetros especificados."); } setCursor(cursor); } } public void showSupplier(final boolean isNeedValidateRows) { String sql = ""; ResultSet resulSet = null; Vector<SGridRow> rows = new Vector<SGridRow>(); mvLayoutRows = new Vector<SLayoutBankRow>(); mltAccountCredit = new ArrayList<>(); Cursor cursor = getCursor(); try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); sql = createSqlQuery(); resulSet = miClient.getSession().getStatement().executeQuery(sql); while (resulSet.next()) { moRow = new SLayoutBankRow(miClient); moRow.setLayoutRowType(SModSysConsts.FIN_LAY_BANK_ADV); //moRow.setPkYearId(resulSet.getInt(4)); //moRow.setPkDocId(resulSet.getInt(5)); moRow.setBizPartnerId(resulSet.getInt(1)); moRow.setBizPartner(resulSet.getString(2)); moRow.setBizPartnerKey(resulSet.getString(6)); moRow.setBizPartnerCreditFiscalId(resulSet.getString(4)); /* moRow.setBizPartnerBranch(resulSet.getString(18)); moRow.setTypeDps(resulSet.getString(17)); moRow.setNumberSer(resulSet.getString(7)); moRow.setDate(resulSet.getDate(6)); moRow.setBizPartnerBranchCob(resulSet.getString(19)); moRow.setSubTotal(resulSet.getDouble(8)); moRow.setTaxCharged(resulSet.getDouble(9)); moRow.setTaxRetained(resulSet.getDouble(10)); moRow.setTotal(resulSet.getDouble(11)); moRow.setBalance(resulSet.getDouble(13)); */ moRow.setBalanceTot(new SMoney(0d, 0)); moRow.setBalanceTotByBizPartner(0); moRow.setCurrencyKey(resulSet.getString(5)); /* moRow.setTotalVat(resulSet.getDouble(21)); moRow.setDateMaturityRo(resulSet.getDate(22)); */ moRow.setCurrencyId(mnCurrencyId); renderBankAccountCredit(resulSet.getInt(7), mnLayoutBank); renderBizPartner(miClient.getSession().getConfigCompany().getCompanyId()); moRow.setAccountCredit(msAccountCredit); moRow.setEmail(resulSet.getString(3)); moRow.setCf(0); moRow.setApply(1); moRow.setAccountDebit(msAccountDebit); moRow.setBizPartnerDebitFiscalId(msDebitFiscalId); moRow.setIsForPayment(false); moRow.setIsToPayed(false); //moRow.setReference(resulSet.getString(7)); moRow.setAccType("CLA"); moRow.setConcept(moTextConcept.getValue()); moRow.setDescription(moTextConcept.getValue()); moRow.setAccountCreditArray(maAccountCredit); moRow.setBranchBankAccountCreditArray(maBranchBankAccountsCredit); moRow.setObservation(""); if (maBranchBankAccountsCredit.size() > 0) { rows.add(moRow); mltAccountCredit.add(maAccountCredit); } mvLayoutRows.add(moRow); } moGridPayments.populateGrid(rows); moGridPayments.createGridColumns(); moGridPayments.getTable().setColumnSelectionAllowed(false); moGridPayments.getTable().getTableHeader().setReorderingAllowed(false); moGridPayments.getTable().getTableHeader().setResizingAllowed(true); moGridPayments.getTable().setRowSorter(new TableRowSorter<AbstractTableModel>(moGridPayments.getModel())); moGridPayments.getTable().getTableHeader().setEnabled(false); if (moGridPayments.getTable().getRowCount() > 0) { moGridPayments.renderGridRows(); moGridPayments.setSelectedGridRow(0); moTableCellEditorOptions.setAccounts(mltAccountCredit); } } catch (Exception e) { SLibUtils.showException(this, e); } finally { if (isNeedValidateRows && moGridPayments.getTable().getRowCount() <= 0) { miClient.showMsgBoxInformation("No se encontró ningún documento para los parámetros especificados."); } setCursor(cursor); } } @Override public void addAllListeners() { moKeyLayouId.addItemListener(this); moKeyBankLayoutType.addItemListener(this); moKeyAccountDebit.addItemListener(this); moKeyCurrencyBank.addItemListener(this); moKeyCurrencyDoc.addItemListener(this); jckDateMaturityRo.addItemListener(this); jckAccountAll.addItemListener(this); jbLayoutPath.addActionListener(this); jbShowDocs.addActionListener(this); jbCleanDocs.addActionListener(this); jbSelectAll.addActionListener(this); jbCleanAll.addActionListener(this); jbPickRecord.addActionListener(this); jbActualExR.addActionListener(this); jbRefreshExR.addActionListener(this); jbExchangeRateSystemOrigin.addActionListener(this); } @Override public void removeAllListeners() { moKeyLayouId.removeItemListener(this); moKeyBankLayoutType.removeItemListener(this); moKeyAccountDebit.removeItemListener(this); jbLayoutPath.removeActionListener(this); jbShowDocs.removeActionListener(this); jbCleanDocs.removeActionListener(this); jbSelectAll.removeActionListener(this); jbCleanAll.removeActionListener(this); jbPickRecord.removeActionListener(this); jbActualExR.removeActionListener(this); jbRefreshExR.removeActionListener(this); jckDateMaturityRo.removeItemListener(this); jckAccountAll.removeItemListener(this); jbExchangeRateSystemOrigin.removeActionListener(this); moKeyCurrencyBank.removeItemListener(this); } @Override public void reloadCatalogues() { moKeyAccountDebit.removeAllItems(); renderLayoutTypeBank(); } @Override public void setRegistry(SDbRegistry registry) throws Exception { moRegistry = (SDbBankLayout) registry; mnFormResult = SLibConsts.UNDEFINED; mbFirstActivation = true; jtfRows.setText("0/0"); jckAccountAll.setSelected(true); mnNumberDocs = 0; moCurrentRecord = null; maXmlRows = new ArrayList<SLayoutBankXmlRow>(); maBankRecords = new ArrayList<SLayoutBankRecord>(); maLocks = new ArrayList<SSrvLock>(); renderRecord(); removeAllListeners(); populateLayoutType(); reloadCatalogues(); if (moRegistry.isRegistryNew()) { jckDateMaturityRo.setSelected(true); initializateNewLayout(); renderBankLayoutSettings(); } else { jckDateMaturityRo.setSelected(false); jtfRegistryNumber.setText(SLibUtils.textKey(moRegistry.getPrimaryKey())); jtfRegistryKey.setText(SLibUtils.textKey(moRegistry.getPrimaryKey())); moDateDate.setValue(moRegistry.getDateLayout()); moDateDateDue.setValue(moRegistry.getDateDue()); moIntConsecutiveDay.setValue(moRegistry.getConsecutive()); moKeyBankLayoutType.setValue(new int[] { moRegistry.getFkBankLayoutTypeId() }); moKeyLayouId.setValue((int[]) moKeyBankLayoutType.getSelectedItem().getComplement()); renderAccountSettings(new int[] { moRegistry.getFkBankCompanyBranchId(), moRegistry.getFkBankAccountCashId() }); moKeyCurrencyBank.setValue(new int[] { mnCurrencyId }); moCurExchangeRate.setCompoundText(SDataReadDescriptions.getCatalogueDescription(((SClientInterface) miClient), SDataConstants.CFGU_CUR, new int[] { moKeyCurrencyBank.getValue()[0] }, SLibConstants.DESCRIPTION_CODE)); miClient.getSession().populateCatalogue(moKeyAccountDebit, SModConsts.FIN_ACC_CASH, SModConsts.FINX_ACC_CASH_BANK, new SGuiParams( new int[] { moKeyCurrencyBank.getValue()[0], ((int[]) ((SGuiItem) moKeyBankLayoutType.getSelectedItem()).getForeignKey())[1] })); moKeyAccountDebit.setValue(new int[] { moRegistry.getFkBankCompanyBranchId(), moRegistry.getFkBankAccountCashId() }); moKeyCurrencyDoc.setValue(new int[] { moRegistry.getFkDocsCur() }); if (moKeyCurrencyBank.getValue()[0] == moKeyCurrencyDoc.getValue()[0]) { moCurExchangeRate.setEnabled(false); jbExchangeRateSystemOrigin.setEnabled(false); } renderBankLayoutSettings(); moTextConcept.setValue(moRegistry.getConcept()); } moTextLayoutPath.setValue(""); if (mnFormSubtype == SModConsts.FIN_REC) { loadPaymentsXml(); moDecBalanceTot.setValue(moRegistry.getAmount()); } else { if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS) { showDps(!moRegistry.isRegistryNew()); } else { showSupplier(!moRegistry.isRegistryNew()); } if (!moRegistry.getLayoutXml().isEmpty()) { updateDocsXml(); actionDateMaturityRo(); } } computeBalancePayment(); setFormEditable(true); enableGeneralFields(moRegistry.isRegistryNew()); moTextConcept.setEnabled(false); moKeyAccountDebit.setEnabled(false); moKeyBankLayoutType.setEnabled(false); moDecBalanceTot.setEditable(false); moDecBalanceTotPay.setEditable(false); moTextLayoutPath.setEditable(false); addAllListeners(); } @Override public SDbBankLayout getRegistry() throws Exception { SDbBankLayout registry = moRegistry.clone(); SLayoutBankPaymentRow payRow = null; if (mnFormSubtype != SModConsts.FIN_REC) { //registry.setPkLayBankId(); registry.setDateLayout(moDateDate.getValue()); registry.setDateDue(moDateDateDue.getValue()); registry.setConcept(moTextConcept.getValue()); registry.setConsecutive(moIntConsecutiveDay.getValue()); registry.setAmount(mdBalanceTot); //registry.setAmountPayed(mdBalancePayed); //registry.setTransfersPayed(); registry.setDocs(mnNumberDocs); //registry.setDocsPayed(); //registry.setLayoutText(msLayoutText); //registry.setLayoutXml(msLayoutText); registry.setDeleted(false); registry.setFkBankLayoutTypeId(mnLayoutSubtype); registry.setFkBankCompanyBranchId(moDataAccountCash.getPkCompanyBranchId()); registry.setFkBankAccountCashId(moDataAccountCash.getPkAccountCashId()); registry.setFkDocsCur(moKeyCurrencyDoc.getValue()[0]); /* registry.setFkUserInsertId(); registry.setFkUserUpdateId(); registry.setTsUserInsert(); registry.setTsUserUpdate(); */ registry.setAuxTitle(moKeyBankLayoutType.getSelectedItem().getItem().toLowerCase()); registry.setAuxLayoutPath(moTextLayoutPath.getValue()); registry.setPostSaveTarget(registry); registry.setPostSaveMethod(registry.getClass().getMethod("writeLayout", SGuiClient.class)); registry.setPostSaveMethodArgs(new Object[] { miClient }); } registry.getXmlRows().addAll(maXmlRows); if (mnFormSubtype != SModConsts.FIN_REC) { registry.setTransactionType(mnFormSubtype == SModSysConsts.FIN_LAY_BANK_DPS ? SFinConsts.LAY_BANK_TYPE_DPS : SFinConsts.LAY_BANK_TYPE_ADV); } if (mnFormSubtype == SModConsts.FIN_REC) { for (SGridRow rowAux : moGridPayments.getModel().getGridRows()) { payRow = (SLayoutBankPaymentRow) rowAux; if (payRow.getFinRecordLayout() != null || payRow.getFinRecordLayoutOld() != null) { registry.getBankPaymentRows().add(payRow); } } registry.setTransfers(moGridPayments.getModel().getGridRows().size()); } registry.setExchangeRate(1); if (!maLocks.isEmpty()) { registry.getLocks().addAll(maLocks); } return registry; } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); if (validation.isValid()) { if (mnLayoutBank != moDataBizPartnerBranchBankAccount.getFkBankId()) { validation.setMessage("El valor para el campo '" + SGuiUtils.getLabelName(jlAccountDebit) + "', debe pertenecer al banco '" + SDataReadDescriptions.getCatalogueDescription((SClientInterface) miClient, SDataConstants.BPSU_BP, new int[] { mnLayoutBank }, SLibConstants.DESCRIPTION_CODE) + "'."); validation.setComponent(moKeyAccountDebit); } if (validation.isValid()) { if (moTextLayoutPath.getValue().length() == 0 && mnFormSubtype != SModConsts.FIN_REC) { validation.setMessage(SGuiConsts.ERR_MSG_FIELD_REQ + "'" + SGuiUtils.getLabelName(jlLayoutPath) + "'."); validation.setComponent(jbLayoutPath); } } if (validation.isValid()) { try { for (SSrvLock lock : maLocks) { SSrvUtils.verifyLockStatus(miClient.getSession(), lock); } } catch (Exception e) { validation.setMessage("No fue posible validar el acceso exclusivo al registro de una de las pólizas seleccionadas." + e); validation.setComponent(jbCancel); } } } return validation; } @Override public void actionSave() { try { if (mnFormSubtype == SModConsts.FIN_REC) { super.actionSave(); } else { if (validateDebtsToPay()) { //createLayoutText(); createLayoutXml(); super.actionSave(); } } } catch (Exception e) { SLibUtils.showException(this, e); } } @Override public void actionCancel() { if (jbCancel.isEnabled()) { try { for (SSrvLock lock : maLocks) { SSrvUtils.releaseLock(miClient.getSession(), lock); } } catch (Exception e) { SLibUtils.showException(this, e); } mnFormResult = SGuiConsts.FORM_RESULT_CANCEL; dispose(); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); if (button == jbLayoutPath) { actionLoadLayoutPath(); } else if (button == jbShowDocs) { actionShowDocs(); } else if (button == jbCleanDocs) { actionCleanDocs(); } else if (button == jbSelectAll) { actionSelectAll(); } else if (button == jbCleanAll) { actionCleanAll(); } else if (button == jbPickRecord) { actionPickRecord(); } else if (button == jbExchangeRateSystemOrigin) { actionExchangeRateSystemOrigin(); } else if (button == jbActualExR) { actionActualExchangeRate(); } else if (button == jbRefreshExR) { actionRefreshExchangeRate(); } } } @Override public void editingStopped(ChangeEvent e) { switch (moGridPayments.getTable().getSelectedColumn()) { case COL_APP: processEditingAppPayment(); break; case COL_APP_PAY: if (mnFormSubtype == SModConsts.FIN_REC) { processEditingAppPayment(); } else if (mnFormSubtype == SModSysConsts.FIN_LAY_BANK_ADV) { processEditingStoppedBalance(); // Is for advances for payment } break; case COL_BAL: processEditingStoppedBalance(); break; case COL_TC: if (moKeyCurrencyBank.getValue()[0] == moKeyCurrencyDoc.getValue()[0]) { miClient.showMsgBoxWarning("No se puede modificar el campo 'Tipo de cambio', el banco y documento tienen la misma moneda."); } else { processEditingStoppedBalance(); } break; default: break; } } @Override public void editingCanceled(ChangeEvent e) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof JComboBox && e.getStateChange() == ItemEvent.SELECTED) { JComboBox comboBox = (JComboBox) e.getSource(); if (comboBox == moKeyLayouId) { itemStateChangedLayout(); } else if (comboBox == moKeyBankLayoutType) { itemStateChangedBankLayoutTypeId(); } else if (comboBox == moKeyAccountDebit) { itemStateChangedAccountDebit(); } else if (comboBox == moKeyCurrencyBank) { itemStateChangedCurrencyBank(); } else if (comboBox == moKeyCurrencyDoc) { itemStateChangedCurrencyDock(); } } else if (e.getSource() instanceof javax.swing.JCheckBox) { JCheckBox checkBox = (JCheckBox) e.getSource(); if (checkBox == jckDateMaturityRo) { actionDateMaturityRo(); } else if (checkBox == jckAccountAll) { actionAccountAll(); } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.seebetter.ini.chips; import ch.unizh.ini.jaer.chip.retina.AETemporalConstastRetina; import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor; import ch.unizh.ini.jaer.projects.davis.frames.DavisFrameAviWriter; import eu.seebetter.ini.chips.davis.AutoExposureController; import eu.seebetter.ini.chips.davis.DavisAutoShooter; import net.sf.jaer.eventprocessing.filter.ApsDvsEventFilter; import net.sf.jaer.eventprocessing.label.SimpleOrientationFilter; /** * Constants for DAVIS AE data format such as raw address encodings. * * @author Christian/Tobi (added IMU) * @see eu.seebetter.ini.chips.davis.DavisBaseCamera */ abstract public class DavisChip extends AETemporalConstastRetina { /** * Field for decoding pixel address and data type */ public static final int YSHIFT = 22, YMASK = 511 << YSHIFT, // 9 bits from bits 22 to 30 XSHIFT = 12, XMASK = 1023 << XSHIFT, // 10 bits from bits 12 to 21 POLSHIFT = 11, POLMASK = 1 << POLSHIFT, // , // 1 bit at bit 11 EVENT_TYPE_SHIFT = 10, EVENT_TYPE_MASK = 3 << EVENT_TYPE_SHIFT, // these 2 bits encode readout type for APS and // other event type (IMU/DVS) for EXTERNAL_INPUT_EVENT_ADDR = 1 << EVENT_TYPE_SHIFT, // This special address is is for external pin input events IMU_SAMPLE_VALUE = 3 << EVENT_TYPE_SHIFT, // this special code is for IMU sample events HW_BGAF = 5, HW_TRACKER_CM = 6, HW_TRACKER_CLUSTER = 7, HW_OMC_EVENT = 4; // event code cannot be higher than 7 // in 3 bits /* Detects bit indicating a DVS external event of type IMU */ public static final int IMUSHIFT = 0, IMUMASK = 1 << IMUSHIFT; /* * Address-type refers to data if is it an "address". This data is either an AE address or ADC reading or an IMU * sample. */ public static final int ADDRESS_TYPE_MASK = 0x80000000, ADDRESS_TYPE_DVS = 0x00000000, ADDRESS_TYPE_APS = 0x80000000, ADDRESS_TYPE_IMU = 0x80000C00; /** * Maximal ADC value */ public static final int ADC_BITS = 10, MAX_ADC = (1 << ADC_BITS) - 1; public static final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(DavisChip.ADC_READCYCLE_MASK); /** * For ADC data, the data is defined by the reading cycle (0:reset read, 1 * first read, 2 second read, which is deprecated and not used). */ public static final int ADC_DATA_MASK = MAX_ADC, ADC_READCYCLE_SHIFT = 10, ADC_READCYCLE_MASK = 0xC00; /** * Property change events fired when these properties change */ public static final String PROPERTY_FRAME_RATE_HZ = "DavisChip.FRAME_RATE_HZ", PROPERTY_MEASURED_EXPOSURE_MS = "ApsDvsChip.EXPOSURE_MS"; public static final String PROPERTY_AUTO_EXPOSURE_ENABLED = "autoExposureEnabled"; public DavisChip() { addDefaultEventFilter(ApsDvsEventFilter.class); addDefaultEventFilter(ApsFrameExtractor.class); addDefaultEventFilter(DavisAutoShooter.class); addDefaultEventFilter(SimpleOrientationFilter.class); addDefaultEventFilter(DavisFrameAviWriter.class); } /** * Returns maximum ADC count value * * @return max value, e.g. 1023 */ abstract public int getMaxADC(); /** * Turns off bias generator * * @param powerDown * true to turn off */ abstract public void setPowerDown(boolean powerDown); /** * Returns measured frame rate * * @return frame rate in Hz */ abstract public float getFrameRateHz(); /** * Returns start of exposure time in timestamp tick units (us). Note this is * particularly relevant for global shutter mode. For rolling shutter * readout mode, this time is the start of exposure time of the first * column. * * @return start of exposure time in timestamp units (us). */ abstract public int getFrameExposureStartTimestampUs(); /** * Returns end of exposure time in timestamp tick units (us). Note this is * particularly relevant for global shutter mode. For rolling shutter * readout mode, this time is the last value read from last column. * * @return start of exposure time in timestamp units (us). */ abstract public int getFrameExposureEndTimestampUs(); /** * Returns measured exposure time * * @return exposure time in ms */ abstract public float getMeasuredExposureMs(); /** * Triggers the taking of one snapshot, i.e, triggers a frame capture. */ abstract public void takeSnapshot(); /** * Turns on/off ADC * * @param adcEnabled * true to turn on */ abstract public void setADCEnabled(boolean adcEnabled); /** * Controls exposure value automatically if auto exposure is enabled. * */ abstract public void controlExposure(); /** * Returns the automatic APS exposure controller * * @return the controller */ abstract public AutoExposureController getAutoExposureController(); /** * Sets threshold for automatically triggers snapshot images * * @param thresholdEvents * set to zero to disable automatic snapshots */ abstract public void setAutoshotThresholdEvents(int thresholdEvents); /** * Returns threshold * * @return threshold. Zero means auto-shot is disabled. */ abstract public int getAutoshotThresholdEvents(); /** * Sets whether automatic exposure control is enabled * * @param yes */ abstract public void setAutoExposureEnabled(boolean yes); /** * Returns if automatic exposure control is enabled. * * @return */ abstract public boolean isAutoExposureEnabled(); /** * Returns if the image histogram should be displayed. * * @return true if it should be displayed. */ abstract public boolean isShowImageHistogram(); /** * Sets if the image histogram should be displayed. * * @param yes * true to show histogram */ abstract public void setShowImageHistogram(boolean yes); /** * Returns the frame counter value. This value is set on each end-of-frame * sample. * * @return the frameCount */ public abstract int getFrameCount(); }
package mathsquared.resultswizard2; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Test; /** * @author MathSquared * */ public class SyntaxParserTest { /** * Test method for {@link mathsquared.resultswizard2.SyntaxParser#parseQuotedSyntax(java.lang.String)}. * * Tests the String <code>"a" "b" "c""d"</code>. */ @Test public void testParseQuotedSyntax () { String[] parsed = SyntaxParser.parseQuotedSyntax("\"a\" \"b\" \"c\"\"d\""); // assertTrue("quoted syntax: space-separated with one quote escape", Arrays.equals(parsed, new String[] {"a", "b", "c\"d"})); assertArrayEquals("quoted syntax: space-separated with one quote escape", new String[] {"a", "b", "c\"d"}, parsed); } /** * Test method for {@link mathsquared.resultswizard2.SyntaxParser#createPairwiseMap(T[])}. */ @Test public void testCreatePairwiseMap () { Map<Integer, Integer> pairs = SyntaxParser.createPairwiseMap(new Integer[] {1, 2, 3, 4, 5}); Map<Integer, Integer> expected = new HashMap<Integer, Integer>(); expected.put(1, 2); expected.put(3, 4); assertTrue("pairwise: five integers", pairs.equals(expected)); } /** * Test method for {@link mathsquared.resultswizard2.SyntaxParser#parseIntegerList(java.lang.String)}. */ @Test public void testParseIntegerList () { int[] parsed = SyntaxParser.parseIntegerList("1 2,3 4.5$"); assertTrue("integer list: five integers, various separators, trailing", Arrays.equals(parsed, new int[] {1, 2, 3, 4, 5})); } }
package eventdetection.pipeline; import java.io.Closeable; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import toberumono.json.JSONObject; import toberumono.json.JSONSystem; import eventdetection.aggregator.AggregatorController; import eventdetection.common.Article; import eventdetection.common.ArticleManager; import eventdetection.common.DBConnection; import eventdetection.common.Query; import eventdetection.common.SubprocessHelpers; import eventdetection.common.ThreadingUtils; import eventdetection.downloader.DownloaderController; import eventdetection.validator.ValidationResult; import eventdetection.validator.ValidatorController; /** * Implements an easily-expanded pipeline system for the project. * * @author Joshua Lipstone */ public class Pipeline implements PipelineComponent, Closeable { private static final Logger logger = LoggerFactory.getLogger("Pipeline"); private final ArticleManager articleManager; private final List<PipelineComponent> components; private boolean closed; /** * Creates a new {@link Pipeline} instance. * * @param config * a {@link JSONObject} holding the configuration data for the {@link Pipeline} and its components * @param queryIDs * the IDs of the {@link Query Queries} to use. This must be empty or {@code null} for the downloader to be * run * @param articleIDs * the IDs of the {@link Article Articles} to use. This must be empty or {@code null} for the downloader to be * run * @param addDefaultComponents * whether the default pipeline components should be added (Downloader, preprocessors, and Validator) * @throws IOException * if an error occurs while initializing the Downloader * @throws SQLException * if an error occurs while connecting to the database */ public Pipeline(JSONObject config, Collection<Integer> queryIDs, Collection<Integer> articleIDs, boolean addDefaultComponents) throws IOException, SQLException { final Collection<Integer> qIDs = queryIDs == null ? Collections.emptyList() : queryIDs, aIDs = articleIDs == null ? Collections.emptyList() : articleIDs; articleManager = new ArticleManager(config); components = new ArrayList<>(); if (addDefaultComponents) { addComponent((queries, articles, results) -> ThreadingUtils.loadQueries(qIDs, queries)); addComponent((queries, articles, results) -> ThreadingUtils.cleanUpArticles(articleManager)); addComponent((queries, articles, results) -> ThreadingUtils.loadArticles(articleManager, aIDs, articles)); if (articleIDs.size() == 0) { //Only run the Downloader if no articles are specified. addComponent(new DownloaderController(config)); addComponent((queries, articles, results) -> { try { SubprocessHelpers.executePythonProcess(Paths.get("./ArticleProcessorDaemon.py"), "--no-lock").waitFor(); } catch (InterruptedException e) {} }); addComponent((queries, articles, results) -> { try { SubprocessHelpers.executePythonProcess(Paths.get("./QueryProcessorDaemon.py"), "--no-lock").waitFor(); } catch (InterruptedException e) {} }); } addComponent(new ValidatorController(config)); addComponent(new AggregatorController(config)); addComponent(Pipeline::filterUsedArticles); addComponent(new Notifier()); } } private static void filterUsedArticles(Map<Integer, Query> queries, Map<Integer, Article> articles, Collection<ValidationResult> results) throws IOException, SQLException { Connection connection = DBConnection.getConnection(); ValidationResult res; try (PreparedStatement seek = connection.prepareStatement("select * from query_articles where query = ? and article = ? and notification_sent = ?"); PreparedStatement update = connection.prepareStatement("insert into query_articles (query, article, notification_sent) values (?, ?, ?) " + "on conflict (query, article) do update set (notification_sent) = (EXCLUDED.notification_sent)")) { seek.setBoolean(3, true); update.setBoolean(3, true); for (Iterator<ValidationResult> iter = results.iterator(); iter.hasNext();) { res = iter.next(); seek.setInt(1, res.getQueryID()); seek.setInt(2, res.getArticleID()); try (ResultSet rs = seek.executeQuery()) { if (rs.next()) //If we've already used it, don't bother iter.remove(); else { update.setInt(1, res.getQueryID()); update.setInt(2, res.getArticleID()); update.executeUpdate(); } } } } } /** * Main method for the {@link Pipeline} entry point. * * @param args * the command-line arguments * @throws IOException * if an error occurs while initializing the Downloader * @throws SQLException * if an error occurs while connecting to the database */ public static void main(String[] args) throws IOException, SQLException { Path configPath = Paths.get("./configuration.json"); //The configuration file defaults to "./configuration.json", but can be changed with arguments int action = 0; boolean actionSet = false; final Collection<Integer> articleIDs = new LinkedHashSet<>(), queryIDs = new LinkedHashSet<>(); for (String arg : args) { try { if (arg.equalsIgnoreCase("-c")) { action = 0; actionSet = true; } else if (arg.equalsIgnoreCase("-a")) { action = 1; actionSet = true; } else if (arg.equalsIgnoreCase("-q")) { action = 2; actionSet = true; } else if (action == 0) configPath = Paths.get(arg); else if (action == 1) articleIDs.add(Integer.parseInt(arg)); else if (action == 2) queryIDs.add(Integer.parseInt(arg)); } catch (NumberFormatException e) { logger.warn(arg + " is not an integer"); } if (!actionSet) action++; if (action > 2) break; } JSONObject config = (JSONObject) JSONSystem.loadJSON(configPath); DBConnection.configureConnection((JSONObject) config.get("database")); try (Pipeline pipeline = new Pipeline(config, queryIDs, articleIDs, true)) { pipeline.execute(); } } /** * Adds a {@link PipelineComponent} to the {@link Pipeline} * * @param component * the {@link PipelineComponent} to add * @return the {@link Pipeline} for chaining purposes */ public Pipeline addComponent(PipelineComponent component) { components.add(component); return this; } @Override public void execute(Map<Integer, Query> queries, Map<Integer, Article> articles, Collection<ValidationResult> results) throws IOException, SQLException { ThreadingUtils.executeTask(() -> { for (PipelineComponent pc : components) pc.execute(queries, articles, results); }); } @Override public void close() throws IOException { if (closed) return; closed = true; articleManager.close(); IOException except = null; for (PipelineComponent comp : components) { try { if (comp instanceof Closeable) ((Closeable) comp).close(); } catch (IOException e) { except = e; } } if (except != null) throw except; } }