repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
debabratahazra/DS
designstudio/components/workbench/core/com.odcgroup.workbench.core/src/main/java/com/odcgroup/workbench/core/template/StandardModelsTemplateDescriptor.java
1397
package com.odcgroup.workbench.core.template; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.odcgroup.template.TemplateDescriptor; public class StandardModelsTemplateDescriptor extends TemplateDescriptor { private String modelsProjectName; private String genProjectName; private File standardModelsPom; private File standardGenPom; public StandardModelsTemplateDescriptor(String modelsProjectName, String genProjectName, File standardModelsJar, File standardModelsPom, File standardGenPom, String name, String description) { super(standardModelsJar, name, description, null, null, Arrays.asList(modelsProjectName, genProjectName)); this.modelsProjectName = modelsProjectName; this.genProjectName = genProjectName; this.standardModelsPom = standardModelsPom; this.standardGenPom = standardGenPom; } public File getStandardModelsJar() { return getTemplateJar(); } public File getStandardModelsPom() { return standardModelsPom; } public String getStandardModelsName() { return modelsProjectName; } public String getStandardGenName() { return genProjectName; } public File getStandardGenPom() { return standardGenPom; } public List<String> getProjectsName() { return Arrays.asList( getStandardModelsJar().getName(), getStandardGenName()); } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/ui/wizards/dialogfields/TreeListDialogField.java
24036
/******************************************************************************* * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; 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.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Tree; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.layout.PixelConverter; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * A tree with a button bar. * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. * Tree model is independent of widget creation. * DialogFields controls are: Label, Tree, and Composite containing buttons. * * @param <E> the type of the root elements */ public class TreeListDialogField<E> extends DialogField { protected TreeViewer fTree; protected ILabelProvider fLabelProvider; protected TreeViewerAdapter fTreeViewerAdapter; protected List<E> fElements; protected ViewerComparator fViewerComparator; protected String[] fButtonLabels; private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; private int fUpButtonIndex; private int fDownButtonIndex; private Label fLastSeparator; private Tree fTreeControl; private Composite fButtonsControl; private ISelection fSelectionWhenEnabled; private ITreeListAdapter<E> fTreeAdapter; private Object fParentElement; private int fTreeExpandLevel; /** * @param adapter Can be <code>null</code>. */ public TreeListDialogField(ITreeListAdapter<E> adapter, String[] buttonLabels, ILabelProvider lprovider) { super(); fTreeAdapter= adapter; fLabelProvider= lprovider; fTreeViewerAdapter= new TreeViewerAdapter(); fParentElement= this; fElements= new ArrayList<>(10); fButtonLabels= buttonLabels; if (fButtonLabels != null) { int nButtons= fButtonLabels.length; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsEnabled[i]= true; } } fTree= null; fTreeControl= null; fButtonsControl= null; fRemoveButtonIndex= -1; fUpButtonIndex= -1; fDownButtonIndex= -1; fTreeExpandLevel= 0; } /** * Sets the index of the 'remove' button in the button label array passed in * the constructor. The behavior of the button marked as the 'remove' button * will then be handled internally. (enable state, button invocation * behavior) */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); fRemoveButtonIndex= removeButtonIndex; } /** * Sets the index of the 'up' button in the button label array passed in the * constructor. The behavior of the button marked as the 'up' button will * then be handled internally. * (enable state, button invocation behavior) */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); fUpButtonIndex= upButtonIndex; } /** * Sets the index of the 'down' button in the button label array passed in * the constructor. The behavior of the button marked as the 'down' button * will then be handled internally. (enable state, button invocation * behavior) */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); fDownButtonIndex= downButtonIndex; } /** * Sets the viewer comparator. * @param viewerComparator The viewer comparator to set */ public void setViewerComparator(ViewerComparator viewerComparator) { fViewerComparator= viewerComparator; } public void setTreeExpansionLevel(int level) { fTreeExpandLevel= level; if (isOkToUse(fTreeControl) && fTreeExpandLevel > 0) { fTree.expandToLevel(level); } } // ------ adapter communication private void buttonPressed(int index) { if (!managedButtonPressed(index) && fTreeAdapter != null) { fTreeAdapter.customButtonPressed(this, index); } } /** * Checks if the button pressed is handled internally * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); } else if (index == fUpButtonIndex) { up(); } else if (index == fDownButtonIndex) { down(); } else { return false; } return true; } // ------ layout helpers /* * @see DialogField#doFillIntoGrid */ @Override public Control[] doFillIntoGrid(Composite parent, int nColumns) { PixelConverter converter= new PixelConverter(parent); assertEnoughColumns(nColumns); Label label= getLabelControl(parent); GridData gd= gridDataForLabel(1); gd.verticalAlignment= GridData.BEGINNING; label.setLayoutData(gd); Control list= getTreeControl(parent); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= GridData.FILL; gd.grabExcessVerticalSpace= true; gd.horizontalSpan= nColumns - 2; gd.widthHint= converter.convertWidthInCharsToPixels(50); gd.heightHint= converter.convertHeightInCharsToPixels(6); list.setLayoutData(gd); Composite buttons= getButtonBox(parent); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= GridData.FILL; gd.grabExcessVerticalSpace= true; gd.horizontalSpan= 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls */ @Override public int getNumberOfControls() { return 3; } /** * Sets the minimal width of the buttons. Must be called after widget creation. */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { ((GridData) fLastSeparator.getLayoutData()).widthHint= minWidth; } } // ------ UI creation /** * Returns the tree control. When called the first time, the control will be * created. * @param parent The parent composite when called the first time, or <code>null</code> * after. */ public Control getTreeControl(Composite parent) { if (fTreeControl == null) { assertCompositeNotNull(parent); fTree= createTreeViewer(parent); fTreeControl= (Tree) fTree.getControl(); fTreeControl.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { handleKeyPressed(e); } }); fTree.setContentProvider(fTreeViewerAdapter); fTree.setLabelProvider(fLabelProvider); fTree.addSelectionChangedListener(fTreeViewerAdapter); fTree.addDoubleClickListener(fTreeViewerAdapter); fTree.setInput(fParentElement); fTree.expandToLevel(fTreeExpandLevel); if (fViewerComparator != null) { fTree.setComparator(fViewerComparator); } fTreeControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); } } return fTreeControl; } /** * @return the internally used tree viewer, or <code>null</code> if the UI has not been created yet */ public TreeViewer getTreeViewer() { return fTree; } /** * @param idx the index of the button * @return the button control, or <code>null</code> if the UI has not been created yet */ public Button getButton(int idx) { return fButtonControls[idx]; } /* * Subclasses may override to specify a different style. */ protected int getTreeStyle() { int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL; return style; } protected TreeViewer createTreeViewer(Composite parent) { Tree tree= new Tree(parent, getTreeStyle()); tree.setFont(parent.getFont()); return new TreeViewer(tree); } protected Button createButton(Composite parent, String label, SelectionListener listener) { Button button= new Button(parent, SWT.PUSH); button.setFont(parent.getFont()); button.setText(label); button.addSelectionListener(listener); GridData gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= GridData.BEGINNING; gd.widthHint= SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { Label separator= new Label(parent, SWT.NONE); separator.setFont(parent.getFont()); separator.setVisible(false); GridData gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.verticalAlignment= GridData.BEGINNING; gd.heightHint= 4; separator.setLayoutData(gd); return separator; } /** * Returns the composite containing the buttons. When called the first time, the control * will be created. * @param parent The parent composite when called the first time, or <code>null</code> * after. */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); SelectionListener listener= new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } @Override public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; Composite contents= new Composite(parent, SWT.NONE); contents.setFont(parent.getFont()); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; contents.setLayout(layout); if (fButtonLabels != null) { fButtonControls= new Button[fButtonLabels.length]; for (int i= 0; i < fButtonLabels.length; i++) { String currLabel= fButtonLabels[i]; if (currLabel != null) { fButtonControls[i]= createButton(contents, currLabel, listener); fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); } else { fButtonControls[i]= null; createSeparator(contents); } } } fLastSeparator= createSeparator(contents); updateButtonState(); fButtonsControl= contents; } return fButtonsControl; } private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { for (int i= 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; } } } } /** * Handles key events in the table viewer. Specifically * when the delete key is pressed. */ protected void handleKeyPressed(KeyEvent event) { if (event.character == SWT.DEL && event.stateMask == 0) { if (fRemoveButtonIndex != -1 && isButtonEnabled(fTree.getSelection(), fRemoveButtonIndex)) { managedButtonPressed(fRemoveButtonIndex); return; } } fTreeAdapter.keyPressed(this, event); } // ------ enable / disable management /* * @see DialogField#dialogFieldChanged */ @Override public void dialogFieldChanged() { super.dialogFieldChanged(); updateButtonState(); } /* * Updates the enable state of the all buttons */ protected void updateButtonState() { if (fButtonControls != null && isOkToUse(fTreeControl) && fTreeControl.isEnabled()) { ISelection sel= fTree.getSelection(); for (int i= 0; i < fButtonControls.length; i++) { Button button= fButtonControls[i]; if (isOkToUse(button)) { button.setEnabled(isButtonEnabled(sel, i)); } } } } protected boolean containsAttributes(List<Object> selected) { for (int i= 0; i < selected.size(); i++) { if (!fElements.contains(selected.get(i))) { return true; } } return false; } protected boolean getManagedButtonState(ISelection sel, int index) { List<Object> selected= getSelectedElements(); boolean hasAttributes= containsAttributes(selected); if (index == fRemoveButtonIndex) { return !selected.isEmpty() && !hasAttributes; } else if (index == fUpButtonIndex) { return !sel.isEmpty() && !hasAttributes && canMoveUp(selected); } else if (index == fDownButtonIndex) { return !sel.isEmpty() && !hasAttributes && canMoveDown(selected); } return true; } /* * @see DialogField#updateEnableState */ @Override protected void updateEnableState() { super.updateEnableState(); boolean enabled= isEnabled(); if (isOkToUse(fTreeControl)) { if (!enabled) { if (fSelectionWhenEnabled == null) { fSelectionWhenEnabled= fTree.getSelection(); selectElements(null); } } else if (fSelectionWhenEnabled != null) { selectElements(fSelectionWhenEnabled); } fTreeControl.setEnabled(enabled); } updateButtonState(); } /** * Sets a button enabled or disabled. */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; updateButtonState(); } } private boolean isButtonEnabled(ISelection sel, int index) { boolean extraState= getManagedButtonState(sel, index); return isEnabled() && extraState && fButtonsEnabled[index]; } // ------ model access /** * Sets the elements shown in the list. */ public void setElements(List<E> elements) { fElements= new ArrayList<>(elements); refresh(); if (isOkToUse(fTreeControl)) { fTree.expandToLevel(fTreeExpandLevel); } dialogFieldChanged(); } /** * Gets the elements shown in the list. * The list returned is a copy, so it can be modified by the user. */ public List<E> getElements() { return new ArrayList<>(fElements); } /** * Gets the element shown at the given index. */ public E getElement(int index) { return fElements.get(index); } /** * Gets the index of an element in the list or -1 if element is not in list. */ public int getIndexOfElement(Object elem) { return fElements.indexOf(elem); } /** * Replace an element. */ public void replaceElement(E oldElement, E newElement) throws IllegalArgumentException { int idx= fElements.indexOf(oldElement); if (idx != -1) { fElements.set(idx, newElement); if (isOkToUse(fTreeControl)) { List<Object> selected= getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } boolean isExpanded= fTree.getExpandedState(oldElement); fTree.remove(oldElement); fTree.add(fParentElement, newElement); if (isExpanded) { fTree.expandToLevel(newElement, fTreeExpandLevel); } selectElements(new StructuredSelection(selected)); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Adds an element at the end of the tree list. */ public boolean addElement(E element) { if (fElements.contains(element)) { return false; } fElements.add(element); if (isOkToUse(fTreeControl)) { fTree.add(fParentElement, element); fTree.expandToLevel(element, fTreeExpandLevel); } dialogFieldChanged(); return true; } /** * Adds elements at the end of the tree list. */ public boolean addElements(List<E> elements) { int nElements= elements.size(); if (nElements > 0) { // filter duplicated ArrayList<E> elementsToAdd= new ArrayList<>(nElements); for (int i= 0; i < nElements; i++) { E elem= elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } } if (!elementsToAdd.isEmpty()) { fElements.addAll(elementsToAdd); if (isOkToUse(fTreeControl)) { fTree.add(fParentElement, elementsToAdd.toArray()); for (int i= 0; i < elementsToAdd.size(); i++) { fTree.expandToLevel(elementsToAdd.get(i), fTreeExpandLevel); } } dialogFieldChanged(); return true; } } return false; } /** * Adds an element at a position. */ public void insertElementAt(E element, int index) { if (fElements.contains(element)) { return; } fElements.add(index, element); if (isOkToUse(fTreeControl)) { fTree.add(fParentElement, element); if (fTreeExpandLevel != -1) { fTree.expandToLevel(element, fTreeExpandLevel); } } dialogFieldChanged(); } /** * Adds an element at a position. */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); refresh(); dialogFieldChanged(); } } /** * Removes an element from the list. */ public void removeElement(E element) throws IllegalArgumentException { if (fElements.remove(element)) { if (isOkToUse(fTreeControl)) { fTree.remove(element); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Removes elements from the list. */ public void removeElements(List<?> elements) { if (elements.size() > 0) { fElements.removeAll(elements); if (isOkToUse(fTreeControl)) { fTree.remove(elements.toArray()); } dialogFieldChanged(); } } /** * Gets the number of elements */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { fSelectionWhenEnabled= selection; if (isOkToUse(fTreeControl)) { fTree.setSelection(selection, true); } } public void selectFirstElement() { Object element= null; if (fViewerComparator != null) { Object[] arr= fElements.toArray(); fViewerComparator.sort(fTree, arr); if (arr.length > 0) { element= arr[0]; } } else { if (fElements.size() > 0) { element= fElements.get(0); } } if (element != null) { selectElements(new StructuredSelection(element)); } } public void postSetSelection(final ISelection selection) { if (isOkToUse(fTreeControl)) { Display d= fTreeControl.getDisplay(); d.asyncExec(new Runnable() { @Override public void run() { if (isOkToUse(fTreeControl)) { selectElements(selection); } } }); } } /** * Refreshes the tree. */ @Override public void refresh() { super.refresh(); if (isOkToUse(fTreeControl)) { fTree.refresh(); } } /** * Refreshes the tree. */ public void refresh(Object element) { if (isOkToUse(fTreeControl)) { fTree.refresh(element); } } /** * Updates the element. */ public void update(Object element) { if (isOkToUse(fTreeControl)) { fTree.update(element, null); } } // ------- list maintenance private List<E> moveUp(List<E> elements, List<E> move) { int nElements= elements.size(); List<E> res= new ArrayList<>(nElements); E floating= null; for (int i= 0; i < nElements; i++) { E curr= elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } floating= curr; } } if (floating != null) { res.add(floating); } return res; } private void moveUp(List<E> toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTree.reveal(toMoveUp.get(0)); } } private void moveDown(List<E> toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTree.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } private List<E> reverse(List<E> p) { List<E> reverse= new ArrayList<>(p.size()); for (int i= p.size() - 1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } private void remove() { removeElements(getSelectedElements()); } private void up() { moveUp(getSelectedRootElements()); } private void down() { moveDown(getSelectedRootElements()); } private boolean canMoveUp(List<Object> selectedElements) { if (isOkToUse(fTreeControl)) { int nSelected= selectedElements.size(); int nElements= fElements.size(); for (int i= 0; i < nElements && nSelected > 0; i++) { if (!selectedElements.contains(fElements.get(i))) { return true; } nSelected--; } } return false; } private boolean canMoveDown(List<Object> selectedElements) { if (isOkToUse(fTreeControl)) { int nSelected= selectedElements.size(); for (int i= fElements.size() - 1; i >= 0 && nSelected > 0; i--) { if (!selectedElements.contains(fElements.get(i))) { return true; } nSelected--; } } return false; } /** * Returns the selected elements. */ public List<Object> getSelectedElements() { ArrayList<Object> result= new ArrayList<>(); if (isOkToUse(fTreeControl)) { ISelection selection= fTree.getSelection(); if (selection instanceof IStructuredSelection) { Iterator<?> iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } } } return result; } public List<E> getSelectedRootElements() { ArrayList<E> result= new ArrayList<>(); if (isOkToUse(fTreeControl)) { ISelection selection= fTree.getSelection(); if (selection instanceof IStructuredSelection) { Iterator<?> iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { Object element= iter.next(); if (fElements.contains(element)) { @SuppressWarnings("unchecked") E rootElement= (E) element; result.add(rootElement); } } } } return result; } public void expandElement(Object element, int level) { if (isOkToUse(fTreeControl)) { fTree.expandToLevel(element, level); } } // ------- TreeViewerAdapter private class TreeViewerAdapter implements ITreeContentProvider, ISelectionChangedListener, IDoubleClickListener { private final Object[] NO_ELEMENTS= new Object[0]; // ------- ITreeContentProvider Interface ------------ @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } @Override public void dispose() { } @Override public Object[] getElements(Object obj) { return fElements.toArray(); } @Override public Object[] getChildren(Object element) { if (fTreeAdapter != null) { return fTreeAdapter.getChildren(TreeListDialogField.this, element); } return NO_ELEMENTS; } @Override public Object getParent(Object element) { if (!fElements.contains(element) && fTreeAdapter != null) { return fTreeAdapter.getParent(TreeListDialogField.this, element); } return fParentElement; } @Override public boolean hasChildren(Object element) { if (fTreeAdapter != null) { return fTreeAdapter.hasChildren(TreeListDialogField.this, element); } return false; } // ------- ISelectionChangedListener Interface ------------ @Override public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } @Override public void doubleClick(DoubleClickEvent event) { doDoubleClick(event); } } protected void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fTreeAdapter != null) { fTreeAdapter.selectionChanged(this); } } protected void doDoubleClick(DoubleClickEvent event) { if (fTreeAdapter != null) { fTreeAdapter.doubleClicked(this); } } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/compositeobject/self/AttributeListOnTargetTestProject.java
1663
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.compositeobject.self; import org.eclipse.persistence.oxm.XMLDescriptor; import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLDirectMapping; public class AttributeListOnTargetTestProject extends AttributeOnTargetProject { public AttributeListOnTargetTestProject() { super(); } public XMLDescriptor getAddressDescriptor() { XMLDescriptor xmlDescriptor = super.getAddressDescriptor(); XMLCompositeDirectCollectionMapping collectionMapping = new XMLCompositeDirectCollectionMapping(); collectionMapping.setAttributeName("provinces"); collectionMapping.setXPath("@provinces"); collectionMapping.setUsesSingleNode(true); xmlDescriptor.addMapping(collectionMapping); return xmlDescriptor; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/mappings/ManyToOneMapping.java
1350
/******************************************************************************* * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * James Sutherland - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.mappings; /** * <p><b>Purpose</b>: Define the relationship to be a ManyToOne. * This is mainly functionally the same as OneToOneMapping. * * @author James Sutherland * @since EclipseLink 2.1 */ public class ManyToOneMapping extends OneToOneMapping { /** * PUBLIC: * Default constructor. */ public ManyToOneMapping() { super(); } /** * INTERNAL: * Related mapping should implement this method to return true. */ @Override public boolean isManyToOneMapping() { return true; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/events/Address.java
1323
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.events; /** * @version $Header: Address.java 17-may-2006.14:00:56 mmacivor Exp $ * @author mmacivor * @since release specific (what release of product did this appear in) */ public class Address { public String street; public boolean equals(Object obj) { if(!(obj instanceof Address)) { return false; } String objStreet = ((Address)obj).street; return objStreet == street || (objStreet != null && street != null && objStreet.equals(street)); } }
epl-1.0
citycloud-bigdata/mondrian
src/main/mondrian/xmla/impl/DynamicDatasourceXmlaServlet.java
1456
/* // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // You must accept the terms of that agreement to use this software. // // Copyright (C) 2006-2013 Pentaho // All Rights Reserved. */ package mondrian.xmla.impl; import mondrian.server.DynamicContentFinder; import mondrian.server.RepositoryContentFinder; import java.util.HashMap; import java.util.Map; /** * Extends DefaultXmlaServlet to add dynamic datasource loading capability. * * @author Thiyagu Ajit * @author Luc Boudreau */ public class DynamicDatasourceXmlaServlet extends MondrianXmlaServlet { private static final long serialVersionUID = 1L; /** * A map of datasources definitions to {@link DynamicContentFinder} * instances. */ private final Map<String, DynamicContentFinder> finders = new HashMap<String, DynamicContentFinder>(); @Override protected RepositoryContentFinder makeContentFinder(String dataSources) { if (!finders.containsKey(dataSources)) { finders.put(dataSources, new DynamicContentFinder(dataSources)); } return finders.get(dataSources); } @Override public void destroy() { for (DynamicContentFinder finder : finders.values()) { finder.shutdown(); } super.destroy(); } } // End DynamicDatasourceXmlaServlet.java
epl-1.0
OndraZizka/windup
rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/model/JPAEntityModel.java
1833
package org.jboss.windup.rules.apps.javaee.model; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.frames.Adjacency; import com.tinkerpop.frames.Property; import com.tinkerpop.frames.modules.typedgraph.TypeValue; /** * Contains metadata associated with a JPA Entity * * @author <a href="mailto:bradsdavis@gmail.com">Brad Davis</a> * @author <a href="mailto:zizka@seznam.cz">Ondrej Zizka</a> */ @TypeValue(JPAEntityModel.TYPE) public interface JPAEntityModel extends PersistenceEntityModel { String TYPE = "JPAEntityModel"; String CATALOG_NAME = TYPE + "-catalogName"; String SCHEMA_NAME = TYPE + "-schemaName"; String NAMED_QUERY = TYPE + "-namedQuery"; String SPECIFICATION_VERSION = TYPE + "-specificationVersion"; /** * Contains the specification version */ @Property(SPECIFICATION_VERSION) String getSpecificationVersion(); /** * Contains the specification version */ @Property(SPECIFICATION_VERSION) void setSpecificationVersion(String version); /** * Contains the schema name */ @Property(SCHEMA_NAME) String getSchemaName(); /** * Contains the schema name */ @Property(SCHEMA_NAME) void setSchemaName(String schemaName); /** * Contains the catalog name */ @Property(CATALOG_NAME) String getCatalogName(); /** * Contains the catalog name */ @Property(CATALOG_NAME) void setCatalogName(String catalogName); /** * Contains the jpa named query */ @Adjacency(label = NAMED_QUERY, direction = Direction.OUT) void addNamedQuery(JPANamedQueryModel model); /** * Contains the jpa named query */ @Adjacency(label = NAMED_QUERY, direction = Direction.OUT) Iterable<JPANamedQueryModel> getNamedQueries(); }
epl-1.0
MDMI/mdmimapeditor
org.mdmi.editor/src/org/openhealthtools/mdht/mdmi/editor/map/tree/EnumerationNode.java
1267
/******************************************************************************* * Copyright (c) 2012 Firestar Software, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Firestar Software, Inc. - initial API and implementation * * Author: * Sally Conway * *******************************************************************************/ package org.openhealthtools.mdht.mdmi.editor.map.tree; import org.openhealthtools.mdht.mdmi.model.EnumerationLiteral; public class EnumerationNode extends EditableObjectNode { public EnumerationNode(EnumerationLiteral literal) { super(literal); setNodeIcon(TreeNodeIcon.EnumerationIcon); } @Override public String getDisplayName(Object userObject) { return ((EnumerationLiteral) userObject).getName(); } @Override public String getToolTipText() { return ((EnumerationLiteral) getUserObject()).getDescription(); } @Override public boolean isEditable() { return true; } @Override public boolean isRemovable() { return true; } }
epl-1.0
gameduell/eclipselink.runtime
jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metamodel/proxy/MapAttributeProxyImpl.java
1524
/******************************************************************************* * Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * tware - initial implementation ******************************************************************************/ package org.eclipse.persistence.internal.jpa.metamodel.proxy; import java.util.Map; import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.Type; import org.eclipse.persistence.internal.jpa.metamodel.MapAttributeImpl; /** * A proxy class that allows EclipseLink to trigger the deployment of a persistence unit * as an MapAttribute is accessed in the metamodel. * @author tware * * @param <X> * @param <T> */ public class MapAttributeProxyImpl<X, K, V> extends PluralAttributeProxyImpl<X, Map<K, V>, V> implements MapAttribute<X, K, V> { @Override public Class<K> getKeyJavaType() { return ((MapAttributeImpl)getAttribute()).getKeyJavaType(); } @Override public Type<K> getKeyType() { return ((MapAttributeImpl)getAttribute()).getKeyType(); } }
epl-1.0
willrogers/dawnsci
org.eclipse.dawnsci.nexus/src/org/eclipse/dawnsci/nexus/impl/NXparametersImpl.java
1769
/*- ******************************************************************************* * Copyright (c) 2015 Diamond Light Source Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This file was auto-generated from the NXDL XML definition. * Generated at: 2015-09-29T13:43:53.722+01:00 *******************************************************************************/ package org.eclipse.dawnsci.nexus.impl; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; import org.eclipse.dawnsci.analysis.dataset.impl.Dataset; import org.eclipse.dawnsci.nexus.*; /** * Container for parameters, usually used in processing or analysis. * * @version 1.0 */ public class NXparametersImpl extends NXobjectImpl implements NXparameters { private static final long serialVersionUID = 1L; // no state in this class, so always compatible public static final String NX_TERM = "term"; public static final String NX_TERM_ATTRIBUTE_UNITS = "units"; protected NXparametersImpl(long oid) { super(oid); } @Override public Class<? extends NXobject> getNXclass() { return NXparameters.class; } @Override public NXbaseClass getNXbaseClass() { return NXbaseClass.NX_PARAMETERS; } @Override public IDataset getTerm() { return getDataset(NX_TERM); } public void setTerm(IDataset term) { setDataset(NX_TERM, term); } @Override public String getTermAttributeUnits() { return getAttrString(NX_TERM, NX_TERM_ATTRIBUTE_UNITS); } public void setTermAttributeUnits(String units) { setAttribute(NX_TERM, NX_TERM_ATTRIBUTE_UNITS, units); } }
epl-1.0
NABUCCO/org.nabucco.framework.base
org.nabucco.framework.base.facade.datatype/src/main/gen/org/nabucco/framework/base/facade/datatype/MultiTenantDatatype.java
6185
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the License at * * http://www.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.nabucco.framework.base.facade.datatype; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.nabucco.framework.base.facade.datatype.Datatype; import org.nabucco.framework.base.facade.datatype.Tenant; import org.nabucco.framework.base.facade.datatype.property.NabuccoProperty; import org.nabucco.framework.base.facade.datatype.property.NabuccoPropertyContainer; import org.nabucco.framework.base.facade.datatype.property.NabuccoPropertyDescriptor; import org.nabucco.framework.base.facade.datatype.property.PropertyCache; import org.nabucco.framework.base.facade.datatype.property.PropertyDescriptorSupport; /** * MultiTenantDatatype<p/>Common datatype for multitenant datatypes.<p/> * * @version 1.0 * @author Frank Ratschinski, PRODYNA AG, 2011-05-27 */ public abstract class MultiTenantDatatype extends NabuccoDatatype implements Datatype { private static final long serialVersionUID = 1L; private static final String[] PROPERTY_CONSTRAINTS = { "l3,12;u0,n;m1,1;" }; public static final String TENANT = "tenant"; /** The tenant of the datatype. Default is NABUCCO. */ private Tenant tenant; /** Constructs a new MultiTenantDatatype instance. */ public MultiTenantDatatype() { super(); this.initDefaults(); } /** InitDefaults. */ private void initDefaults() { } /** * CloneObject. * * @param clone the MultiTenantDatatype. */ protected void cloneObject(MultiTenantDatatype clone) { super.cloneObject(clone); if ((this.getTenant() != null)) { clone.setTenant(this.getTenant().cloneObject()); } } /** * CreatePropertyContainer. * * @return the NabuccoPropertyContainer. */ protected static NabuccoPropertyContainer createPropertyContainer() { Map<String, NabuccoPropertyDescriptor> propertyMap = new HashMap<String, NabuccoPropertyDescriptor>(); propertyMap.putAll(PropertyCache.getInstance().retrieve(NabuccoDatatype.class).getPropertyMap()); propertyMap.put(TENANT, PropertyDescriptorSupport.createBasetype(TENANT, Tenant.class, 3, PROPERTY_CONSTRAINTS[0], true)); return new NabuccoPropertyContainer(propertyMap); } @Override public void init() { this.initDefaults(); } @Override public Set<NabuccoProperty> getProperties() { Set<NabuccoProperty> properties = super.getProperties(); properties.add(super.createProperty(MultiTenantDatatype.getPropertyDescriptor(TENANT), this.tenant, null)); return properties; } @Override public boolean setProperty(NabuccoProperty property) { if (super.setProperty(property)) { return true; } if ((property.getName().equals(TENANT) && (property.getType() == Tenant.class))) { this.setTenant(((Tenant) property.getInstance())); return true; } return false; } @Override public boolean equals(Object obj) { if ((this == obj)) { return true; } if ((obj == null)) { return false; } if ((this.getClass() != obj.getClass())) { return false; } if ((!super.equals(obj))) { return false; } final MultiTenantDatatype other = ((MultiTenantDatatype) obj); if ((this.tenant == null)) { if ((other.tenant != null)) return false; } else if ((!this.tenant.equals(other.tenant))) return false; return true; } @Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); result = ((PRIME * result) + ((this.tenant == null) ? 0 : this.tenant.hashCode())); return result; } @Override public abstract MultiTenantDatatype cloneObject(); /** * The tenant of the datatype. Default is NABUCCO. * * @return the Tenant. */ public Tenant getTenant() { return this.tenant; } /** * The tenant of the datatype. Default is NABUCCO. * * @param tenant the Tenant. */ public void setTenant(Tenant tenant) { this.tenant = tenant; } /** * The tenant of the datatype. Default is NABUCCO. * * @param tenant the String. */ public void setTenant(String tenant) { if ((this.tenant == null)) { if ((tenant == null)) { return; } this.tenant = new Tenant(); } this.tenant.setValue(tenant); } /** * Getter for the PropertyDescriptor. * * @param propertyName the String. * @return the NabuccoPropertyDescriptor. */ public static NabuccoPropertyDescriptor getPropertyDescriptor(String propertyName) { return PropertyCache.getInstance().retrieve(MultiTenantDatatype.class).getProperty(propertyName); } /** * Getter for the PropertyDescriptorList. * * @return the List<NabuccoPropertyDescriptor>. */ public static List<NabuccoPropertyDescriptor> getPropertyDescriptorList() { return PropertyCache.getInstance().retrieve(MultiTenantDatatype.class).getAllProperties(); } }
epl-1.0
arcanefoam/jgrapht
jgrapht-core/src/main/java/org/jgrapht/alg/interfaces/MaximumFlowAlgorithm.java
2600
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This program and the accompanying materials are dual-licensed under * either * * (a) the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation, or (at your option) any * later version. * * or (per the licensee's choosing) * * (b) the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation. */ /* ----------------- * MaximumFlowAlgorithm.java * ----------------- * (C) Copyright 2015-2015, by Alexey Kudinkin and Contributors. * * Original Author: Alexey Kudinkin * Contributor(s): * * $Id$ * * Changes * ------- */ package org.jgrapht.alg.interfaces; import java.util.*; /** * Allows to derive <a * href="https://en.wikipedia.org/wiki/Maximum_flow_problem">maximum-flow</a> * from the supplied <a href="https://en.wikipedia.org/wiki/Flow_network">flow * network</a> * * @param <V> vertex concept type * @param <E> edge concept type */ public interface MaximumFlowAlgorithm<V, E> { /** * Builds maximum flow for the supplied network flow, for the supplied * ${source} and ${sink} * * @param source source of the flow inside the network * @param sink sink of the flow inside the network * * @return maximum flow */ MaximumFlow<E> buildMaximumFlow(V source, V sink); interface MaximumFlow<E> { /** * Returns value of the maximum-flow for the given network * * @return value of th maximum-flow */ Double getValue(); /** * Returns mapping from edge to flow value through this particular edge * * @return maximum flow */ Map<E, Double> getFlow(); } class MaximumFlowImpl<E> implements MaximumFlow { private Double value; private Map<E, Double> flow; public MaximumFlowImpl(Double value, Map<E, Double> flow) { this.value = value; this.flow = Collections.unmodifiableMap(flow); } @Override public Double getValue() { return value; } @Override public Map<E, Double> getFlow() { return flow; } } } // End MaximumFlowAlgorithm.java
epl-1.0
lbchen/odl-mod
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/GroupingBuilder.java
1120
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.yang.parser.builder.api; import java.util.List; import java.util.Set; import org.opendaylight.controller.yang.model.api.GroupingDefinition; import org.opendaylight.controller.yang.model.api.Status; import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBuilder; /** * Interface for builders of 'grouping' statement. */ public interface GroupingBuilder extends DataNodeContainerBuilder, SchemaNodeBuilder, TypeDefinitionAwareBuilder { String getDescription(); String getReference(); Status getStatus(); GroupingDefinition build(); DataSchemaNodeBuilder getChildNode(String name); List<UnknownSchemaNodeBuilder> getUnknownNodes(); Set<GroupingBuilder> getGroupings(); Set<UsesNodeBuilder> getUses(); }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.wemo/src/main/java/org/openhab/binding/wemo/internal/WemoHttpCallFactory.java
747
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.wemo.internal; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.wemo.internal.http.WemoHttpCall; /** * {@link WemoHttpCallFactory} creates {@WemoHttpCall}s. * * @author Wouter Born - Initial contribution */ @NonNullByDefault public interface WemoHttpCallFactory { WemoHttpCall createHttpCall(); }
epl-1.0
elexis/elexis-3-core
bundles/ch.elexis.core.services/src/ch/elexis/core/services/CodeElementService.java
2955
package ch.elexis.core.services; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicyOption; import org.slf4j.LoggerFactory; import ch.elexis.core.model.IArticle; import ch.elexis.core.model.ICodeElement; @Component public class CodeElementService implements ICodeElementService { private HashMap<String, ICodeElementServiceContribution> contributions = new HashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY) public void setCodeElementServiceContribution(ICodeElementServiceContribution contribution){ ICodeElementServiceContribution previous = contributions.put(contribution.getSystem(), contribution); if (previous != null) { LoggerFactory.getLogger(getClass()) .warn("Possible ICodeElementServiceContribution collision previous [" + previous + "] new [" + contribution + "]"); } } public void unsetCodeElementServiceContribution(ICodeElementServiceContribution store){ contributions.remove(store.getSystem()); } @Override public Optional<ICodeElement> loadFromString(String system, String code, Map<Object, Object> context){ ICodeElementServiceContribution contribution = contributions.get(system); if (contribution != null) { if (context == null) { context = Collections.emptyMap(); } return contribution.loadFromCode(code, context); } else { LoggerFactory.getLogger(getClass()) .warn("No ICodeElementServiceContribution for system [" + system + "] code [" + code + "]"); } return Optional.empty(); } @Override public Optional<IArticle> findArticleByGtin(String gtin){ for (ICodeElementServiceContribution contribution : getContributionsByTyp( CodeElementTyp.ARTICLE)) { Optional<ICodeElement> loadFromCode = contribution.loadFromCode(gtin); if (loadFromCode.isPresent()) { if (loadFromCode.get() instanceof IArticle) { return loadFromCode.map(IArticle.class::cast); } else { LoggerFactory.getLogger(getClass()).warn( "Found article for gtin [{}] but is not castable to IArticle [{}]", gtin, loadFromCode.get().getClass().getName()); } } } return Optional.empty(); } @Override public List<ICodeElementServiceContribution> getContributionsByTyp(CodeElementTyp typ){ return contributions.values().stream().filter(contribution -> contribution.getTyp() == typ) .collect(Collectors.toList()); } @Override public Optional<ICodeElementServiceContribution> getContribution(CodeElementTyp typ, String codeSystemName){ return Optional.ofNullable(contributions.get(codeSystemName)); } }
epl-1.0
WIZARD-CXY/RSSOwl
org.rssowl.ui/src/org/rssowl/ui/internal/ApplicationActionBarAdvisor.java
90031
/* ********************************************************************** ** ** Copyright notice ** ** ** ** (c) 2005-2009 RSSOwl Development Team ** ** http://www.rssowl.org/ ** ** ** ** All rights reserved ** ** ** ** This program and the accompanying materials are made available under ** ** the terms of the Eclipse Public License v1.0 which accompanies this ** ** distribution, and is available at: ** ** http://www.rssowl.org/legal/epl-v10.html ** ** ** ** A copy is found in the file epl-v10.html and important notices to the ** ** license from the team is found in the textfile LICENSE.txt distributed ** ** in this package. ** ** ** ** This copyright notice MUST APPEAR in all copies of the file! ** ** ** ** Contributors: ** ** RSSOwl Development Team - initial API and implementation ** ** ** ** ********************************************************************** */ package org.rssowl.ui.internal; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.ICoolBarManager; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.bindings.TriggerSequence; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.resource.LocalResourceManager; import org.eclipse.jface.resource.ResourceManager; import org.eclipse.jface.viewers.DecorationOverlayIcon; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.IShellProvider; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ContributionItemFactory; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.keys.IBindingService; import org.rssowl.core.Owl; import org.rssowl.core.internal.persist.pref.DefaultPreferences; import org.rssowl.core.persist.IAttachment; import org.rssowl.core.persist.IBookMark; import org.rssowl.core.persist.IFilterAction; import org.rssowl.core.persist.IFolder; import org.rssowl.core.persist.IFolderChild; import org.rssowl.core.persist.ILabel; import org.rssowl.core.persist.IMark; import org.rssowl.core.persist.INews; import org.rssowl.core.persist.INewsBin; import org.rssowl.core.persist.INewsMark; import org.rssowl.core.persist.ISearchFilter; import org.rssowl.core.persist.ISearchMark; import org.rssowl.core.persist.dao.DynamicDAO; import org.rssowl.core.persist.dao.IBookMarkDAO; import org.rssowl.core.persist.pref.IPreferenceScope; import org.rssowl.core.util.CoreUtils; import org.rssowl.core.util.Pair; import org.rssowl.core.util.StringUtils; import org.rssowl.core.util.URIUtils; import org.rssowl.ui.internal.OwlUI.Layout; import org.rssowl.ui.internal.OwlUI.PageSize; import org.rssowl.ui.internal.actions.ArchiveNewsAction; import org.rssowl.ui.internal.actions.AssignLabelsAction; import org.rssowl.ui.internal.actions.AutomateFilterAction; import org.rssowl.ui.internal.actions.CopyLinkAction; import org.rssowl.ui.internal.actions.CreateFilterAction; import org.rssowl.ui.internal.actions.CreateFilterAction.PresetAction; import org.rssowl.ui.internal.actions.FindAction; import org.rssowl.ui.internal.actions.LabelAction; import org.rssowl.ui.internal.actions.MakeNewsStickyAction; import org.rssowl.ui.internal.actions.MarkAllNewsReadAction; import org.rssowl.ui.internal.actions.MoveCopyNewsToBinAction; import org.rssowl.ui.internal.actions.OpenInBrowserAction; import org.rssowl.ui.internal.actions.OpenInExternalBrowserAction; import org.rssowl.ui.internal.actions.OpenInNewTabAction; import org.rssowl.ui.internal.actions.RedoAction; import org.rssowl.ui.internal.actions.ReloadAllAction; import org.rssowl.ui.internal.actions.ReloadTypesAction; import org.rssowl.ui.internal.actions.SearchNewsAction; import org.rssowl.ui.internal.actions.SendLinkAction; import org.rssowl.ui.internal.actions.ToggleReadStateAction; import org.rssowl.ui.internal.actions.UndoAction; import org.rssowl.ui.internal.dialogs.CustomizeToolbarDialog; import org.rssowl.ui.internal.dialogs.LabelDialog; import org.rssowl.ui.internal.dialogs.LabelDialog.DialogMode; import org.rssowl.ui.internal.dialogs.preferences.ManageLabelsPreferencePage; import org.rssowl.ui.internal.dialogs.preferences.NotifierPreferencesPage; import org.rssowl.ui.internal.dialogs.preferences.OverviewPreferencesPage; import org.rssowl.ui.internal.dialogs.preferences.SharingPreferencesPage; import org.rssowl.ui.internal.dialogs.welcome.TutorialPage.Chapter; import org.rssowl.ui.internal.dialogs.welcome.TutorialWizard; import org.rssowl.ui.internal.editors.browser.WebBrowserContext; import org.rssowl.ui.internal.editors.feed.FeedView; import org.rssowl.ui.internal.editors.feed.FeedViewInput; import org.rssowl.ui.internal.editors.feed.NewsColumn; import org.rssowl.ui.internal.editors.feed.NewsColumnViewModel; import org.rssowl.ui.internal.editors.feed.NewsFilter; import org.rssowl.ui.internal.editors.feed.NewsGrouping; import org.rssowl.ui.internal.filter.DownloadAttachmentsNewsAction; import org.rssowl.ui.internal.handler.RemoveLabelsHandler; import org.rssowl.ui.internal.handler.TutorialHandler; import org.rssowl.ui.internal.services.DownloadService.DownloadRequest; import org.rssowl.ui.internal.util.BrowserUtils; import org.rssowl.ui.internal.util.EditorUtils; import org.rssowl.ui.internal.util.ModelUtils; import org.rssowl.ui.internal.views.explorer.BookMarkExplorer; import org.rssowl.ui.internal.views.explorer.BookMarkFilter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author bpasero */ public class ApplicationActionBarAdvisor extends ActionBarAdvisor { /** Name of the "Manage Extensions" SubMenu */ public static final String M_MANAGE_EXTENSIONS = "manageExtensions"; //$NON-NLS-1$ /** Name of the View Top Menu */ public static final String M_VIEW = "view"; //$NON-NLS-1$ /** Start of the View Top Menu */ public static final String M_VIEW_START = "viewStart"; //$NON-NLS-1$ /** End of the View Top Menu */ public static final String M_VIEW_END = "viewEnd"; //$NON-NLS-1$ /* Local Resource Manager (lives across entire application life) */ private static ResourceManager fgResources = new LocalResourceManager(JFaceResources.getResources()); private CoolBarAdvisor fCoolBarAdvisor; private IContributionItem fOpenWindowsItem; private IContributionItem fReopenEditors; private FindAction fFindAction; /** * @param configurer */ public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } /* * @see org.eclipse.ui.application.ActionBarAdvisor#makeActions(org.eclipse.ui.IWorkbenchWindow) */ @Override protected void makeActions(IWorkbenchWindow window) { /* Menu: File */ register(ActionFactory.SAVE_AS.create(window)); register(ActionFactory.CLOSE.create(window)); register(ActionFactory.CLOSE_ALL.create(window)); register(ActionFactory.PRINT.create(window)); register(ActionFactory.QUIT.create(window)); fReopenEditors = ContributionItemFactory.REOPEN_EDITORS.create(window); /* Menu: Edit */ register(ActionFactory.CUT.create(window)); register(ActionFactory.COPY.create(window)); register(ActionFactory.PASTE.create(window)); register(ActionFactory.DELETE.create(window)); register(ActionFactory.SELECT_ALL.create(window)); register(ActionFactory.PROPERTIES.create(window)); fFindAction = new FindAction(); register(fFindAction); /* Menu: Tools */ register(ActionFactory.PREFERENCES.create(window)); /* Menu: Window */ register(ActionFactory.OPEN_NEW_WINDOW.create(window)); getAction(ActionFactory.OPEN_NEW_WINDOW.getId()).setText(Messages.ApplicationActionBarAdvisor_NEW_WINDOW); fOpenWindowsItem = ContributionItemFactory.OPEN_WINDOWS.create(window); // register(ActionFactory.TOGGLE_COOLBAR.create(window)); // register(ActionFactory.RESET_PERSPECTIVE.create(window)); // register(ActionFactory.EDIT_ACTION_SETS.create(window)); // register(ActionFactory.ACTIVATE_EDITOR.create(window)); // register(ActionFactory.MAXIMIZE.create(window)); // register(ActionFactory.MINIMIZE.create(window)); // register(ActionFactory.NEXT_EDITOR.create(window)); // register(ActionFactory.PREVIOUS_EDITOR.create(window)); // register(ActionFactory.PREVIOUS_PART.create(window)); // register(ActionFactory.NEXT_PART.create(window)); // register(ActionFactory.SHOW_EDITOR.create(window)); /* Menu: Help */ // register(ActionFactory.INTRO.create(window)); register(ActionFactory.ABOUT.create(window)); getAction(ActionFactory.ABOUT.getId()).setText(Messages.ApplicationActionBarAdvisor_ABOUT_RSSOWL); /* CoolBar: Contextual Menu */ register(ActionFactory.LOCK_TOOL_BAR.create(window)); } /* * @see org.eclipse.ui.application.ActionBarAdvisor#fillMenuBar(org.eclipse.jface.action.IMenuManager) */ @Override protected void fillMenuBar(IMenuManager menuBar) { /* File Menu */ createFileMenu(menuBar); /* Edit Menu */ createEditMenu(menuBar); /* View Menu */ createViewMenu(menuBar); /* Go Menu */ createGoMenu(menuBar); /* Bookmarks Menu */ createBookMarksMenu(menuBar); /* News Menu */ createNewsMenu(menuBar); /* Allow Top-Level Menu Contributions here */ menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); /* Menu: Tools */ createToolsMenu(menuBar); /* Window Menu */ createWindowMenu(menuBar); /* Menu: Help */ createHelpMenu(menuBar); } /* Menu: File */ private void createFileMenu(IMenuManager menuBar) { MenuManager fileMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_FILE, IWorkbenchActionConstants.M_FILE); menuBar.add(fileMenu); fileMenu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START)); fileMenu.add(new GroupMarker(IWorkbenchActionConstants.NEW_EXT)); fileMenu.add(new Separator()); fileMenu.add(getAction(ActionFactory.CLOSE.getId())); fileMenu.add(getAction(ActionFactory.CLOSE_ALL.getId())); fileMenu.add(new GroupMarker(IWorkbenchActionConstants.CLOSE_EXT)); fileMenu.add(new Separator()); fileMenu.add(getAction(ActionFactory.SAVE_AS.getId())); if (!Application.IS_MAC) { //Printing is not supported on Mac fileMenu.add(new Separator()); fileMenu.add(getAction(ActionFactory.PRINT.getId())); } fileMenu.add(new Separator()); fileMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); fileMenu.add(new Separator()); fileMenu.add(new GroupMarker(IWorkbenchActionConstants.FILE_END)); fileMenu.add(new Separator()); if (Application.IS_LINUX) { fileMenu.add(getAction(ActionFactory.PROPERTIES.getId())); fileMenu.add(new Separator()); } fileMenu.add(getAction(ActionFactory.QUIT.getId())); } /* Menu: Edit */ private void createEditMenu(IMenuManager menuBar) { MenuManager editMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_EDIT, IWorkbenchActionConstants.M_EDIT); editMenu.add(getAction(ActionFactory.COPY.getId())); //Dummy action menuBar.add(editMenu); editMenu.setRemoveAllWhenShown(true); editMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager editMenu) { editMenu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_START)); editMenu.add(new Separator()); editMenu.add(new UndoAction()); editMenu.add(new RedoAction()); editMenu.add(new GroupMarker(IWorkbenchActionConstants.UNDO_EXT)); editMenu.add(new Separator()); editMenu.add(getAction(ActionFactory.CUT.getId())); editMenu.add(getAction(ActionFactory.COPY.getId())); editMenu.add(new CopyLinkAction()); editMenu.add(getAction(ActionFactory.PASTE.getId())); editMenu.add(new Separator()); editMenu.add(getAction(ActionFactory.DELETE.getId())); editMenu.add(getAction(ActionFactory.SELECT_ALL.getId())); editMenu.add(new Separator()); editMenu.add(new SearchNewsAction(OwlUI.getWindow())); editMenu.add(fFindAction); editMenu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_END)); editMenu.add(new Separator()); if (Application.IS_LINUX) { IAction preferences = getAction(ActionFactory.PREFERENCES.getId()); preferences.setImageDescriptor(OwlUI.getImageDescriptor("icons/elcl16/preferences.gif")); //$NON-NLS-1$ editMenu.add(preferences); } else editMenu.add(getAction(ActionFactory.PROPERTIES.getId())); } }); } /* Menu: View */ private void createViewMenu(IMenuManager menuBar) { final IPreferenceScope globalPreferences = Owl.getPreferenceService().getGlobalScope(); final IPreferenceScope eclipsePrefs = Owl.getPreferenceService().getEclipseScope(); MenuManager viewMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_VIEW, M_VIEW); viewMenu.setRemoveAllWhenShown(true); menuBar.add(viewMenu); /* Add dummy action to show the top level menu */ viewMenu.add(new Action("") { //$NON-NLS-1$ @Override public void run() {} }); /* Build Menu dynamically */ viewMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { final FeedView activeFeedView = OwlUI.getActiveFeedView(); final IPreferenceScope entityPreferences = OwlUI.getActiveFeedViewPreferences(); final Layout layout = OwlUI.getLayout(entityPreferences != null ? entityPreferences : globalPreferences); final PageSize pageSize = OwlUI.getPageSize(entityPreferences != null ? entityPreferences : globalPreferences); manager.add(new GroupMarker(M_VIEW_START)); /* Layout */ MenuManager layoutMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_LAYOUT); layoutMenu.add(new Action(Messages.ApplicationActionBarAdvisor_CLASSIC_LAYOUT, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateLayoutPreferences(globalPreferences, entityPreferences, Layout.CLASSIC); } @Override public boolean isChecked() { return layout == Layout.CLASSIC; } }); layoutMenu.add(new Action(Messages.ApplicationActionBarAdvisor_VERTICAL_LAYOUT, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateLayoutPreferences(globalPreferences, entityPreferences, Layout.VERTICAL); } @Override public boolean isChecked() { return layout == Layout.VERTICAL; } }); layoutMenu.add(new Action(Messages.ApplicationActionBarAdvisor_LIST_LAYOUT, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateLayoutPreferences(globalPreferences, entityPreferences, Layout.LIST); } @Override public boolean isChecked() { return layout == Layout.LIST; } }); layoutMenu.add(new Action(Messages.ApplicationActionBarAdvisor_NEWSPAPER_LAYOUT, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateLayoutPreferences(globalPreferences, entityPreferences, Layout.NEWSPAPER); } @Override public boolean isChecked() { return layout == Layout.NEWSPAPER; } }); layoutMenu.add(new Action(Messages.ApplicationActionBarAdvisor_HEADLINES_LAYOUT, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateLayoutPreferences(globalPreferences, entityPreferences, Layout.HEADLINES); } @Override public boolean isChecked() { return layout == Layout.HEADLINES; } }); /* Add the Page Size if using Newspaper or Headlines layout */ if (layout == Layout.NEWSPAPER || layout == Layout.HEADLINES) { layoutMenu.add(new Separator()); MenuManager pageMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_PAGE_SIZE); pageMenu.add(new Action(Messages.ApplicationActionBarAdvisor_T_ARTICLES, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updatePageSizePreferences(globalPreferences, entityPreferences, PageSize.TEN); } @Override public boolean isChecked() { return pageSize == PageSize.TEN; } }); pageMenu.add(new Action(Messages.ApplicationActionBarAdvisor_TF_ARTICLES, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updatePageSizePreferences(globalPreferences, entityPreferences, PageSize.TWENTY_FIVE); } @Override public boolean isChecked() { return pageSize == PageSize.TWENTY_FIVE; } }); pageMenu.add(new Action(Messages.ApplicationActionBarAdvisor_F_ARTICLES, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updatePageSizePreferences(globalPreferences, entityPreferences, PageSize.FIFTY); } @Override public boolean isChecked() { return pageSize == PageSize.FIFTY; } }); pageMenu.add(new Action(Messages.ApplicationActionBarAdvisor_H_ARTICLES, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updatePageSizePreferences(globalPreferences, entityPreferences, PageSize.HUNDRED); } @Override public boolean isChecked() { return pageSize == PageSize.HUNDRED; } }); pageMenu.add(new Separator()); pageMenu.add(new Action(Messages.ApplicationActionBarAdvisor_ALL_ARTICLES, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updatePageSizePreferences(globalPreferences, entityPreferences, PageSize.NO_PAGING); } @Override public boolean isChecked() { return pageSize == PageSize.NO_PAGING; } }); layoutMenu.add(pageMenu); } manager.add(layoutMenu); /* Columns */ final boolean isColumnsEnabled = (layout != Layout.NEWSPAPER && layout != Layout.HEADLINES); MenuManager columnsMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_COLUMNS); final NewsColumnViewModel model = NewsColumnViewModel.loadFrom(entityPreferences != null ? entityPreferences : globalPreferences); NewsColumn[] columns = NewsColumn.values(); for (final NewsColumn column : columns) { if (column.isSelectable()) { columnsMenu.add(new Action(column.getName(), IAction.AS_CHECK_BOX) { @Override public void run() { if (model.contains(column)) model.removeColumn(column); else model.addColumn(column); updateColumnsPreferences(globalPreferences, entityPreferences, model, DefaultPreferences.BM_NEWS_COLUMNS); } @Override public boolean isChecked() { return model.contains(column); } @Override public boolean isEnabled() { return isColumnsEnabled; }; }); } } columnsMenu.add(new Separator()); columnsMenu.add(new Action(Messages.ApplicationActionBarAdvisor_RESTORE_DEFAULT_COLUMNS) { @Override public void run() { NewsColumnViewModel defaultModel = NewsColumnViewModel.createDefault(false); updateColumnsPreferences(globalPreferences, entityPreferences, defaultModel, DefaultPreferences.BM_NEWS_COLUMNS, DefaultPreferences.BM_NEWS_SORT_COLUMN, DefaultPreferences.BM_NEWS_SORT_ASCENDING); } @Override public boolean isEnabled() { return isColumnsEnabled; }; }); manager.add(columnsMenu); /* Sorting */ MenuManager sortingMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_SORT_BY); for (final NewsColumn column : columns) { if (column.isSelectable()) { sortingMenu.add(new Action(column.getName(), IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) { //Need to use parent scope to get real selection state from UI and not Model model.setSortColumn(column); updateColumnsPreferences(globalPreferences, entityPreferences, model, DefaultPreferences.BM_NEWS_SORT_COLUMN); } } @Override public boolean isChecked() { return model.getSortColumn().equals(column); } }); } } sortingMenu.add(new Separator()); sortingMenu.add(new Action(Messages.ApplicationActionBarAdvisor_ASCENDING, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) { //Need to use parent scope to get real selection state from UI and not Model model.setAscending(true); updateColumnsPreferences(globalPreferences, entityPreferences, model, DefaultPreferences.BM_NEWS_SORT_ASCENDING); } } @Override public boolean isChecked() { return model.isAscending(); } }); sortingMenu.add(new Action(Messages.ApplicationActionBarAdvisor_DESCENDING, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) { //Need to use parent scope to get real selection state from UI and not Model model.setAscending(false); updateColumnsPreferences(globalPreferences, entityPreferences, model, DefaultPreferences.BM_NEWS_SORT_ASCENDING); } } @Override public boolean isChecked() { return !model.isAscending(); } }); manager.add(sortingMenu); /* News Filter */ manager.add(new Separator()); MenuManager filterMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_FILTER_NEWS); int selectedFilterIndex; if (entityPreferences != null) selectedFilterIndex = ModelUtils.loadIntegerValueWithFallback(entityPreferences, DefaultPreferences.BM_NEWS_FILTERING, globalPreferences, DefaultPreferences.FV_FILTER_TYPE); else selectedFilterIndex = ModelUtils.loadIntegerValueWithFallback(globalPreferences, DefaultPreferences.BM_NEWS_FILTERING, globalPreferences, DefaultPreferences.FV_FILTER_TYPE); final NewsFilter.Type selectedFilter = NewsFilter.Type.values()[selectedFilterIndex]; NewsFilter.Type[] filters = new NewsFilter.Type[] { NewsFilter.Type.SHOW_ALL, NewsFilter.Type.SHOW_NEW, NewsFilter.Type.SHOW_UNREAD, NewsFilter.Type.SHOW_STICKY, NewsFilter.Type.SHOW_LABELED, NewsFilter.Type.SHOW_RECENT, NewsFilter.Type.SHOW_LAST_5_DAYS }; for (final NewsFilter.Type filter : filters) { filterMenu.add(new Action(filter.getName(), IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateFilterAndGroupingPreferences(globalPreferences, entityPreferences, filter, null); }; @Override public boolean isChecked() { return filter == selectedFilter; }; }); /* Add Separators to improve readability of filter options */ if (filter == NewsFilter.Type.SHOW_ALL || filter == NewsFilter.Type.SHOW_UNREAD || filter == NewsFilter.Type.SHOW_LABELED) filterMenu.add(new Separator()); } manager.add(filterMenu); /* News Grouping */ MenuManager groupMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_GROUP_NEWS); int selectedGroupIndex; if (entityPreferences != null) selectedGroupIndex = ModelUtils.loadIntegerValueWithFallback(entityPreferences, DefaultPreferences.BM_NEWS_GROUPING, globalPreferences, DefaultPreferences.FV_GROUP_TYPE); else selectedGroupIndex = ModelUtils.loadIntegerValueWithFallback(globalPreferences, DefaultPreferences.BM_NEWS_GROUPING, globalPreferences, DefaultPreferences.FV_GROUP_TYPE); final NewsGrouping.Type selectedGroup = NewsGrouping.Type.values()[selectedGroupIndex]; NewsGrouping.Type[] groups = new NewsGrouping.Type[] { NewsGrouping.Type.NO_GROUPING, NewsGrouping.Type.GROUP_BY_DATE, NewsGrouping.Type.GROUP_BY_AUTHOR, NewsGrouping.Type.GROUP_BY_CATEGORY, NewsGrouping.Type.GROUP_BY_TOPIC, NewsGrouping.Type.GROUP_BY_FEED, NewsGrouping.Type.GROUP_BY_STATE, NewsGrouping.Type.GROUP_BY_STICKY, NewsGrouping.Type.GROUP_BY_LABEL }; for (final NewsGrouping.Type group : groups) { groupMenu.add(new Action(group.getName(), IAction.AS_RADIO_BUTTON) { @Override public void run() { if (super.isChecked()) //Need to use parent scope to get real selection state from UI and not Model updateFilterAndGroupingPreferences(globalPreferences, entityPreferences, null, group); }; @Override public boolean isChecked() { return group == selectedGroup; }; }); /* Add Separators to improve readability of grouping options */ if (group == NewsGrouping.Type.NO_GROUPING || group == NewsGrouping.Type.GROUP_BY_FEED || group == NewsGrouping.Type.GROUP_BY_STICKY) groupMenu.add(new Separator()); } manager.add(groupMenu); /* Zoom (In, Out, Reset) */ final boolean isZoomingEnabled = (activeFeedView != null && activeFeedView.isBrowserShowingNews()); manager.add(new Separator()); MenuManager zoomMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_ZOOM); /* Zoom In */ zoomMenu.add(new Action(Messages.ApplicationActionBarAdvisor_ZOOM_IN) { @Override public void run() { OwlUI.zoomNewsText(true, false); } @Override public String getId() { return "org.rssowl.ui.ZoomInCommand"; //$NON-NLS-1$ } @Override public String getActionDefinitionId() { return "org.rssowl.ui.ZoomInCommand"; //$NON-NLS-1$ } @Override public boolean isEnabled() { return isZoomingEnabled; } }); /* Zoom Out */ zoomMenu.add(new Action(Messages.ApplicationActionBarAdvisor_ZOOM_OUT) { @Override public void run() { OwlUI.zoomNewsText(false, false); } @Override public String getId() { return "org.rssowl.ui.ZoomOutCommand"; //$NON-NLS-1$ } @Override public String getActionDefinitionId() { return "org.rssowl.ui.ZoomOutCommand"; //$NON-NLS-1$ } @Override public boolean isEnabled() { return isZoomingEnabled; } }); /* Reset */ zoomMenu.add(new Separator()); zoomMenu.add(new Action(Messages.ApplicationActionBarAdvisor_RESET) { @Override public void run() { OwlUI.zoomNewsText(false, true); } @Override public String getId() { return "org.rssowl.ui.ZoomResetCommand"; //$NON-NLS-1$ } @Override public String getActionDefinitionId() { return "org.rssowl.ui.ZoomResetCommand"; //$NON-NLS-1$ } @Override public boolean isEnabled() { return isZoomingEnabled; } }); manager.add(zoomMenu); /* Toolbars */ manager.add(new Separator()); final MenuManager toolbarsMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_TOOLBARS); toolbarsMenu.setRemoveAllWhenShown(true); toolbarsMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { boolean useExternalBrowser = OwlUI.useExternalBrowser(); /* Main Toolbar */ toolbarsMenu.add(new Action(Messages.ApplicationActionBarAdvisor_TOOLBAR, IAction.AS_CHECK_BOX) { @Override public void run() { ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.fgPrimaryApplicationWorkbenchWindowAdvisor; boolean isMainToolBarVisible = globalPreferences.getBoolean(DefaultPreferences.SHOW_TOOLBAR); configurer.setToolBarVisible(!isMainToolBarVisible, true); globalPreferences.putBoolean(DefaultPreferences.SHOW_TOOLBAR, !isMainToolBarVisible); } @Override public boolean isChecked() { return globalPreferences.getBoolean(DefaultPreferences.SHOW_TOOLBAR); } }); /* Feed Toolbar */ toolbarsMenu.add(new Action(Messages.ApplicationActionBarAdvisor_FEED_TOOLBAR, IAction.AS_CHECK_BOX) { @Override public void run() { boolean isFeedToolBarHidden = globalPreferences.getBoolean(DefaultPreferences.FV_FEED_TOOLBAR_HIDDEN); globalPreferences.putBoolean(DefaultPreferences.FV_FEED_TOOLBAR_HIDDEN, !isFeedToolBarHidden); /* Update opened Feedviews */ EditorUtils.updateToolbarVisibility(); } @Override public boolean isChecked() { return !globalPreferences.getBoolean(DefaultPreferences.FV_FEED_TOOLBAR_HIDDEN); } }); /* Browser Toolbar */ if (!useExternalBrowser) { toolbarsMenu.add(new Action(Messages.ApplicationActionBarAdvisor_BROWSER_TOOLBAR, IAction.AS_CHECK_BOX) { @Override public void run() { boolean isBrowserToolBarHidden = globalPreferences.getBoolean(DefaultPreferences.FV_BROWSER_TOOLBAR_HIDDEN); globalPreferences.putBoolean(DefaultPreferences.FV_BROWSER_TOOLBAR_HIDDEN, !isBrowserToolBarHidden); /* Update opened Feedviews */ EditorUtils.updateToolbarVisibility(); } @Override public boolean isChecked() { return !globalPreferences.getBoolean(DefaultPreferences.FV_BROWSER_TOOLBAR_HIDDEN); } }); } } }); manager.add(toolbarsMenu); /* Toggle State of Status Bar Visibility */ manager.add(new Action(Messages.ApplicationActionBarAdvisor_STATUS, IAction.AS_CHECK_BOX) { @Override public void run() { ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.fgPrimaryApplicationWorkbenchWindowAdvisor; boolean isStatusVisible = globalPreferences.getBoolean(DefaultPreferences.SHOW_STATUS); configurer.setStatusVisible(!isStatusVisible, true); globalPreferences.putBoolean(DefaultPreferences.SHOW_STATUS, !isStatusVisible); } @Override public boolean isChecked() { return globalPreferences.getBoolean(DefaultPreferences.SHOW_STATUS); } }); /* Toggle State of Bookmarks Visibility */ manager.add(new Action(Messages.ApplicationActionBarAdvisor_BOOKMARKS, IAction.AS_CHECK_BOX) { @Override public void run() { OwlUI.toggleBookmarks(); } @Override public String getActionDefinitionId() { return "org.rssowl.ui.ToggleBookmarksCommand"; //$NON-NLS-1$ } @Override public String getId() { return "org.rssowl.ui.ToggleBookmarksCommand"; //$NON-NLS-1$ } @Override public boolean isChecked() { IWorkbenchPage page = OwlUI.getPage(); if (page != null) return page.findView(BookMarkExplorer.VIEW_ID) != null; return false; } }); /* Customize Toolbar */ manager.add(new Separator()); manager.add(new Action(Messages.ApplicationActionBarAdvisor_CUSTOMIZE_TOOLBAR) { @Override public void run() { /* Unhide Toolbar if hidden */ ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.fgPrimaryApplicationWorkbenchWindowAdvisor; boolean isToolBarVisible = globalPreferences.getBoolean(DefaultPreferences.SHOW_TOOLBAR); if (!isToolBarVisible) { configurer.setToolBarVisible(true, true); globalPreferences.putBoolean(DefaultPreferences.SHOW_TOOLBAR, true); } /* Open Dialog to Customize Toolbar */ CustomizeToolbarDialog dialog = new CustomizeToolbarDialog(getActionBarConfigurer().getWindowConfigurer().getWindow().getShell()); if (dialog.open() == IDialogConstants.OK_ID) fCoolBarAdvisor.advise(true); } }); /* Tabbed Browsing */ manager.add(new Separator()); manager.add(new Action(Messages.ApplicationActionBarAdvisor_TABBED_BROWSING, IAction.AS_CHECK_BOX) { @Override public void run() { boolean tabbedBrowsingEnabled = isChecked(); /* Disable Tabbed Browsing */ if (tabbedBrowsingEnabled) { /* Close other Tabs if necessary */ boolean doit = true; IWorkbenchPage page = OwlUI.getPage(); if (page != null) { IEditorReference[] editorReferences = page.getEditorReferences(); if (editorReferences.length > 1) { MessageBox confirmDialog = new MessageBox(page.getWorkbenchWindow().getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); confirmDialog.setText(Messages.ApplicationActionBarAdvisor_DISABLE_TABBED_BROWSING); confirmDialog.setMessage(NLS.bind(Messages.ApplicationActionBarAdvisor_TABS_MESSAGE, editorReferences.length)); if (confirmDialog.open() == SWT.YES) OwlUI.closeOtherEditors(); else doit = false; } } /* Update Preferences */ if (doit) { eclipsePrefs.putBoolean(DefaultPreferences.ECLIPSE_MULTIPLE_TABS, false); eclipsePrefs.putBoolean(DefaultPreferences.ECLIPSE_AUTOCLOSE_TABS, true); eclipsePrefs.putInteger(DefaultPreferences.ECLIPSE_AUTOCLOSE_TABS_THRESHOLD, 1); } } /* Enable Tabbed Browsing */ else { eclipsePrefs.putBoolean(DefaultPreferences.ECLIPSE_MULTIPLE_TABS, true); eclipsePrefs.putBoolean(DefaultPreferences.ECLIPSE_AUTOCLOSE_TABS, false); eclipsePrefs.putInteger(DefaultPreferences.ECLIPSE_AUTOCLOSE_TABS_THRESHOLD, 5); } } @Override public boolean isChecked() { return OwlUI.isTabbedBrowsingEnabled(); } }); /* Fullscreen Mode */ manager.add(new Action(Messages.ApplicationActionBarAdvisor_FULL_SCREEN, IAction.AS_CHECK_BOX) { @Override public void run() { OwlUI.toggleFullScreen(); } @Override public String getActionDefinitionId() { return "org.rssowl.ui.FullScreenCommand"; //$NON-NLS-1$ } @Override public String getId() { return "org.rssowl.ui.FullScreenCommand"; //$NON-NLS-1$ } @Override public boolean isChecked() { Shell shell = OwlUI.getActiveShell(); if (shell != null) return shell.getFullScreen(); return super.isChecked(); } }); /* Minimize */ manager.add(new Action(Messages.ApplicationActionBarAdvisor_MINIMIZE) { @Override public void run() { Shell shell = OwlUI.getActiveShell(); if (shell != null) shell.setMinimized(true); } @Override public String getActionDefinitionId() { return "org.rssowl.ui.MinimizeCommand"; //$NON-NLS-1$ } @Override public String getId() { return "org.rssowl.ui.MinimizeCommand"; //$NON-NLS-1$ } }); manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); manager.add(new GroupMarker(M_VIEW_START)); } }); } private void updatePageSizePreferences(IPreferenceScope globalPreferences, IPreferenceScope entityPreferences, PageSize pageSize) { /* Update Global */ globalPreferences.putInteger(DefaultPreferences.NEWS_BROWSER_PAGE_SIZE, pageSize.getPageSize()); /* Update Entity if it was configured explicitly */ if (entityPreferences != null) { if (entityPreferences.hasKey(DefaultPreferences.NEWS_BROWSER_PAGE_SIZE)) { entityPreferences.delete(DefaultPreferences.NEWS_BROWSER_PAGE_SIZE); entityPreferences.flush(); } } } private void updateLayoutPreferences(IPreferenceScope globalPreferences, IPreferenceScope entityPreferences, Layout layout) { /* Update Global */ globalPreferences.putInteger(DefaultPreferences.FV_LAYOUT, layout.ordinal()); /* Update Entity if it was configured explicitly */ if (entityPreferences != null) { if (entityPreferences.hasKey(DefaultPreferences.FV_LAYOUT)) { entityPreferences.delete(DefaultPreferences.FV_LAYOUT); entityPreferences.flush(); } } /* Update Feed Views */ EditorUtils.updateLayout(); } private void updateFilterAndGroupingPreferences(IPreferenceScope globalPreferences, IPreferenceScope entityPreferences, NewsFilter.Type filter, NewsGrouping.Type grouping) { /* Update Global */ if (filter != null) globalPreferences.putInteger(DefaultPreferences.BM_NEWS_FILTERING, filter.ordinal()); if (grouping != null) globalPreferences.putInteger(DefaultPreferences.BM_NEWS_GROUPING, grouping.ordinal()); /* Update Entity if it was configured explicitly */ if (entityPreferences != null) { boolean flush = false; if (filter != null && entityPreferences.hasKey(DefaultPreferences.BM_NEWS_FILTERING)) { entityPreferences.delete(DefaultPreferences.BM_NEWS_FILTERING); flush = true; } if (grouping != null && entityPreferences.hasKey(DefaultPreferences.BM_NEWS_GROUPING)) { entityPreferences.delete(DefaultPreferences.BM_NEWS_GROUPING); flush = true; } if (flush) entityPreferences.flush(); } /* Update Feed Views */ EditorUtils.updateFilterAndGrouping(); } private void updateColumnsPreferences(IPreferenceScope globalPreferences, IPreferenceScope entityPreferences, NewsColumnViewModel model, String... prefKeys) { /* Update Global */ boolean saveColumns = contains(DefaultPreferences.BM_NEWS_COLUMNS, prefKeys); boolean saveSortColumn = contains(DefaultPreferences.BM_NEWS_SORT_COLUMN, prefKeys); boolean saveSortDirection = contains(DefaultPreferences.BM_NEWS_SORT_ASCENDING, prefKeys); model.saveTo(globalPreferences, false, saveColumns, saveSortColumn, saveSortDirection); /* Update Entity if it was configured explicitly */ if (entityPreferences != null && prefKeys != null) { boolean flush = false; for (String prefKey : prefKeys) { if (entityPreferences.hasKey(prefKey)) { entityPreferences.delete(prefKey); flush = true; } } if (flush) entityPreferences.flush(); } /* Update Feed Views */ EditorUtils.updateColumns(); } private boolean contains(String key, String... elements) { if (elements == null) return false; for (String element : elements) { if (key.equals(element)) return true; } return false; } /* Menu: Go */ private void createGoMenu(IMenuManager menuBar) { MenuManager goMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_GO, IWorkbenchActionConstants.M_NAVIGATE); menuBar.add(goMenu); goMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); goMenu.add(fReopenEditors); } /* Menu: Bookmarks */ private void createBookMarksMenu(IMenuManager menuBar) { MenuManager bmMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_BOOKMARKS, "bookmarks"); //$NON-NLS-1$ bmMenu.setRemoveAllWhenShown(true); bmMenu.add(new Action("") {}); //Dummy Action //$NON-NLS-1$ bmMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { fillBookMarksMenu(manager, getActionBarConfigurer().getWindowConfigurer().getWindow()); manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); menuBar.add(bmMenu); } /* Menu News */ private void createNewsMenu(IMenuManager menuBar) { final MenuManager newsMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_NEWS, "news"); //$NON-NLS-1$ menuBar.add(newsMenu); newsMenu.setRemoveAllWhenShown(true); newsMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { final IStructuredSelection selection; FeedView activeFeedView = OwlUI.getActiveFeedView(); FeedViewInput activeInput = null; if (activeFeedView != null) { selection = (IStructuredSelection) activeFeedView.getSite().getSelectionProvider().getSelection(); activeInput = (FeedViewInput) activeFeedView.getEditorInput(); } else selection = StructuredSelection.EMPTY; boolean isEntityGroupSelected = ModelUtils.isEntityGroupSelected(selection); /* Open */ if (!isEntityGroupSelected) { manager.add(new Separator("open")); //$NON-NLS-1$ /* Open News in Browser */ manager.add(new OpenInBrowserAction(selection, WebBrowserContext.createFrom(selection, activeFeedView)) { @Override public boolean isEnabled() { return !selection.isEmpty(); } }); /* Open Externally - Show only when internal browser is used */ if (!selection.isEmpty() && !OwlUI.useExternalBrowser()) manager.add(new OpenInExternalBrowserAction(selection)); } /* Attachments */ { fillAttachmentsMenu(manager, selection, getActionBarConfigurer().getWindowConfigurer().getWindow(), false); } /* Mark / Label */ { manager.add(new Separator("mark")); //$NON-NLS-1$ /* Mark */ { MenuManager markMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_MARK, "mark"); //$NON-NLS-1$ manager.add(markMenu); /* Mark as Read */ IAction action = new ToggleReadStateAction(selection); action.setEnabled(!selection.isEmpty()); markMenu.add(action); /* Mark All Read */ action = new MarkAllNewsReadAction(); action.setEnabled(activeFeedView != null); markMenu.add(action); /* Sticky */ markMenu.add(new Separator()); action = new MakeNewsStickyAction(selection); action.setEnabled(!selection.isEmpty()); markMenu.add(action); } /* Label */ fillLabelMenu(manager, selection, getActionBarConfigurer().getWindowConfigurer().getWindow(), false); } /* Move To / Copy To */ if (!selection.isEmpty()) { manager.add(new Separator("movecopy")); //$NON-NLS-1$ /* Load all news bins and sort by name */ List<INewsBin> newsbins = new ArrayList<INewsBin>(DynamicDAO.loadAll(INewsBin.class)); Comparator<INewsBin> comparator = new Comparator<INewsBin>() { public int compare(INewsBin o1, INewsBin o2) { return o1.getName().compareTo(o2.getName()); }; }; Collections.sort(newsbins, comparator); /* Move To */ MenuManager moveMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_MOVE_TO, "moveto"); //$NON-NLS-1$ manager.add(moveMenu); for (INewsBin bin : newsbins) { if (activeInput != null && activeInput.getMark().equals(bin)) continue; moveMenu.add(new MoveCopyNewsToBinAction(selection, bin, true)); } moveMenu.add(new MoveCopyNewsToBinAction(selection, null, true)); moveMenu.add(new Separator()); moveMenu.add(new AutomateFilterAction(PresetAction.MOVE, selection)); /* Copy To */ MenuManager copyMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_COPY_TO, "copyto"); //$NON-NLS-1$ manager.add(copyMenu); for (INewsBin bin : newsbins) { if (activeInput != null && activeInput.getMark().equals(bin)) continue; copyMenu.add(new MoveCopyNewsToBinAction(selection, bin, false)); } copyMenu.add(new MoveCopyNewsToBinAction(selection, null, false)); copyMenu.add(new Separator()); copyMenu.add(new AutomateFilterAction(PresetAction.COPY, selection)); /* Archive */ manager.add(new ArchiveNewsAction(selection)); } /* Share */ fillShareMenu(manager, selection, getActionBarConfigurer().getWindowConfigurer().getWindow(), false); /* Filter */ if (!selection.isEmpty()) { manager.add(new Separator("filter")); //$NON-NLS-1$ /* Create Filter */ manager.add(new Action(Messages.ApplicationActionBarAdvisor_CREATE_FILTER) { @Override public void run() { CreateFilterAction action = new CreateFilterAction(); action.selectionChanged(null, selection); action.run(null); } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.FILTER; } @Override public String getActionDefinitionId() { return CreateFilterAction.ID; }; @Override public String getId() { return CreateFilterAction.ID; }; }); } /* Update */ { manager.add(new Separator("reload")); //$NON-NLS-1$ /* Update */ manager.add(new Action(Messages.ApplicationActionBarAdvisor_UPDATE) { @Override public void run() { IActionDelegate action = new ReloadTypesAction(); action.selectionChanged(null, selection); action.run(null); } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.getImageDescriptor("icons/elcl16/reload.gif"); //$NON-NLS-1$ } @Override public ImageDescriptor getDisabledImageDescriptor() { return OwlUI.getImageDescriptor("icons/dlcl16/reload.gif"); //$NON-NLS-1$ } @Override public boolean isEnabled() { return !selection.isEmpty() || OwlUI.getActiveFeedView() != null; } @Override public String getActionDefinitionId() { return ReloadTypesAction.ID; } @Override public String getId() { return ReloadTypesAction.ID; } }); /* Update All */ manager.add(new ReloadAllAction()); } manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } }); } /* Menu: Tools */ private void createToolsMenu(IMenuManager menuBar) { MenuManager toolsMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_TOOLS, OwlUI.M_TOOLS); menuBar.add(toolsMenu); /* Contributions */ toolsMenu.add(new GroupMarker("begin")); //$NON-NLS-1$ toolsMenu.add(new Separator()); toolsMenu.add(new GroupMarker("middle")); //$NON-NLS-1$ toolsMenu.add(new Separator("addons")); //$NON-NLS-1$ toolsMenu.add(new Separator()); toolsMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); toolsMenu.add(new Separator()); toolsMenu.add(new GroupMarker("end")); //$NON-NLS-1$ /* Preferences (Windows, Mac) */ if (!Application.IS_LINUX) { toolsMenu.add(new Separator()); IAction preferences = getAction(ActionFactory.PREFERENCES.getId()); preferences.setImageDescriptor(OwlUI.getImageDescriptor("icons/elcl16/preferences.gif")); //$NON-NLS-1$ toolsMenu.add(preferences); if (Application.IS_MAC) { IContributionItem item = toolsMenu.find(ActionFactory.PREFERENCES.getId()); if (item != null) item.setVisible(false); } } } /* Menu: Window */ private void createWindowMenu(IMenuManager menuBar) { MenuManager windowMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_WINDOW, IWorkbenchActionConstants.M_WINDOW); menuBar.add(windowMenu); IAction openNewWindowAction = getAction(ActionFactory.OPEN_NEW_WINDOW.getId()); openNewWindowAction.setImageDescriptor(OwlUI.getImageDescriptor("icons/elcl16/newwindow.gif")); //$NON-NLS-1$ windowMenu.add(openNewWindowAction); windowMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); windowMenu.add(fOpenWindowsItem); // MenuManager showViewMenu = new MenuManager("&Show View"); // windowMenu.add(showViewMenu); // showViewMenu.add(fShowViewMenu); // windowMenu.add(new Separator()); // windowMenu.add(getAction(ActionFactory.EDIT_ACTION_SETS.getId())); // windowMenu.add(getAction(ActionFactory.RESET_PERSPECTIVE.getId())); // windowMenu.add(new Separator()); // // MenuManager navigationMenu = new MenuManager("&Navigation"); // windowMenu.add(navigationMenu); // // navigationMenu.add(getAction(ActionFactory.SHOW_PART_PANE_MENU.getId())); // navigationMenu.add(getAction(ActionFactory.SHOW_VIEW_MENU.getId())); // navigationMenu.add(new Separator()); // navigationMenu.add(getAction(ActionFactory.MAXIMIZE.getId())); // navigationMenu.add(getAction(ActionFactory.MINIMIZE.getId())); // navigationMenu.add(new Separator()); // navigationMenu.add(getAction(ActionFactory.ACTIVATE_EDITOR.getId())); // navigationMenu.add(getAction(ActionFactory.SHOW_EDITOR.getId())); // navigationMenu.add(getAction(ActionFactory.NEXT_EDITOR.getId())); // navigationMenu.add(getAction(ActionFactory.PREVIOUS_EDITOR.getId())); // navigationMenu.add(getAction(ActionFactory.SHOW_OPEN_EDITORS.getId())); // navigationMenu.add(getAction(ActionFactory.SHOW_WORKBOOK_EDITORS.getId())); // navigationMenu.add(new Separator()); // navigationMenu.add(getAction(ActionFactory.NEXT_PART.getId())); // navigationMenu.add(getAction(ActionFactory.PREVIOUS_PART.getId())); } /* Menu: Help */ private void createHelpMenu(IMenuManager menuBar) { MenuManager helpMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_HELP, IWorkbenchActionConstants.M_HELP); menuBar.add(helpMenu); helpMenu.add(new GroupMarker(IWorkbenchActionConstants.HELP_START)); /* Tutorial Wizard */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_TUTORIAL) { @Override public void run() { TutorialWizard wizard = new TutorialWizard(); OwlUI.openWizard(getActionBarConfigurer().getWindowConfigurer().getWindow().getShell(), wizard, false, false, null); } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.getImageDescriptor("icons/elcl16/help.gif"); //$NON-NLS-1$ } @Override public String getId() { return TutorialHandler.ID; } @Override public String getActionDefinitionId() { return TutorialHandler.ID; } }); /* Google Reader Synchronization */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_GOOGLE_READER_SYNC) { @Override public void run() { TutorialWizard wizard = new TutorialWizard(Chapter.SYNCHRONIZATION); OwlUI.openWizard(getActionBarConfigurer().getWindowConfigurer().getWindow().getShell(), wizard, false, false, null); } }); /* Link to Help */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_FAQ) { @Override public void run() { BrowserUtils.openLinkExternal("http://www.rssowl.org/help"); //$NON-NLS-1$ } }); /* Link to Forum */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_VISIT_FORUM) { @Override public void run() { BrowserUtils.openLinkExternal("http://sourceforge.net/projects/rssowl/forums/forum/296910"); //$NON-NLS-1$ } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.getImageDescriptor("icons/obj16/forum.gif"); //$NON-NLS-1$ } }); /* Show Key Bindings */ helpMenu.add(new Separator()); helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_SHOW_KEY_BINDINGS) { @Override public void run() { IWorkbench workbench = PlatformUI.getWorkbench(); IBindingService bindingService = (IBindingService) workbench.getService(IBindingService.class); bindingService.openKeyAssistDialog(); } }); helpMenu.add(new Separator()); /* Report Bugs */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_REPORT_PROBLEMS) { @Override public void run() { BrowserUtils.openLinkExternal("http://dev.rssowl.org"); //$NON-NLS-1$ } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.getImageDescriptor("icons/elcl16/bug.gif"); //$NON-NLS-1$ } }); /* Export Log to File */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_EXPORT_LOGFILE) { @Override public void run() { FileDialog dialog = new FileDialog(getActionBarConfigurer().getWindowConfigurer().getWindow().getShell(), SWT.SAVE); dialog.setText(Messages.ApplicationActionBarAdvisor_EXPORT_LOGFILE_DIALOG); dialog.setFilterExtensions(new String[] { "*.log" }); //$NON-NLS-1$ dialog.setFileName("rssowl.log"); //$NON-NLS-1$ dialog.setOverwrite(true); String file = dialog.open(); if (StringUtils.isSet(file)) { try { /* Check for Log Message from Core to have a complete log */ String logMessages = CoreUtils.getAndFlushLogMessages(); if (logMessages != null && logMessages.length() > 0) Activator.safeLogError(logMessages, null); /* Help to find out where the log is coming from */ Activator.safeLogInfo("Error Log Exported"); //$NON-NLS-1$ /* Export Log File */ File logFile = Platform.getLogFileLocation().toFile(); InputStream inS; if (logFile.exists()) inS = new FileInputStream(logFile); else inS = new ByteArrayInputStream(new byte[0]); FileOutputStream outS = new FileOutputStream(new File(file)); CoreUtils.copy(inS, outS); /* Append a Report of Feeds that are not loading if any */ String nl = System.getProperty("line.separator"); //$NON-NLS-1$ if (!StringUtils.isSet(nl)) nl = "\n"; //$NON-NLS-1$ StringBuilder errorReport = new StringBuilder(); Collection<IBookMark> bookmarks = DynamicDAO.getDAO(IBookMarkDAO.class).loadAll(); for (IBookMark bookmark : bookmarks) { if (bookmark.isErrorLoading()) { Object errorObj = bookmark.getProperty(Controller.LOAD_ERROR_KEY); if (errorObj != null && errorObj instanceof String) { errorReport.append(Controller.getDefault().createLogEntry(bookmark, null, (String) errorObj)); errorReport.append(nl).append(nl); } } } if (errorReport.length() > 0) { FileWriter writer = new FileWriter(new File(file), true); try { writer.append(nl).append(nl).append(nl); writer.write("--- Summary of Feeds that are not Loading -----------------------------------------------"); //$NON-NLS-1$ writer.append(nl).append(nl); writer.write(errorReport.toString()); writer.close(); } finally { writer.close(); } } } catch (FileNotFoundException e) { Activator.getDefault().logError(e.getMessage(), e); } catch (IOException e) { Activator.getDefault().logError(e.getMessage(), e); } } } }); helpMenu.add(new Separator()); /* Homepage */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_HOMEPAGE) { @Override public void run() { BrowserUtils.openLinkExternal("http://www.rssowl.org"); //$NON-NLS-1$ } }); /* License */ helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_LICENSE) { @Override public void run() { BrowserUtils.openLinkExternal("http://www.rssowl.org/legal/epl-v10.html"); //$NON-NLS-1$ } }); /* Donate */ helpMenu.add(new Separator()); helpMenu.add(new Action(Messages.ApplicationActionBarAdvisor_DONATE) { @Override public void run() { BrowserUtils.openLinkExternal("http://sourceforge.net/donate/index.php?group_id=86683"); //$NON-NLS-1$ } }); helpMenu.add(new Separator()); helpMenu.add(new Separator()); helpMenu.add(new GroupMarker(IWorkbenchActionConstants.HELP_END)); helpMenu.add(new Separator()); helpMenu.add(getAction(ActionFactory.ABOUT.getId())); if (Application.IS_MAC) { IContributionItem item = helpMenu.find(ActionFactory.ABOUT.getId()); if (item != null) item.setVisible(false); } } /* * @see org.eclipse.ui.application.ActionBarAdvisor#fillStatusLine(org.eclipse.jface.action.IStatusLineManager) */ @Override protected void fillStatusLine(IStatusLineManager statusLine) { super.fillStatusLine(statusLine); } /* * @see org.eclipse.ui.application.ActionBarAdvisor#fillActionBars(int) */ @Override public void fillActionBars(int flags) { super.fillActionBars(flags); } /** * @param trayItem * @param shell * @param advisor */ protected void fillTrayItem(IMenuManager trayItem, final Shell shell, final ApplicationWorkbenchWindowAdvisor advisor) { trayItem.add(new ReloadAllAction(false)); trayItem.add(new Separator()); trayItem.add(new Action(Messages.ApplicationActionBarAdvisor_CONFIGURE_NOTIFICATIONS) { @Override public void run() { advisor.restoreFromTray(shell); PreferencesUtil.createPreferenceDialogOn(shell, NotifierPreferencesPage.ID, null, null).open(); } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.getImageDescriptor("icons/elcl16/notification.gif"); //$NON-NLS-1$ } }); trayItem.add(new Action(Messages.ApplicationActionBarAdvisor_PREFERENCES) { @Override public void run() { advisor.restoreFromTray(shell); PreferencesUtil.createPreferenceDialogOn(shell, OverviewPreferencesPage.ID, null, null).open(); } @Override public ImageDescriptor getImageDescriptor() { return OwlUI.getImageDescriptor("icons/elcl16/preferences.gif"); //$NON-NLS-1$ } }); trayItem.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); trayItem.add(new Action(Messages.ApplicationActionBarAdvisor_EXIT) { @Override public void run() { PlatformUI.getWorkbench().close(); } }); } /* * @see org.eclipse.ui.application.ActionBarAdvisor#fillCoolBar(org.eclipse.jface.action.ICoolBarManager) */ @Override protected void fillCoolBar(ICoolBarManager coolBar) { /* CoolBar Context Menu */ MenuManager coolBarContextMenuManager = new MenuManager(null, "org.rssowl.ui.CoolBarContextMenu"); //$NON-NLS-1$ coolBar.setContextMenuManager(coolBarContextMenuManager); /* Customize Coolbar */ coolBarContextMenuManager.add(new Action(Messages.ApplicationActionBarAdvisor_CUSTOMIZE_TOOLBAR) { @Override public void run() { CustomizeToolbarDialog dialog = new CustomizeToolbarDialog(getActionBarConfigurer().getWindowConfigurer().getWindow().getShell()); if (dialog.open() == IDialogConstants.OK_ID) fCoolBarAdvisor.advise(true); } }); /* Lock Coolbar */ coolBarContextMenuManager.add(new Separator()); IAction lockToolbarAction = getAction(ActionFactory.LOCK_TOOL_BAR.getId()); lockToolbarAction.setText(Messages.ApplicationActionBarAdvisor_LOCK_TOOLBAR); coolBarContextMenuManager.add(lockToolbarAction); /* Toggle State of Toolbar Visibility */ coolBarContextMenuManager.add(new Action(Messages.ApplicationActionBarAdvisor_HIDE_TOOLBAR) { @Override public void run() { ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.fgPrimaryApplicationWorkbenchWindowAdvisor; configurer.setToolBarVisible(false, true); Owl.getPreferenceService().getGlobalScope().putBoolean(DefaultPreferences.SHOW_TOOLBAR, false); } }); /* Support for more Contributions */ coolBarContextMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); /* Coolbar Advisor */ fCoolBarAdvisor = new CoolBarAdvisor(coolBar, getActionBarConfigurer().getWindowConfigurer().getWindow()); fCoolBarAdvisor.advise(); } /** * @param manager the {@link IMenuManager} to fill this menu into. * @param selection the current {@link IStructuredSelection} of {@link INews}. * @param shellProvider a {@link IShellProvider} for dialogs. * @param directMenu if <code>true</code> directly fill all items to the menu, * otherwise create a sub menu. */ public static void fillAttachmentsMenu(IMenuManager manager, final IStructuredSelection selection, final IShellProvider shellProvider, boolean directMenu) { final List<Pair<IAttachment, URI>> attachments = ModelUtils.getAttachmentLinks(selection); if (!attachments.isEmpty()) { manager.add(new Separator("attachments")); //$NON-NLS-1$ /* Either as direct Menu or Submenu */ IMenuManager attachmentMenu; if (directMenu) attachmentMenu = manager; else { attachmentMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_ATTACHMENTS, "attachments"); //$NON-NLS-1$ manager.add(attachmentMenu); } final IPreferenceScope preferences = Owl.getPreferenceService().getGlobalScope(); /* Offer to Download All */ if (attachments.size() > 1) { int sumBytes = 0; for (Pair<IAttachment, URI> attachment : attachments) { if (attachment.getFirst().getLength() > 0) { sumBytes += attachment.getFirst().getLength(); } else { sumBytes = 0; break; } } String sumSize = OwlUI.getSize(sumBytes); Action downloadAllAction = new Action(sumSize != null ? (NLS.bind(Messages.ApplicationActionBarAdvisor_DOWNLOAD_ALL_WITH_SIZE, sumSize)) : (Messages.ApplicationActionBarAdvisor_DOWNLOAD_ALL)) { @Override public void run() { DirectoryDialog dialog = new DirectoryDialog(shellProvider.getShell(), SWT.None); dialog.setText(Messages.ApplicationActionBarAdvisor_SELECT_FOLDER_FOR_DOWNLOADS); String downloadFolder = preferences.getString(DefaultPreferences.DOWNLOAD_FOLDER); if (StringUtils.isSet(downloadFolder) && new File(downloadFolder).exists()) dialog.setFilterPath(downloadFolder); String folder = dialog.open(); if (StringUtils.isSet(folder)) { for (Pair<IAttachment, URI> attachment : attachments) { Controller.getDefault().getDownloadService().download(DownloadRequest.createAttachmentDownloadRequest(attachment.getFirst(), attachment.getSecond(), new File(folder), true, null)); } /* Remember Download Folder in Settings */ preferences.putString(DefaultPreferences.DOWNLOAD_FOLDER, folder); } } }; downloadAllAction.setImageDescriptor(OwlUI.getImageDescriptor("icons/elcl16/save_all.gif")); //$NON-NLS-1$ attachmentMenu.add(downloadAllAction); attachmentMenu.add(new Separator()); } /* Collect openable Attachments that have already been downloaded */ List<Action> openActions = new ArrayList<Action>(1); Set<String> downloadLocations = getDownloadLocations(); /* Offer Download Action for each */ for (final Pair<IAttachment, URI> attachmentPair : attachments) { IAttachment attachment = attachmentPair.getFirst(); final String fileName = URIUtils.getFile(attachmentPair.getSecond(), OwlUI.getExtensionForMime(attachment.getType())); String size = OwlUI.getSize(attachment.getLength()); Action action = new Action(size != null ? (NLS.bind(Messages.ApplicationActionBarAdvisor_FILE_SIZE, fileName, size)) : (fileName)) { @Override public void run() { FileDialog dialog = new FileDialog(shellProvider.getShell(), SWT.SAVE); dialog.setText(Messages.ApplicationActionBarAdvisor_SELECT_FILE_FOR_DOWNLOAD); dialog.setFileName(Application.IS_WINDOWS ? CoreUtils.getSafeFileNameForWindows(fileName) : fileName); dialog.setOverwrite(true); String downloadFolder = preferences.getString(DefaultPreferences.DOWNLOAD_FOLDER); if (StringUtils.isSet(downloadFolder) && new File(downloadFolder).exists()) dialog.setFilterPath(downloadFolder); String selectedFileName = dialog.open(); if (StringUtils.isSet(selectedFileName)) { File file = new File(selectedFileName); Controller.getDefault().getDownloadService().download(DownloadRequest.createAttachmentDownloadRequest(attachmentPair.getFirst(), attachmentPair.getSecond(), file.getParentFile(), true, file.getName())); /* Remember Download Folder in Settings */ preferences.putString(DefaultPreferences.DOWNLOAD_FOLDER, file.getParentFile().toString()); } } }; action.setImageDescriptor(OwlUI.getImageDescriptor("icons/etool16/save_as.gif")); //$NON-NLS-1$ attachmentMenu.add(action); /* Check if Attachment already exists and offer Open Action then */ String usedFileName = Application.IS_WINDOWS ? CoreUtils.getSafeFileNameForWindows(fileName) : fileName; if (shouldOfferOpenAction(usedFileName)) { for (String downloadLocation : downloadLocations) { final File downloadedFile = new File(downloadLocation, usedFileName); if (downloadedFile.exists()) { Action openAction = new Action(NLS.bind(Messages.ApplicationActionBarAdvisor_OPEN_FILE, fileName)) { @Override public void run() { Program.launch(downloadedFile.toString()); } }; openAction.setImageDescriptor(OwlUI.getAttachmentImage(fileName, attachmentPair.getFirst().getType())); openActions.add(openAction); break; } } } } boolean separate = true; /* Offer Open Action for each downloaded */ if (!openActions.isEmpty()) { attachmentMenu.add(new Separator()); for (Action openAction : openActions) { attachmentMenu.add(openAction); } } /* Offer Copy Action for Attachment Link */ else if (attachments.size() == 1) { separate = false; attachmentMenu.add(new Separator()); CopyLinkAction action = new CopyLinkAction(); action.setIgnoreActiveSelection(true); action.selectionChanged(action, new StructuredSelection(attachments.iterator().next().getFirst())); attachmentMenu.add(action); } /* Offer to Automize Downloading */ if (separate) attachmentMenu.add(new Separator()); attachmentMenu.add(new AutomateFilterAction(PresetAction.DOWNLOAD, selection)); } } private static boolean shouldOfferOpenAction(String filename) { if (Application.IS_WINDOWS) return !filename.endsWith(".exe") && !filename.endsWith(".bat") && !filename.endsWith(".com"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return true; } private static Set<String> getDownloadLocations() { IPreferenceScope preferences = Owl.getPreferenceService().getGlobalScope(); Set<String> locations = new HashSet<String>(1); /* Check Preference */ String folderPath = preferences.getString(DefaultPreferences.DOWNLOAD_FOLDER); if (folderPath != null) { File folder = new File(folderPath); if (folder.exists()) locations.add(folderPath); } /* Check Filters */ Collection<ISearchFilter> filters = DynamicDAO.loadAll(ISearchFilter.class); for (ISearchFilter filter : filters) { List<IFilterAction> actions = filter.getActions(); for (IFilterAction action : actions) { if (DownloadAttachmentsNewsAction.ID.equals(action.getActionId()) && action.getData() instanceof String) { folderPath = (String) action.getData(); if (folderPath != null) { File folder = new File(folderPath); if (folder.exists()) locations.add(folderPath); } } } } return locations; } /** * @param manager the {@link IMenuManager} to fill this menu into. * @param selection the current {@link IStructuredSelection} of {@link INews}. * @param shellProvider a {@link IShellProvider} for dialogs. * @param directMenu if <code>true</code> directly fill all items to the menu, * otherwise create a sub menu. */ public static void fillShareMenu(IMenuManager manager, final IStructuredSelection selection, final IShellProvider shellProvider, boolean directMenu) { manager.add(new Separator("share")); //$NON-NLS-1$ /* Either as direct Menu or Submenu */ IMenuManager shareMenu; if (directMenu) shareMenu = manager; else { shareMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_SHARE_NEWS, OwlUI.SHARE, "sharenews"); //$NON-NLS-1$ manager.add(shareMenu); } /* List all selected Share Providers */ final boolean isEnabled = !selection.isEmpty() && !ModelUtils.isEntityGroupSelected(selection); List<ShareProvider> providers = Controller.getDefault().getShareProviders(); for (final ShareProvider provider : providers) { if (provider.isEnabled()) { shareMenu.add(new Action(provider.getName()) { @Override public void run() { Controller.getDefault().share(selection, provider); }; @Override public ImageDescriptor getImageDescriptor() { if (StringUtils.isSet(provider.getIconPath())) return OwlUI.getImageDescriptor(provider.getPluginId(), provider.getIconPath()); return super.getImageDescriptor(); }; @Override public String getText() { IBindingService bs = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); TriggerSequence binding = bs.getBestActiveBindingFor(provider.getId()); return binding != null ? NLS.bind(Messages.ApplicationActionBarAdvisor_SHARE_BINDING, provider.getName(), binding.format()) : provider.getName(); } @Override public boolean isEnabled() { return isEnabled; } @Override public String getActionDefinitionId() { return SendLinkAction.ID.equals(provider.getId()) ? SendLinkAction.ID : super.getActionDefinitionId(); } @Override public String getId() { return SendLinkAction.ID.equals(provider.getId()) ? SendLinkAction.ID : super.getId(); } }); } } /* Allow to Configure Providers */ shareMenu.add(new Separator()); shareMenu.add(new Action(Messages.ApplicationActionBarAdvisor_CONFIGURE) { @Override public void run() { PreferencesUtil.createPreferenceDialogOn(shellProvider.getShell(), SharingPreferencesPage.ID, null, null).open(); }; }); } /** * @param manager the {@link IMenuManager} to fill this menu into. * @param selection the current {@link IStructuredSelection} of {@link INews}. * @param shellProvider a {@link IShellProvider} for dialogs. * @param directMenu if <code>true</code> directly fill all items to the menu, * otherwise create a sub menu. */ public static void fillLabelMenu(IMenuManager manager, final IStructuredSelection selection, final IShellProvider shellProvider, boolean directMenu) { /* Either as direct Menu or Submenu */ IMenuManager labelMenu; if (directMenu) labelMenu = manager; else { labelMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_LABEL); manager.add(labelMenu); } /* Assign Labels */ labelMenu.add(new AssignLabelsAction(shellProvider.getShell(), selection)); /* Organize Labels */ labelMenu.add(new Action(Messages.ApplicationActionBarAdvisor_ORGANIZE_LABELS) { @Override public void run() { PreferencesUtil.createPreferenceDialogOn(shellProvider.getShell(), ManageLabelsPreferencePage.ID, null, null).open(); } }); /* Load Labels */ final Collection<ILabel> labels = CoreUtils.loadSortedLabels(); /* Retrieve Labels that all selected News contain */ labelMenu.add(new Separator()); Set<ILabel> selectedLabels = ModelUtils.getLabelsForAll(selection); for (final ILabel label : labels) { LabelAction labelAction = new LabelAction(label, selection); labelAction.setChecked(selectedLabels.contains(label)); labelMenu.add(labelAction); } /* New Label */ labelMenu.add(new Action(Messages.ApplicationActionBarAdvisor_NEW_LABEL) { @Override public void run() { LabelDialog dialog = new LabelDialog(shellProvider.getShell(), DialogMode.ADD, null); if (dialog.open() == IDialogConstants.OK_ID) { String name = dialog.getName(); RGB color = dialog.getColor(); ILabel newLabel = Owl.getModelFactory().createLabel(null, name); newLabel.setColor(OwlUI.toString(color)); newLabel.setOrder(labels.size()); DynamicDAO.save(newLabel); LabelAction labelAction = new LabelAction(newLabel, selection); labelAction.run(); } } @Override public boolean isEnabled() { return !selection.isEmpty(); } }); /* Remove All Labels */ labelMenu.add(new Separator()); LabelAction removeAllLabels = new LabelAction(null, selection); removeAllLabels.setId(RemoveLabelsHandler.ID); removeAllLabels.setActionDefinitionId(RemoveLabelsHandler.ID); removeAllLabels.setEnabled(!selection.isEmpty() && !labels.isEmpty()); labelMenu.add(removeAllLabels); } /** * @param menu the {@link IMenuManager} to fill. * @param window the {@link IWorkbenchWindow} where the menu is living. */ public static void fillBookMarksMenu(IMenuManager menu, IWorkbenchWindow window) { Set<IFolder> roots = CoreUtils.loadRootFolders(); /* Filter Options */ final IPreferenceScope preferences = Owl.getPreferenceService().getGlobalScope(); BookMarkFilter.Type[] allFilters = BookMarkFilter.Type.values(); BookMarkFilter.Type selectedFilter = allFilters[preferences.getInteger(DefaultPreferences.BM_MENU_FILTER)]; List<BookMarkFilter.Type> displayedFilters = Arrays.asList(new BookMarkFilter.Type[] { BookMarkFilter.Type.SHOW_ALL, BookMarkFilter.Type.SHOW_NEW, BookMarkFilter.Type.SHOW_UNREAD, BookMarkFilter.Type.SHOW_STICKY }); MenuManager optionsMenu = new MenuManager(Messages.ApplicationActionBarAdvisor_FILTER_ELEMENTS, (selectedFilter == BookMarkFilter.Type.SHOW_ALL) ? OwlUI.FILTER : OwlUI.getImageDescriptor("icons/etool16/filter_active.gif"), null); //$NON-NLS-1$ for (final BookMarkFilter.Type filter : displayedFilters) { String name = Messages.ApplicationActionBarAdvisor_SHOW_ALL; switch (filter) { case SHOW_NEW: name = Messages.ApplicationActionBarAdvisor_SHOW_NEW; break; case SHOW_UNREAD: name = Messages.ApplicationActionBarAdvisor_SHOW_UNREAD; break; case SHOW_STICKY: name = Messages.ApplicationActionBarAdvisor_SHOW_STICKY; break; } Action action = new Action(name, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (isChecked()) preferences.putInteger(DefaultPreferences.BM_MENU_FILTER, filter.ordinal()); } }; action.setChecked(filter == selectedFilter); optionsMenu.add(action); if (filter == BookMarkFilter.Type.SHOW_ALL) optionsMenu.add(new Separator()); } menu.add(optionsMenu); menu.add(new Separator()); /* Single Bookmark Set */ if (roots.size() == 1) { fillBookMarksMenu(window, preferences, menu, roots.iterator().next().getChildren(), selectedFilter); } /* More than one Bookmark Set */ else { for (IFolder root : roots) { if (shouldShow(root, selectedFilter)) { MenuManager rootItem = new MenuManager(root.getName(), OwlUI.BOOKMARK_SET, null); menu.add(rootItem); fillBookMarksMenu(window, preferences, rootItem, root.getChildren(), selectedFilter); } } } /* Indicate that no Items are Showing */ if (menu.getItems().length == 2 && selectedFilter != BookMarkFilter.Type.SHOW_ALL) { boolean hasBookMarks = false; for (IFolder root : roots) { if (!root.getChildren().isEmpty()) { hasBookMarks = true; break; } } if (hasBookMarks) { menu.add(new Action(Messages.ApplicationActionBarAdvisor_SOME_ELEMENTS_FILTERED) { @Override public boolean isEnabled() { return false; } }); } } } private static boolean shouldShow(IFolderChild child, BookMarkFilter.Type filter) { switch (filter) { case SHOW_ALL: return true; case SHOW_NEW: return hasNewsWithState(child, EnumSet.of(INews.State.NEW)); case SHOW_UNREAD: return hasNewsWithState(child, EnumSet.of(INews.State.NEW, INews.State.UNREAD, INews.State.UPDATED)); case SHOW_STICKY: return hasStickyNews(child); default: return true; } } private static void fillBookMarksMenu(final IWorkbenchWindow window, final IPreferenceScope preferences, IMenuManager parent, List<IFolderChild> childs, final BookMarkFilter.Type filter) { for (final IFolderChild child : childs) { /* Check if a Filter applies */ if (!shouldShow(child, filter)) continue; /* News Mark or Empty Folder */ if (child instanceof INewsMark || (child instanceof IFolder && ((IFolder) child).getChildren().isEmpty())) { String name = child.getName(); if (child instanceof INewsMark) { int unreadNewsCount = (((INewsMark) child).getNewsCount(EnumSet.of(INews.State.NEW, INews.State.UNREAD, INews.State.UPDATED))); if (unreadNewsCount > 0) name = NLS.bind(Messages.ApplicationActionBarAdvisor_MARK_UNREAD_COUNT, name, unreadNewsCount); } Action action = new Action(name) { @Override public void run() { if (child instanceof INewsMark) OwlUI.openInFeedView(window.getActivePage(), new StructuredSelection(child)); } }; action.setImageDescriptor(getImageDescriptor(child)); parent.add(action); } /* Folder with Children */ else if (child instanceof IFolder) { final IFolder folder = (IFolder) child; final MenuManager folderMenu = new MenuManager(folder.getName(), getImageDescriptor(folder), null); parent.add(folderMenu); folderMenu.add(new Action("") {}); //Dummy Action //$NON-NLS-1$ folderMenu.setRemoveAllWhenShown(true); folderMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { /* Open Folder */ folderMenu.add(new Action(Messages.ApplicationActionBarAdvisor_OPEN_FOLDER) { @Override public void run() { OwlUI.openInFeedView(window.getActivePage(), new StructuredSelection(child)); } }); /* Offer Actions to force open a new Tab */ if (preferences.getBoolean(DefaultPreferences.ALWAYS_REUSE_FEEDVIEW) && OwlUI.isTabbedBrowsingEnabled()) { /* Open Folder in New Tab */ folderMenu.add(new OpenInNewTabAction(OwlUI.getPage(window), new StructuredSelection(child))); /* Open All in New Tabs */ folderMenu.add(new OpenInNewTabAction(OwlUI.getPage(window), folder)); } folderMenu.add(new Separator()); /* Show other entries */ fillBookMarksMenu(window, preferences, folderMenu, folder.getChildren(), filter); } }); } } } private static ImageDescriptor getImageDescriptor(IFolderChild child) { boolean hasNewNews = hasNewsWithState(child, EnumSet.of(INews.State.NEW)); /* Bookmark */ if (child instanceof IBookMark) { ImageDescriptor favicon = OwlUI.getFavicon((IBookMark) child); if (!hasNewNews) return (favicon != null) ? favicon : OwlUI.BOOKMARK; /* Overlay if News are *new* */ Image base = (favicon != null) ? OwlUI.getImage(fgResources, favicon) : OwlUI.getImage(fgResources, OwlUI.BOOKMARK); DecorationOverlayIcon overlay = new DecorationOverlayIcon(base, OwlUI.getImageDescriptor("icons/ovr16/new.gif"), IDecoration.BOTTOM_RIGHT); //$NON-NLS-1$ return overlay; } /* Saved Search */ else if (child instanceof ISearchMark) { if (hasNewNews) return OwlUI.SEARCHMARK_NEW; else if (((INewsMark) child).getNewsCount(INews.State.getVisible()) != 0) return OwlUI.SEARCHMARK; return OwlUI.SEARCHMARK_EMPTY; } /* News Bin */ else if (child instanceof INewsBin) { boolean isArchive = child.getProperty(DefaultPreferences.ARCHIVE_BIN_MARKER) != null; if (hasNewNews) return isArchive ? OwlUI.ARCHIVE_NEW : OwlUI.NEWSBIN_NEW; else if (isArchive) return OwlUI.ARCHIVE; else if (((INewsMark) child).getNewsCount(INews.State.getVisible()) != 0) return OwlUI.NEWSBIN; return OwlUI.NEWSBIN_EMPTY; } /* Folder */ else if (child instanceof IFolder) return hasNewNews ? OwlUI.FOLDER_NEW : OwlUI.FOLDER; return null; } private static boolean hasNewsWithState(IFolderChild child, EnumSet<INews.State> states) { if (child instanceof IFolder) return hasNewsWithStates((IFolder) child, states); return ((INewsMark) child).getNewsCount(states) != 0; } private static boolean hasNewsWithStates(IFolder folder, EnumSet<INews.State> states) { List<IMark> marks = folder.getMarks(); for (IMark mark : marks) { if (mark instanceof INewsMark && ((INewsMark) mark).getNewsCount(states) != 0) return true; } List<IFolder> folders = folder.getFolders(); for (IFolder child : folders) { if (hasNewsWithStates(child, states)) return true; } return false; } private static boolean hasStickyNews(IFolderChild child) { if (child instanceof IFolder) return hasStickyNews((IFolder) child); if (child instanceof IBookMark) return ((IBookMark) child).getStickyNewsCount() != 0; return false; } private static boolean hasStickyNews(IFolder folder) { List<IMark> marks = folder.getMarks(); for (IMark mark : marks) { if (mark instanceof IBookMark && ((IBookMark) mark).getStickyNewsCount() != 0) return true; } List<IFolder> folders = folder.getFolders(); for (IFolder child : folders) { if (hasStickyNews(child)) return true; } return false; } }
epl-1.0
DavidGutknecht/elexis-3-base
bundles/ch.elexis.docbox.ws.client/src-gen/org/hl7/v3/POCDMT000040Custodian.java
6301
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for POCD_MT000040.Custodian complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="POCD_MT000040.Custodian"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="realmCode" type="{urn:hl7-org:v3}CS" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="typeId" type="{urn:hl7-org:v3}POCD_MT000040.InfrastructureRoot.typeId" minOccurs="0"/> * &lt;element name="templateId" type="{urn:hl7-org:v3}II" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="assignedCustodian" type="{urn:hl7-org:v3}POCD_MT000040.AssignedCustodian"/> * &lt;/sequence> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="typeCode" type="{urn:hl7-org:v3}ParticipationType" fixed="CST" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "POCD_MT000040.Custodian", propOrder = { "realmCode", "typeId", "templateId", "assignedCustodian" }) public class POCDMT000040Custodian { protected List<CS> realmCode; protected POCDMT000040InfrastructureRootTypeId typeId; protected List<II> templateId; @XmlElement(required = true) protected POCDMT000040AssignedCustodian assignedCustodian; @XmlAttribute protected List<String> nullFlavor; @XmlAttribute protected List<String> typeCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link POCDMT000040InfrastructureRootTypeId } * */ public POCDMT000040InfrastructureRootTypeId getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link POCDMT000040InfrastructureRootTypeId } * */ public void setTypeId(POCDMT000040InfrastructureRootTypeId value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the assignedCustodian property. * * @return * possible object is * {@link POCDMT000040AssignedCustodian } * */ public POCDMT000040AssignedCustodian getAssignedCustodian() { return assignedCustodian; } /** * Sets the value of the assignedCustodian property. * * @param value * allowed object is * {@link POCDMT000040AssignedCustodian } * */ public void setAssignedCustodian(POCDMT000040AssignedCustodian value) { this.assignedCustodian = value; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the typeCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the typeCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTypeCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getTypeCode() { if (typeCode == null) { typeCode = new ArrayList<String>(); } return this.typeCode; } }
epl-1.0
lbeurerkellner/n4js
plugins/org.eclipse.n4js.json/src-gen/org/eclipse/n4js/json/AbstractJSONRuntimeModule.java
6467
/** * Copyright (c) 2017 NumberFour AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * NumberFour AG - Initial API and implementation */ package org.eclipse.n4js.json; import com.google.inject.Binder; import com.google.inject.Provider; import com.google.inject.name.Names; import java.util.Properties; import org.eclipse.n4js.json.formatting2.JSONFormatter; import org.eclipse.n4js.json.parser.antlr.JSONAntlrTokenFileProvider; import org.eclipse.n4js.json.parser.antlr.JSONParser; import org.eclipse.n4js.json.parser.antlr.internal.InternalJSONLexer; import org.eclipse.n4js.json.serializer.JSONSemanticSequencer; import org.eclipse.n4js.json.serializer.JSONSyntacticSequencer; import org.eclipse.n4js.json.services.JSONGrammarAccess; import org.eclipse.n4js.json.validation.JSONValidator; import org.eclipse.xtext.Constants; import org.eclipse.xtext.IGrammarAccess; import org.eclipse.xtext.formatting2.FormatterPreferenceValuesProvider; import org.eclipse.xtext.formatting2.FormatterPreferences; import org.eclipse.xtext.formatting2.IFormatter2; import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider; import org.eclipse.xtext.naming.IQualifiedNameProvider; import org.eclipse.xtext.parser.IParser; import org.eclipse.xtext.parser.ITokenToStringConverter; import org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider; import org.eclipse.xtext.parser.antlr.AntlrTokenToStringConverter; import org.eclipse.xtext.parser.antlr.IAntlrTokenFileProvider; import org.eclipse.xtext.parser.antlr.ITokenDefProvider; import org.eclipse.xtext.parser.antlr.Lexer; import org.eclipse.xtext.parser.antlr.LexerBindings; import org.eclipse.xtext.parser.antlr.LexerProvider; import org.eclipse.xtext.preferences.IPreferenceValuesProvider; import org.eclipse.xtext.serializer.ISerializer; import org.eclipse.xtext.serializer.impl.Serializer; import org.eclipse.xtext.serializer.sequencer.ISemanticSequencer; import org.eclipse.xtext.serializer.sequencer.ISyntacticSequencer; import org.eclipse.xtext.service.DefaultRuntimeModule; import org.eclipse.xtext.service.SingletonBinding; /** * Manual modifications go to {@link JSONRuntimeModule}. */ @SuppressWarnings("all") public abstract class AbstractJSONRuntimeModule extends DefaultRuntimeModule { protected Properties properties = null; @Override public void configure(Binder binder) { properties = tryBindProperties(binder, "org/eclipse/n4js/json/JSON.properties"); super.configure(binder); } public void configureLanguageName(Binder binder) { binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.n4js.json.JSON"); } public void configureFileExtensions(Binder binder) { if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null) binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("json"); } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class<? extends ISemanticSequencer> bindISemanticSequencer() { return JSONSemanticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class<? extends ISyntacticSequencer> bindISyntacticSequencer() { return JSONSyntacticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class<? extends ISerializer> bindISerializer() { return Serializer.class; } // contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2 @SingletonBinding(eager=true) public Class<? extends JSONValidator> bindJSONValidator() { return JSONValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public Class<? extends IFormatter2> bindIFormatter2() { return JSONFormatter.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public void configureFormatterPreferences(Binder binder) { binder.bind(IPreferenceValuesProvider.class).annotatedWith(FormatterPreferences.class).to(FormatterPreferenceValuesProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public ClassLoader bindClassLoaderToInstance() { return getClass().getClassLoader(); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public Class<? extends IGrammarAccess> bindIGrammarAccess() { return JSONGrammarAccess.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends IParser> bindIParser() { return JSONParser.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends ITokenToStringConverter> bindITokenToStringConverter() { return AntlrTokenToStringConverter.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends IAntlrTokenFileProvider> bindIAntlrTokenFileProvider() { return JSONAntlrTokenFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends Lexer> bindLexer() { return InternalJSONLexer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends ITokenDefProvider> bindITokenDefProvider() { return AntlrTokenDefProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Provider<? extends InternalJSONLexer> provideInternalJSONLexer() { return LexerProvider.create(InternalJSONLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureRuntimeLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerBindings.RUNTIME)) .to(InternalJSONLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2 public Class<? extends IQualifiedNameProvider> bindIQualifiedNameProvider() { return DefaultDeclarativeQualifiedNameProvider.class; } }
epl-1.0
msteindorfer/oopsla15-artifact
pdb.values.persistent.clojure/src/main/java/org/eclipse/imp/pdb/facts/impl/persistent/clojure/Node.java
5537
/******************************************************************************* * Copyright (c) 2012-2013 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI *******************************************************************************/ package org.eclipse.imp.pdb.facts.impl.persistent.clojure; //import static org.eclipse.imp.pdb.facts.impl.persistent.clojure.ClojureHelper.core$merge; // //import java.util.Iterator; //import java.util.Map; // //import org.eclipse.imp.pdb.facts.IList; //import org.eclipse.imp.pdb.facts.INode; //import org.eclipse.imp.pdb.facts.IValue; //import org.eclipse.imp.pdb.facts.IValueFactory; //import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; //import org.eclipse.imp.pdb.facts.impl.AbstractNode; //import org.eclipse.imp.pdb.facts.type.Type; //import org.eclipse.imp.pdb.facts.type.TypeFactory; //import org.eclipse.imp.pdb.facts.visitors.IValueVisitor; // //import clojure.lang.IPersistentMap; //import clojure.lang.IPersistentVector; //import clojure.lang.PersistentHashMap; //import clojure.lang.PersistentVector; // //public class Node extends AbstractNode { // // protected final String name; // protected final IPersistentVector children; // protected final IPersistentMap annotations; // // protected Node(Type type, String name, IPersistentVector children, IPersistentMap annotations) { // super(type); // this.name = name.intern(); // NOTE: using intern() here! // this.children = children; // this.annotations = annotations; // } // // protected Node(String name) { // this(TypeFactory.getInstance().nodeType(), name, PersistentVector.EMPTY, PersistentHashMap.EMPTY); // } // // protected Node(String name, IValue... children) { // this(TypeFactory.getInstance().nodeType(), name, PersistentVector.create((Object[])children), PersistentHashMap.EMPTY); // } // // protected Node(String name, java.util.Map<String, IValue> newAnnotationsMap, IValue... children) { // this(TypeFactory.getInstance().nodeType(), name, PersistentVector.create((Object[])children), PersistentHashMap.create(newAnnotationsMap)); // } // // @Override // public IValue get(int i) throws IndexOutOfBoundsException { // return (IValue) children.nth(i); // } // // @Override // public INode set(int i, IValue newChild) throws IndexOutOfBoundsException { // return new Node(type, name, children.assocN(i, newChild), annotations); // } // // @Override // public int arity() { // return children.length(); // } // // @Override // public String getName() { // return name; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // @Override // public Iterable<IValue> getChildren() { // return (Iterable) children; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // @Override // public Iterator<IValue> iterator() { // return ((Iterable) children).iterator(); // } // // @Override // public IValue getAnnotation(String label) throws FactTypeUseException { // return (IValue) annotations.valAt(label, null); // } // // @Override // public INode setAnnotation(String label, IValue newValue) // throws FactTypeUseException { // return new Node(type, name, children, annotations.assoc(label, newValue)); // } // // @Override // public boolean hasAnnotation(String label) throws FactTypeUseException { // return annotations.containsKey(label); // } // // @Override // public boolean hasAnnotations() { // return !(annotations.count() == 0); // } // // @SuppressWarnings("unchecked") // @Override // public Map<String, IValue> getAnnotations() { // return (Map<String, IValue>) annotations; // } // // @Override // public INode setAnnotations(Map<String, IValue> newAnnotations) { // return new Node(type, name, children, PersistentHashMap.create(newAnnotations)); // } // // @Override // public INode joinAnnotations(Map<String, IValue> newAnnotationsMap) { // IPersistentMap newAnnotations = core$merge(annotations, PersistentHashMap.create(newAnnotationsMap)); // return new Node(type, name, children, newAnnotations); // } // // @Override // public INode removeAnnotation(String key) { // return new Node(type, name, children, annotations.without(key)); // } // // @Override // public INode removeAnnotations() { // return new Node(type, name, children, (IPersistentMap) annotations.empty()); // } // // @Override // public String[] getKeywordArgumentNames() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Type getType() { // // TODO Auto-generated method stub // return null; // } // // @Override // public boolean equals(Object other) { // if (other instanceof Node) { // Node that = (Node) other; // return this.name.equals(that.name) // && this.children.equals(that.children); //// && this.annotations.equals(that.annotations); // } else { // return false; // } // } // // @Override // public boolean isEqual(IValue other) { // return this.equals(other); // } // // @SuppressWarnings("rawtypes") // @Override // public int hashCode() { // int hash = 0; // // for (Object child : (Iterable) children) { // hash = (hash << 1) ^ (hash >> 1) ^ child.hashCode(); // } // return hash; // } // // @Override // protected IValueFactory getValueFactory() { // return ValueFactory.getInstance(); // } // //}
epl-1.0
sleshchenko/che
plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/java/org/eclipse/che/plugin/java/server/che/SourceFromBytecodeGeneratorTest.java
11803
/* * Copyright (c) 2012-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.plugin.java.server.che; import static org.fest.assertions.Assertions.assertThat; import org.eclipse.che.plugin.java.server.SourcesFromBytecodeGenerator; import org.eclipse.jdt.core.IType; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** @author Evgen Vidolob */ // TODO: rework after new Project API @Ignore public class SourceFromBytecodeGeneratorTest extends BaseTest { private IType type; private IType zipFileSystem; @Before public void findType() throws Exception { type = project.findType("com.sun.nio.zipfs.ZipFileStore"); zipFileSystem = project.findType("com.sun.nio.zipfs.ZipFileSystem"); } @Test public void testClassComment() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(type); assertThat(source) .isNotNull() .isNotEmpty() .contains("// Failed to get sources. Instead, stub sources have been generated.") .contains("// Implementation of methods is unavailable."); } @Test public void testPackageDeclaration() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(type); assertThat(source).contains("package com.sun.nio.zipfs;"); } @Test public void testClassDeclaration() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(type); assertThat(source).contains("public class ZipFileStore extends java.nio.file.FileStore {"); } @Test public void testFieldsDeclaration() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(type); assertThat(source).contains(" private final com.sun.nio.zipfs.ZipFileSystem zfs;"); } @Test public void testFieldsDeclaration2() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source).contains(" private boolean readOnly;"); } @Test public void testFieldsDeclaration3() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source).contains(" private final boolean createNew;"); } @Test public void testFieldsDeclaration4() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " private static final java.util.Set<java.lang.String> supportedFileAttributeViews;"); } @Test public void testFieldsDeclaration5() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains(" private static final java.lang.String GLOB_SYNTAX = \"glob\";"); } @Test public void testFieldsDeclaration6() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source).contains(" private static byte[] ROOTPATH;"); } @Test public void testFieldsDeclaration7() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " private java.util.LinkedHashMap<com.sun.nio.zipfs.ZipFileSystem.IndexNode,com.sun.nio.zipfs.ZipFileSystem.IndexNode> inodes;"); } @Test public void testFieldsDeclaration8() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source).contains(" private com.sun.nio.zipfs.ZipFileSystem.IndexNode root;"); } @Test public void testFieldsDeclaration9() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source).contains(" private final int MAX_FLATER = 20;"); } @Test public void testConstructorDeclaration() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " ZipFileSystem(com.sun.nio.zipfs.ZipFileSystemProvider arg0, java.nio.file.Path arg1, java.util.Map<java.lang.String,?> arg2) throws java.io.IOException { /* compiled code */ }"); } @Test public void testMethodDeclaration() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " public java.nio.file.spi.FileSystemProvider provider() { /* compiled code */ }"); } @Test public void testMethodDeclaration2() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " public com.sun.nio.zipfs.ZipPath getPath(java.lang.String arg0, java.lang.String[] arg1) { /* compiled code */ }"); } @Test public void testMethodDeclaration3() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " void createDirectory(byte[] arg0, java.nio.file.attribute.FileAttribute<?>[] arg1) throws java.io.IOException { /* compiled code */ }"); } @Test public void testGenericMethodDeclaration() throws Exception { IType iType = project.findType("com.sun.nio.zipfs.ZipFileStore"); String source = new SourcesFromBytecodeGenerator().generateSource(iType); assertThat(source) .contains( "public <V extends java.nio.file.attribute.FileStoreAttributeView> V getFileStoreAttributeView(java.lang.Class<V> arg0) { /* compiled code */ }"); } @Test public void testEnumDeclaration() throws Exception { IType enumType = project.findType("javax.servlet.DispatcherType"); String source = new SourcesFromBytecodeGenerator().generateSource(enumType); assertThat(source) .contains( "\n" + "public final enum DispatcherType {\n" + " FORWARD, INCLUDE, REQUEST, ASYNC, ERROR;\n" + "\n" + " public static javax.servlet.DispatcherType[] values() { /* compiled code */ }\n" + "\n" + " public static javax.servlet.DispatcherType valueOf(java.lang.String name) { /* " + "compiled code */ }\n" + "\n" + " private DispatcherType() { /* compiled code */ }\n" + "\n" + "}"); } @Test public void testInnerTypeDeclaration() throws Exception { String source = new SourcesFromBytecodeGenerator().generateSource(zipFileSystem); assertThat(source) .contains( " private static class ExChannelCloser {\n" + " java.nio.file.Path path;\n" + " java.nio.channels.SeekableByteChannel ch;\n" + " java.util.Set<java.io.InputStream> streams;\n" + "\n" + " ExChannelCloser(java.nio.file.Path arg0, java.nio.channels.SeekableByteChannel " + "arg1, java.util.Set<java.io.InputStream> arg2) { /* compiled code */ }\n" + "\n" + " }"); } @Test public void testInterfaceDeclaration() throws Exception { IType interfaceType = project.findType("java.lang.CharSequence"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source).contains("public interface CharSequence {"); } @Test public void testInterfaceMethodDeclaration() throws Exception { IType interfaceType = project.findType("java.lang.CharSequence"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source) .contains(" public int length();") .contains(" public char charAt(int arg0);") .contains(" public java.lang.CharSequence subSequence(int arg0, int arg1);") .contains(" public java.lang.String toString();"); } @Test public void testTypeExtendsGeneric() throws Exception { IType interfaceType = project.findType("com.sun.nio.zipfs.ZipDirectoryStream"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source) .contains( "public class ZipDirectoryStream implements java.nio.file.DirectoryStream<java.nio.file.Path> {\n" + " private final com.sun.nio.zipfs.ZipFileSystem zipfs;\n" + " private final byte[] path;\n" + " private final java.nio.file.DirectoryStream.Filter<? super java.nio.file.Path> filter;\n" + " private volatile boolean isClosed;\n" + " private volatile java.util.Iterator<java.nio.file.Path> itr;\n" + "\n" + " ZipDirectoryStream(com.sun.nio.zipfs.ZipPath arg0, java.nio.file.DirectoryStream.Filter<? super java.nio.file.Path> " + "arg1) throws java.io.IOException { /* compiled code */ }\n" + "\n" + " public synchronized java.util.Iterator<java.nio.file.Path> iterator() { /* compiled code */ }\n" + "\n" + " public synchronized void close() throws java.io.IOException { /* compiled code */ }\n" + "\n" + "}"); } @Test public void testGenericInterface() throws Exception { IType interfaceType = project.findType("com.google.gwt.user.client.rpc.AsyncCallback"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source) .contains( "public interface AsyncCallback<T> {\n" + "\n" + " public void onFailure(java.lang.Throwable arg0);\n" + "\n" + " public void onSuccess(T arg0);\n" + "\n" + "}"); } @Test public void testAnnotation() throws Exception { IType interfaceType = project.findType("com.google.gwt.core.client.SingleJsoImpl"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source).contains("public @interface SingleJsoImpl {\n"); } @Test public void testAnnotationMethod() throws Exception { IType interfaceType = project.findType("com.google.gwt.core.client.SingleJsoImpl"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source) .contains( " public java.lang.Class<? extends com.google.gwt.core.client.JavaScriptObject> value();\n"); } @Test public void testAnnotationsOnAnnotation() throws Exception { IType interfaceType = project.findType("com.google.gwt.core.client.SingleJsoImpl"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source) .contains( "@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)\n") .contains("@java.lang.annotation.Target(value=java.lang.annotation.ElementType.TYPE)\n"); } @Test public void testAnnotationsOnMethod() throws Exception { IType interfaceType = project.findType("java.util.Date"); String source = new SourcesFromBytecodeGenerator().generateSource(interfaceType); assertThat(source).contains("@java.lang.Deprecated\n public Date(java.lang.String arg0)"); } }
epl-1.0
donghongwang/BookingSystem
src/com/bs/bean/P_T.java
1426
package com.bs.bean; import java.util.Date; public class P_T implements java.io.Serializable{ private static final long serialVersionUID = -4888836126783955019L; private int pid; private int tid; private int state; private Date jointime; public P_T(){} public P_T(int pid,int tid,int state,Date jointime) { this.pid=pid; this.tid=tid; this.state=state; this.jointime=jointime; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public int getState() { return state; } public void setState(int state) { this.state = state; } public Date getJointime() { return jointime; } public void setJointime(Date jointime) { this.jointime = jointime; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; P_T other = (P_T) obj; if(pid!=other.pid) return false; if(tid!=other.tid) return false; return true; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (new Integer(this.pid)).hashCode(); result = prime * result + (new Integer(this.tid)).hashCode(); return result; } }
epl-1.0
cscheid/lux
src/shade/scale/geo/latlong_to_mercator.js
148
Shade.Scale.Geo.latlongToMercator = Shade(function(lat, lon) { lat = lat.div(2).add(Math.PI/4).tan().log(); return Shade.vec(lon, lat); });
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/ui/wizards/NewAnnotationWizardPage.java
17515
/******************************************************************************* * Copyright (c) 2004, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Harald Albers <eclipse@albersweb.de> - [type wizards] New Annotation dialog could allow generating @Documented, @Retention and @Target - https://bugs.eclipse.org/339292 *******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; 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.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.PlatformUI; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; /** * Wizard page to create a new annotation type. * <p> * Note: This class is not intended to be subclassed, but clients can instantiate. * To implement a different kind of a new annotation wizard page, extend <code>NewTypeWizardPage</code>. * </p> * * @since 3.1 * * @noextend This class is not intended to be subclassed by clients. */ public class NewAnnotationWizardPage extends NewTypeWizardPage { private final static String PAGE_NAME= "NewAnnotationWizardPage"; //$NON-NLS-1$ private final static int TYPE = NewTypeWizardPage.ANNOTATION_TYPE; private final static String SETTINGS_ADD_DOCUMENTED= "add_documented"; //$NON-NLS-1$ private AddRetentionControl fRetentionSelection; private AddTargetControl fTargetSelection; private SelectionButtonDialogField fDocumentedSelection; /** * Create a new <code>NewAnnotationWizardPage</code> */ public NewAnnotationWizardPage() { super(TYPE, PAGE_NAME); setTitle(NewWizardMessages.NewAnnotationWizardPage_title); setDescription(NewWizardMessages.NewAnnotationWizardPage_description); fRetentionSelection= new AddRetentionControl(); fTargetSelection= new AddTargetControl(); fDocumentedSelection= new SelectionButtonDialogField(SWT.CHECK); fDocumentedSelection.setLabelText(NewWizardMessages.NewAnnotationWizardPage_add_documented); } // -------- Initialization --------- /** * The wizard owning this page is responsible for calling this method with the * current selection. The selection is used to initialize the fields of the wizard * page. * * @param selection used to initialize the fields */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); initAnnotationPage(); doStatusUpdate(); } // ------ validation -------- private void initAnnotationPage() { IDialogSettings dialogSettings= getDialogSettings(); IDialogSettings section= null; if (dialogSettings != null) { section= dialogSettings.getSection(PAGE_NAME); } restoreSettings(section); } private void restoreSettings(IDialogSettings section) { if (section != null) { boolean addDocumented= section.getBoolean(SETTINGS_ADD_DOCUMENTED); fDocumentedSelection.setSelection(addDocumented); } fRetentionSelection.init(section); fTargetSelection.init(section); } @Override protected IStatus containerChanged() { IStatus status= super.containerChanged(); if (status.isOK()) { IJavaProject javaProject= getJavaProject(); fRetentionSelection.setProject(javaProject); fTargetSelection.setProject(javaProject); } return status; } private void doStatusUpdate() { // all used component status IStatus[] status= new IStatus[] { fContainerStatus, isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, fTypeNameStatus, fModifierStatus, }; // the mode severe status will be displayed and the OK button enabled/disabled. updateStatus(status); } /* * @see NewContainerWizardPage#handleFieldChanged */ @Override protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); doStatusUpdate(); } // ------ UI -------- /** * Control for adding an annotation with enum-based values to the generated source code. * * @param <A> the class to add as an annotation * @param <E> the enum class that supplies values for the annotation */ private abstract static class AddAnnotationControl<A, E extends Enum<E>> { private static final String SETTINGS_ENABLED= "enabled"; //$NON-NLS-1$ private static final String SETTINGS_SELECTED_ENUMS= "selectedEnums"; //$NON-NLS-1$ /** * A checkbox for enabling the addition of this annotation. */ protected final SelectionButtonDialogField fEnableButton; /** * A group of buttons for choosing between the available enum values for the annotation. */ protected final SelectionButtonDialogFieldGroup fEnumButtons; /** * The annotation whose addition this control represents. */ private final Class<A> fAnnotationClass; /** * The enum from which one or more constants should be added as values to the annotation. */ private final Class<E> fEnumClass; private boolean fControlsAreCreated; /** * The Java project in which the annotation is going to be created. The availability of enum * constants may depend on the project, e.g. its source level. */ protected IJavaProject fJavaProject; public AddAnnotationControl(int style, String enableLabel, Class<A> annotationClass, Class<E> enumClass, int nColumns) { fAnnotationClass= annotationClass; fEnumClass= enumClass; String[] enumLabels= toStringArray(enumClass); fEnableButton= new SelectionButtonDialogField(SWT.CHECK); fEnableButton.setLabelText(enableLabel); fEnumButtons= new SelectionButtonDialogFieldGroup(style, enumLabels, nColumns); fEnableButton.setDialogFieldListener(new IDialogFieldListener() { @Override public void dialogFieldChanged(DialogField field) { fEnumButtons.setEnabled(fEnableButton.isSelected()); } }); } private String[] toStringArray(Class<E> enumClass) { E[] enums= enumClass.getEnumConstants(); String[] strings= new String[enums.length]; for (Enum<?> en : enums) { strings[en.ordinal()]= labelFor(en); } return strings; } protected String labelFor(Enum<?> en) { String name= en.name(); String first= name.substring(0, 1).toUpperCase(); String rest= name.substring(1).toLowerCase().replace('_', ' '); return first + rest; } public void init(IDialogSettings settings) { boolean enabled= false; String[] selectedEnums= defaultSelectedEnums(); if (settings != null) { IDialogSettings section= settings.getSection(dialogSettingsSectionName()); if (section != null) { enabled= section.getBoolean(SETTINGS_ENABLED); selectedEnums= section.getArray(SETTINGS_SELECTED_ENUMS); } } applyInitialSettings(enabled, selectedEnums); } protected String[] defaultSelectedEnums() { return new String[] {}; } private void applyInitialSettings(boolean enabled, String[] selectedEnumsAsStrings) { fEnableButton.setSelection(enabled); fEnumButtons.setEnabled(enabled); fEnumButtons.setSelection(0, false); for (String string : selectedEnumsAsStrings) { E en= Enum.valueOf(fEnumClass, string); fEnumButtons.setSelection(en.ordinal(), true); } } /** * @return the section name under which this control persists its settings. */ abstract protected String dialogSettingsSectionName(); public void persistSettings(IDialogSettings settings) { String sectionName= dialogSettingsSectionName(); IDialogSettings section= settings.getSection(sectionName); if (section == null) { section= settings.addNewSection(sectionName); } section.put(SETTINGS_ENABLED, isEnabled()); section.put(SETTINGS_SELECTED_ENUMS, selectedEnumsAsStrings()); } private String[] selectedEnumsAsStrings() { List<String> resultList= new ArrayList<>(); for (E en : allEnums()) { if (isSelected(en)) { resultList.add(en.name()); } } String[] resultArray= resultList.toArray(new String[] {}); return resultArray; } private E[] allEnums() { return fEnumClass.getEnumConstants(); } public void doFillIntoGrid(Composite parent, int nColumns) { Button button= fEnableButton.getSelectionButton(parent); GridData gdButton= new GridData(GridData.VERTICAL_ALIGN_BEGINNING); button.setLayoutData(gdButton); Composite buttonsGroup= fEnumButtons.getSelectionButtonsGroup(parent); GridData gdButtonsGroup= new GridData(); gdButtonsGroup.horizontalSpan= nColumns - 1; buttonsGroup.setLayoutData(gdButtonsGroup); fControlsAreCreated= true; updateButtons(); } /** * Sets or changes the target <code>IJavaProject</code>. The availability of enum constants * may depend on the project, e.g. its source level. * * @param javaProject the new Java project in which the annotation will be created. */ public void setProject(IJavaProject javaProject) { fJavaProject= javaProject; updateButtons(); } private void updateButtons() { if (fControlsAreCreated && fJavaProject != null) { updateAvailableButtons(); } } protected void updateAvailableButtons() { // after changing the project, the availability of buttons might change. } /** * @return <code>true</code> if the control is enabled, else <code>false</code> */ public boolean isEnabled() { return fEnableButton.isSelected(); } public void addAnnotation(IType newType, ImportsManager imports, String lineDelimiter) throws JavaModelException { if (isEnabled()) { List<E> selectedEnums= availableSelectedEnums(); if (selectedEnums.size() > 0) { String annotation= createAnnotationAndImports(selectedEnums, imports, lineDelimiter); int start= newType.getSourceRange().getOffset(); IBuffer buffer= newType.getCompilationUnit().getBuffer(); buffer.replace(start, 0, annotation); } } } private List<E> availableSelectedEnums() { List<E> resultList= new ArrayList<>(); for (E en : allEnums()) { if (isEnabled(en) && isSelected(en)) { resultList.add(en); } } return resultList; } private boolean isEnabled(E en) { return fEnumButtons.isEnabled(en.ordinal()); } private boolean isSelected(E en) { return fEnumButtons.isSelected(en.ordinal()); } private String createAnnotationAndImports(List<E> selectedEnums, ImportsManager imports, String lineDelimiter) { StringBuffer buffer= new StringBuffer(); String annotationTypeName= imports.addImport(fAnnotationClass.getName()); buffer.append("@"); //$NON-NLS-1$ buffer.append(annotationTypeName); buffer.append("("); //$NON-NLS-1$ if (selectedEnums.size() > 1) { buffer.append("{"); //$NON-NLS-1$ } for (Enum<?> en : selectedEnums) { String enumTypeName= imports.addStaticImport(en.getClass().getName(), en.name(), true); buffer.append(enumTypeName); buffer.append(", "); //$NON-NLS-1$ } buffer.delete(buffer.length() - 2, buffer.length()); if (selectedEnums.size() > 1) { buffer.append("}"); //$NON-NLS-1$ } buffer.append(")"); //$NON-NLS-1$ buffer.append(lineDelimiter); return buffer.toString(); } } /** * Control for adding <code>@Retention(RetentionPolicy)</code> */ private static class AddRetentionControl extends AddAnnotationControl<Retention, RetentionPolicy> { private static final String SETTINGS_SECTION_NAME= "AddRetention"; //$NON-NLS-1$ private static final String[] MNEMONICS= { "S", "l", "n" }; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ public AddRetentionControl() { super(SWT.RADIO, NewWizardMessages.NewAnnotationWizardPage_add_retention, Retention.class, RetentionPolicy.class, 3); } @Override protected String labelFor(Enum<?> en) { String label= super.labelFor(en); String mnemonic= MNEMONICS[en.ordinal()]; return label.replaceFirst(mnemonic, "&" + mnemonic); //$NON-NLS-1$ } @Override protected String dialogSettingsSectionName() { return SETTINGS_SECTION_NAME; } @Override protected String[] defaultSelectedEnums() { return new String[] { RetentionPolicy.CLASS.name() }; } } /** * Control for adding <code>@Target([ElementType])</code> */ private static class AddTargetControl extends AddAnnotationControl<Target, ElementType> { private static final String SETTINGS_SECTION_NAME= "AddTarget"; //$NON-NLS-1$ /** * Ordinals of enum values that were added in Java 8. As we are still on Java 7 here, they * cannot be expressed as literals. */ private static final int[] fEnumValuesSinceJava8= new int[] { 8, 9 }; public AddTargetControl() { super(SWT.CHECK, NewWizardMessages.NewAnnotationWizardPage_add_target, Target.class, ElementType.class, 3); } @Override protected void updateAvailableButtons() { boolean isJava8orHigher= JavaModelUtil.is18OrHigher(fJavaProject); for (int index : fEnumValuesSinceJava8) { fEnumButtons.enableSelectionButton(index, isJava8orHigher); } } @Override protected String dialogSettingsSectionName() { return SETTINGS_SECTION_NAME; } } /* * @see WizardPage#createControl */ @Override public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createEnclosingTypeControls(composite, nColumns); createSeparator(composite, nColumns); createTypeNameControls(composite, nColumns); createModifierControls(composite, nColumns); createSeparator(composite, nColumns); createAddAnnotationControls(composite, nColumns); createSeparator(composite, nColumns); createCommentControls(composite, nColumns); enableCommentControl(true); setControl(composite); Dialog.applyDialogFont(composite); PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_ANNOTATION_WIZARD_PAGE); } private void createAddAnnotationControls(Composite composite, int nColumns) { fRetentionSelection.doFillIntoGrid(composite, nColumns); DialogField.createEmptySpace(composite, nColumns); fTargetSelection.doFillIntoGrid(composite, nColumns); DialogField.createEmptySpace(composite, nColumns); fDocumentedSelection.doFillIntoGrid(composite, nColumns); } /* * @see WizardPage#becomesVisible */ @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { setFocus(); } } // ------ code generation -------- @Override protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { String lineDelimiter= StubUtility.getLineDelimiterUsed(newType.getJavaProject()); fTargetSelection.addAnnotation(newType, imports, lineDelimiter); fRetentionSelection.addAnnotation(newType, imports, lineDelimiter); addDocumentedAnnotation(newType, imports, lineDelimiter); persistSettings(); } private void addDocumentedAnnotation(IType newType, ImportsManager imports, String lineDelimiter) throws JavaModelException { if (fDocumentedSelection.isSelected()) { String typeName= imports.addImport(Documented.class.getName()); int start= newType.getSourceRange().getOffset(); IBuffer buffer= newType.getCompilationUnit().getBuffer(); buffer.replace(start, 0, "@" + typeName + lineDelimiter); //$NON-NLS-1$ } } private void persistSettings() { IDialogSettings dialogSettings= getDialogSettings(); if (dialogSettings != null) { IDialogSettings section= dialogSettings.getSection(PAGE_NAME); if (section == null) { section= dialogSettings.addNewSection(PAGE_NAME); } section.put(SETTINGS_ADD_DOCUMENTED, fDocumentedSelection.isSelected()); fRetentionSelection.persistSettings(section); fTargetSelection.persistSettings(section); } } }
epl-1.0
prm-svm/kura
kura/DenaliWebAutomation/src/test/java/com/eurotech/denali/view/SettingsView.java
2203
package com.eurotech.denali.view; import com.eurotech.denali.driver.processor.WebDriverActions; import com.eurotech.denali.objectrepo.BrowserRepository; public class SettingsView extends WebDriverActions { public void selectSettingView() { click(BrowserRepository.SETTINGS); } public void clickApply() { click(BrowserRepository.SETTINGS_APPLY); } public boolean isApplyButtonEnabled() { return isButtonEnabled(BrowserRepository.SETTINGS_APPLY); } public void selectAdminPasswordTab() { click(BrowserRepository.SETTINGS_ADMIN_PASSWORD); } public void setCurrentAdminPassword(String password) { sendKeys(BrowserRepository.SETTINGS_CURRENT_PASSWORD, password); } public boolean isCurrentAdminPasswordEnabled() { return isTextBoxEnabled(BrowserRepository.SETTINGS_CURRENT_PASSWORD); } public void setNewPassword(String password) { sendKeys(BrowserRepository.SETTINGS_NEW_PASSWORD, password); } public boolean isNewPasswordEnabled() { return isTextBoxEnabled(BrowserRepository.SETTINGS_NEW_PASSWORD); } public void setConfirmPassword(String password) { sendKeys(BrowserRepository.SETTINGS_CONFIRM_PASSWORD, password); } public boolean isConfirmPasswordEnabled() { return isTextBoxEnabled(BrowserRepository.SETTINGS_CONFIRM_PASSWORD); } public boolean isConfirmationPresent() { boolean status = false; int i=0; while(i++<50) { status = isDisplayed(BrowserRepository.SETTING_CONFIRMATION); if(status ==true) break; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } return status; } public boolean isSnapshotRefreshEnabled() { return isButtonEnabled(BrowserRepository.SETTINGS_SNAPSHOT_REFRESH_BUTTON); } public boolean isSnapshotDownloadEnabled() { return isButtonEnabled(BrowserRepository.SETTINGS_SNAPSHOT_DOWNLOAD_BUTTON); } public boolean isSnapshotRollbackEnabled() { return isButtonEnabled(BrowserRepository.SETTINGS_SNAPSHOT_ROLLBACK_BUTTON); } public boolean isSnapshotApplyEnabled() { return isButtonEnabled(BrowserRepository.SETTINGS_SNAPSHOT_APPLY_BUTTON); } }
epl-1.0
gorkem/js-parser-benchmarks
src/main/java/org/jboss/tools/benchmark/parsers/AcornWithNodeJS.java
754
package org.jboss.tools.benchmark.parsers; import java.io.IOException; import org.jboss.tools.benchmark.parsers.acorn.AcornParser; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; @State(Scope.Thread) public class AcornWithNodeJS extends TestBase{ private final AcornParser parser = new AcornParser(); @Override public void testDelegate(final String content) { try { final String result = parser.parse(content); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args){ AcornWithNodeJS self = new AcornWithNodeJS(); try { self.testAngular125(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
epl-1.0
HenryVegaAyala/DEV_GIT
HolaMundo/src/prueba2.java
149
public class prueba2 { public static void main(String[] argumentos) { for(int i=500;i<600;i+=2){ System.out.println(i); } } }
epl-1.0
ugilio/keen
it.cnr.istc.keen.epsl/src/it/cnr/istc/keen/epsl/utils/ProjectUtils.java
2995
/* * Copyright (c) 2016-2017 PST (http://istc.cnr.it/group/pst). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Giulio Bernardi */ package it.cnr.istc.keen.epsl.utils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; public class ProjectUtils { public ProjectUtils() { // TODO Auto-generated constructor stub } private IResource getResource(IStructuredSelection ss) { Object element = ss.getFirstElement(); if (element instanceof IResource) return (IResource) element; if (!(element instanceof IAdaptable)) return null; IAdaptable adaptable = (IAdaptable)element; Object adapter = adaptable.getAdapter(IResource.class); return (IResource) adapter; } private IFile getFile(IStructuredSelection ss) { Object element = ss.getFirstElement(); if (element instanceof IFile) return (IFile) element; if (!(element instanceof IAdaptable)) return null; IAdaptable adaptable = (IAdaptable)element; Object adapter = adaptable.getAdapter(IFile.class); return (IFile) adapter; } private IFile getFile(IEditorInput ei) { if (ei != null) { if (ei instanceof IFileEditorInput) return ((IFileEditorInput)ei).getFile(); } return null; } public IFile getCurrentFile() { Object o = getCurrentObject(); if (o instanceof IFile) return (IFile) o; return null; } public IProject getCurrentProject() { Object o = getCurrentObject(); if (o instanceof IResource) return ((IResource) o).getProject(); return null; } private Object getCurrentObject() { Object rc[] = new Object[1]; IWorkbench wb = PlatformUI.getWorkbench(); wb.getDisplay().syncExec(new Runnable() { @Override public void run() { IEditorPart part = wb.getActiveWorkbenchWindow().getActivePage().getActiveEditor(); Object theFile=getFile(part.getEditorInput()); ISelection sel = wb.getActiveWorkbenchWindow().getActivePage().getSelection(); boolean validSelection = sel instanceof IStructuredSelection && !sel.isEmpty(); if (validSelection) rc[0]=getFile((IStructuredSelection)sel); if (rc[0] == null && theFile != null) rc[0] = theFile; if (validSelection && rc[0]==null) rc[0]=getResource((IStructuredSelection)sel); } }); return rc[0]; } }
epl-1.0
terry1013/Alesia
dev/utils/FadingPanel.java
2210
/******************************************************************************* * Copyright (C) 2017 terry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * terry - initial API and implementation ******************************************************************************/ package dev.utils; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.Timer; public class FadingPanel extends JComponent implements ActionListener { private Timer ticker = null; private int alpha = 0; private int step; private FadeListener fadeListener; public FadingPanel(FadeListener fadeListener) { this.fadeListener = fadeListener; } public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { if (ticker != null) { ticker.stop(); } alpha = 0; step = 25; ticker = new Timer(50, this); ticker.start(); } else { if (ticker != null) { ticker.stop(); ticker = null; } } } protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(new Color(255, 255, 255, alpha)); Rectangle clip = g.getClipBounds(); g.fillRect(clip.x, clip.y, clip.width, clip.height); } public void switchDirection() { step = -step; ticker.start(); } public void actionPerformed(ActionEvent e) { alpha += step; if (alpha >= 255) { alpha = 255; ticker.stop(); fadeListener.fadeOutFinished(); } else if (alpha < 0) { alpha = 0; ticker.stop(); fadeListener.fadeInFinished(); } repaint(); } }
epl-1.0
junli007/vone
WebRoot/dep/angular/i18n/angular-locale_sah-ru.js
3751
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u042d\u0418", "\u042d\u041a" ], "DAY": [ "\u0411\u0430\u0441\u043a\u044b\u04bb\u044b\u0430\u043d\u043d\u044c\u0430", "\u0411\u044d\u043d\u0438\u0434\u0438\u044d\u043b\u0438\u043d\u043d\u044c\u0438\u043a", "\u041e\u043f\u0442\u0443\u043e\u0440\u0443\u043d\u043d\u044c\u0443\u043a", "\u0421\u044d\u0440\u044d\u0434\u044d", "\u0427\u044d\u043f\u043f\u0438\u044d\u0440", "\u0411\u044d\u044d\u0442\u0438\u04a5\u0441\u044d", "\u0421\u0443\u0431\u0443\u043e\u0442\u0430" ], "MONTH": [ "\u0422\u043e\u0445\u0441\u0443\u043d\u043d\u044c\u0443", "\u041e\u043b\u0443\u043d\u043d\u044c\u0443", "\u041a\u0443\u043b\u0443\u043d \u0442\u0443\u0442\u0430\u0440", "\u041c\u0443\u0443\u0441 \u0443\u0441\u0442\u0430\u0440", "\u042b\u0430\u043c \u044b\u0439\u044b\u043d", "\u0411\u044d\u0441 \u044b\u0439\u044b\u043d", "\u041e\u0442 \u044b\u0439\u044b\u043d", "\u0410\u0442\u044b\u0440\u0434\u044c\u044b\u0445 \u044b\u0439\u044b\u043d", "\u0411\u0430\u043b\u0430\u0495\u0430\u043d \u044b\u0439\u044b\u043d", "\u0410\u043b\u0442\u044b\u043d\u043d\u044c\u044b", "\u0421\u044d\u0442\u0438\u043d\u043d\u044c\u0438", "\u0410\u0445\u0441\u044b\u043d\u043d\u044c\u044b" ], "SHORTDAY": [ "\u0411\u0441", "\u0411\u043d", "\u041e\u043f", "\u0421\u044d", "\u0427\u043f", "\u0411\u044d", "\u0421\u0431" ], "SHORTMONTH": [ "\u0422\u043e\u0445\u0441", "\u041e\u043b\u0443\u043d", "\u041a\u043b\u043d_\u0442\u0442\u0440", "\u041c\u0443\u0441_\u0443\u0441\u0442", "\u042b\u0430\u043c_\u0439\u043d", "\u0411\u044d\u0441_\u0439\u043d", "\u041e\u0442_\u0439\u043d", "\u0410\u0442\u0440\u0434\u044c_\u0439\u043d", "\u0411\u043b\u0495\u043d_\u0439\u043d", "\u0410\u043b\u0442", "\u0421\u044d\u0442", "\u0410\u0445\u0441" ], "fullDate": "y '\u0441\u044b\u043b' MMMM d '\u043a\u04af\u043d\u044d', EEEE", "longDate": "y, MMMM d", "medium": "y, MMM d HH:mm:ss", "mediumDate": "y, MMM d", "mediumTime": "HH:mm:ss", "short": "yy/M/d HH:mm", "shortDate": "yy/M/d", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u0440\u0443\u0431.", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "sah-ru", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
epl-1.0
bradsdavis/cxml-api
src/main/java/org/cxml/v12024/DsXPath.java
1244
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.08.05 at 11:46:51 PM EDT // package org.cxml.v12024; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "ds:XPath") public class DsXPath { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getvalue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setvalue(String value) { this.value = value; } }
epl-1.0
lhillah/pnmlframework
pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/hlcorestructure/PNType.java
7218
/** * Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités, Univ. Paris 06 - CNRS UMR 7606 (LIP6) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Project leader / Initial Contributor: * Lom Messan Hillah - <lom-messan.hillah@lip6.fr> * * Contributors: * ${ocontributors} - <$oemails}> * * Mailing list: * lom-messan.hillah@lip6.fr */ /** * (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6/MoVe) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Lom HILLAH (LIP6) - Initial models and implementation * Rachid Alahyane (UPMC) - Infrastructure and continuous integration * Bastien Bouzerau (UPMC) - Architecture * Guillaume Giffo (UPMC) - Code generation refactoring, High-level API */ package fr.lip6.move.pnml.hlpn.hlcorestructure; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>PN Type</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see fr.lip6.move.pnml.hlpn.hlcorestructure.HlcorestructurePackage#getPNType() * @model * @generated */ public enum PNType implements Enumerator { /** * The '<em><b>HLPN</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #HLPN_VALUE * @generated * @ordered */ HLPN(3, "HLPN", "http://www.pnml.org/version-2009/grammar/highlevelnet"), /** * The '<em><b>COREMODEL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #COREMODEL_VALUE * @generated * @ordered */ COREMODEL(0, "COREMODEL", "http://www.pnml.org/version-2009/grammar/pnmlcoremodel"), /** * The '<em><b>PTNET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PTNET_VALUE * @generated * @ordered */ PTNET(1, "PTNET", "http://www.pnml.org/version-2009/grammar/ptnet"), /** * The '<em><b>SYMNET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #SYMNET_VALUE * @generated * @ordered */ SYMNET(2, "SYMNET", "http://www.pnml.org/version-2009/grammar/snnet"); /** * The '<em><b>HLPN</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>HLPN</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #HLPN * @model literal="http://www.pnml.org/version-2009/grammar/highlevelnet" * @generated * @ordered */ public static final int HLPN_VALUE = 3; /** * The '<em><b>COREMODEL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>COREMODEL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #COREMODEL * @model literal="http://www.pnml.org/version-2009/grammar/pnmlcoremodel" * @generated * @ordered */ public static final int COREMODEL_VALUE = 0; /** * The '<em><b>PTNET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>PTNET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PTNET * @model literal="http://www.pnml.org/version-2009/grammar/ptnet" * @generated * @ordered */ public static final int PTNET_VALUE = 1; /** * The '<em><b>SYMNET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>SYMNET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #SYMNET * @model literal="http://www.pnml.org/version-2009/grammar/snnet" * @generated * @ordered */ public static final int SYMNET_VALUE = 2; /** * An array of all the '<em><b>PN Type</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final PNType[] VALUES_ARRAY = new PNType[] { HLPN, COREMODEL, PTNET, SYMNET, }; /** * A public read-only list of all the '<em><b>PN Type</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<PNType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>PN Type</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static PNType get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { PNType result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>PN Type</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static PNType getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { PNType result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>PN Type</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static PNType get(int value) { switch (value) { case HLPN_VALUE: return HLPN; case COREMODEL_VALUE: return COREMODEL; case PTNET_VALUE: return PTNET; case SYMNET_VALUE: return SYMNET; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private PNType(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //PNType
epl-1.0
aptana/Pydev
tests/org.python.pydev.core.tests/src/org/python/pydev/core/docutils/ParsingUtilsTest.java
19058
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Created on Mar 14, 2006 */ package org.python.pydev.core.docutils; import java.util.Iterator; import junit.framework.TestCase; import org.eclipse.jface.text.Document; import org.python.pydev.shared_core.string.FastStringBuffer; public class ParsingUtilsTest extends TestCase { public static void main(String[] args) { try { ParsingUtilsTest test = new ParsingUtilsTest(); test.setUp(); test.testFindNextChar(); test.tearDown(); junit.textui.TestRunner.run(ParsingUtilsTest.class); } catch (Throwable e) { e.printStackTrace(); } } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testIsInCommOrStr() { String str = "" + "#comm1\n" + "'str'\n" + "pass\n" + ""; assertEquals(ParsingUtils.PY_COMMENT, ParsingUtils.getContentType(str, 2)); assertEquals(ParsingUtils.PY_SINGLELINE_STRING1, ParsingUtils.getContentType(str, 10)); assertEquals(ParsingUtils.PY_DEFAULT, ParsingUtils.getContentType(str, 17)); } public void testIsInCommOrStr2() { String str = "" + "'''\n" + "foo\n" + "'''" + ""; assertEquals(ParsingUtils.PY_DEFAULT, ParsingUtils.getContentType(str, str.length())); assertEquals(ParsingUtils.PY_DEFAULT, ParsingUtils.getContentType(str, str.length() - 1)); assertEquals(ParsingUtils.PY_MULTILINE_STRING1, ParsingUtils.getContentType(str, str.length() - 2)); } public void testEatComments() { String str = "" + "#comm1\n" + "pass\n" + ""; ParsingUtils parsingUtils = ParsingUtils.create(str); int i = parsingUtils.eatComments(null, 0); assertEquals('\n', parsingUtils.charAt(i)); } public void testEatLiterals() throws SyntaxErrorException { String str = "" + "'''\n" + "pass\n" + "'''" + "w" + ""; ParsingUtils parsingUtils = ParsingUtils.create(str); int i = parsingUtils.eatLiterals(null, 0); assertEquals(11, i); assertEquals('\'', parsingUtils.charAt(i)); } public void testInvalidSyntax() { String str = "" + "'" + //not properly closed ""; ParsingUtils parsingUtils = ParsingUtils.create(str, true); try { parsingUtils.eatLiterals(null, 0); fail("Expected invalid code."); } catch (SyntaxErrorException e) { //expected } str = "" + "'''" + //not properly closed ""; parsingUtils = ParsingUtils.create(str, true); try { parsingUtils.eatLiterals(null, 0); fail("Expected invalid code."); } catch (SyntaxErrorException e) { //expected } str = "" + "(" + //not properly closed ""; parsingUtils = ParsingUtils.create(str, true); try { parsingUtils.eatPar(0, null); fail("Expected invalid code."); } catch (SyntaxErrorException e) { //expected } } public void testEatWhitespaces() { String str = "" + " #comm\n" + "pass\n" + ""; ParsingUtils parsingUtils = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); int i = parsingUtils.eatWhitespaces(buf, 0); assertEquals(3, i); assertEquals(" ", buf.toString()); assertEquals(' ', parsingUtils.charAt(i)); } public void testEatWhitespaces2() { String str = "" + " "; ParsingUtils parsingUtils = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); int i = parsingUtils.eatWhitespaces(buf, 0); assertEquals(" ", buf.toString()); assertEquals(' ', parsingUtils.charAt(i)); assertEquals(3, i); } public void testIterator() throws Exception { String str = "" + "#c\n" + "'s'\n" + "pass\n" + ""; Document d = new Document(str); Iterator<String> it = ParsingUtils.getNoLiteralsOrCommentsIterator(d); assertEquals("\n", it.next()); assertEquals(true, it.hasNext()); assertEquals("\n", it.next()); assertEquals(true, it.hasNext()); assertEquals("pass\n", it.next()); assertEquals(false, it.hasNext()); } public void testGetFlattenedLine() throws Exception { String str = "" + "line #c\n" + "start =\\\n" + "10 \\\n" + "30\n" + "call(\n" + " ttt,\n" + ")\n"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(6, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals('c', str.charAt(6)); assertEquals("line ", buf.toString()); parsing.getFullFlattenedLine(1, buf.clear()); assertEquals("ine ", buf.toString()); assertEquals(23, parsing.getFullFlattenedLine(8, buf.clear())); assertEquals('0', str.charAt(23)); assertEquals("start =10 30", buf.toString()); assertEquals(39, parsing.getFullFlattenedLine(25, buf.clear())); assertEquals("call", buf.toString()); assertEquals(')', str.charAt(39)); } public void testGetFlattenedLine2() throws Exception { String str = "" + "line = '''\n" + "bla bla bla''' = xxy\n" + "what"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(30, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals('y', str.charAt(30)); assertEquals("line = = xxy", buf.toString()); } public void testGetFlattenedLine3() throws Exception { String str = "" + "a = c(\r\n" + "a)\r\n" + "b = 20\r\n"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(9, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals("a = c", buf.toString()); assertEquals(')', str.charAt(9)); } public void testGetFlattenedLine4() throws Exception { String str = "" + "a = c(\r" + "a)\r" + "b = 20\r"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(8, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals("a = c", buf.toString()); assertEquals(')', str.charAt(8)); } public void testGetFlattenedLine5() throws Exception { String str = "" + "a = c(\n" + "a)\n" + //char 8 == ) "b = 20\n"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(')', str.charAt(8)); assertEquals(8, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals("a = c", buf.toString()); } public void testGetFlattenedLine6() throws Exception { String str = "" + "a = '''" + "a)\n" + "'''\n" + "b = 10"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(12, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals("a = ", buf.toString()); assertEquals('\'', str.charAt(12)); } public void testGetFlattenedLine7() throws Exception { String str = "" + "a = '''" + "a)\n" + "'''"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(12, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals("a = ", buf.toString()); assertEquals('\'', str.charAt(12)); } public void testGetFlattenedLine8() throws Exception { String str = "" + "a = '''" + "a)\n" + "'''\\"; ParsingUtils parsing = ParsingUtils.create(str); FastStringBuffer buf = new FastStringBuffer(); assertEquals(13, parsing.getFullFlattenedLine(0, buf.clear())); assertEquals("a = ", buf.toString()); assertEquals('\\', str.charAt(13)); } public void testIterator2() throws Exception { String str = "" + "#c\n" + "'s'" + ""; Document d = new Document(str); PyDocIterator it = (PyDocIterator) ParsingUtils.getNoLiteralsOrCommentsIterator(d); assertEquals(-1, it.getLastReturnedLine()); assertEquals("\n", it.next()); assertEquals(0, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("", it.next()); assertEquals(1, it.getLastReturnedLine()); assertEquals(false, it.hasNext()); } public void testIterator3() throws Exception { String str = "" + "#c"; Document d = new Document(str); PyDocIterator it = (PyDocIterator) ParsingUtils.getNoLiteralsOrCommentsIterator(d); assertEquals(-1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("", it.next()); assertEquals(0, it.getLastReturnedLine()); assertEquals(false, it.hasNext()); } public void testIterator5() throws Exception { String str = "" + "class Foo:\n" + " '''\n" + " \"\n" + " b\n" + " '''a\n" + " pass\n" + "\n"; Document d = new Document(str); PyDocIterator it = new PyDocIterator(d, false, true, true); assertEquals(-1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("class Foo:", it.next()); assertEquals(0, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals(" ", it.next()); assertEquals(1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals(" ", it.next()); assertEquals(2, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals(" ", it.next()); assertEquals(3, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals(" a", it.next()); assertEquals(4, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals(" pass", it.next()); assertEquals(5, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("", it.next()); assertEquals(6, it.getLastReturnedLine()); assertEquals(false, it.hasNext()); } public void testIterator7() throws Exception { String str = "" + "'''\n" + "\n" + "'''\n" + ""; Document d = new Document(str); PyDocIterator it = new PyDocIterator(d, false, true, true); assertEquals(" ", it.next()); assertEquals(0, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("", it.next()); assertEquals(1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals(" ", it.next()); assertEquals(2, it.getLastReturnedLine()); assertEquals(false, it.hasNext()); } public void testIterator6() throws Exception { String str = "" + "'''\n" + "\n" + "'''\n" + "class Foo:\n" + " '''\n" + " \"\n" + " b\n" + " '''a\n" + " pass\n" + " def m1(self):\n" + " '''\n" + " eueueueueue\n" + " '''\n" + "\n" + "\n"; Document d = new Document(str); PyDocIterator it = new PyDocIterator(d, false, true, true); assertEquals(-1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); for (int i = 0; i < d.getNumberOfLines() - 1; i++) { it.next(); assertEquals(i, it.getLastReturnedLine()); if (i == d.getNumberOfLines() - 2) { assertTrue("Failed at line:" + i, !it.hasNext()); } else { assertTrue("Failed at line:" + i, it.hasNext()); } } } public void testIterator4() throws Exception { String str = "" + "pass\r" + "foo\n" + "bla\r\n" + "what"; Document d = new Document(str); PyDocIterator it = (PyDocIterator) ParsingUtils.getNoLiteralsOrCommentsIterator(d); assertEquals(-1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("pass\r", it.next()); assertEquals(0, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("foo\n", it.next()); assertEquals(1, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("bla\r\n", it.next()); assertEquals(2, it.getLastReturnedLine()); assertEquals(true, it.hasNext()); assertEquals("what", it.next()); assertEquals(3, it.getLastReturnedLine()); assertEquals(false, it.hasNext()); } public void testMakeParseable() throws Exception { assertEquals("a=1\r\n", ParsingUtils.makePythonParseable("a=1", "\r\n")); String code = "class C:\n" + " pass"; String expected = "class C:\r\n" + " pass\r\n" + "\r\n"; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\r\n")); code = "class C:" + ""; expected = "class C:\r\n" + ""; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\r\n")); code = " def m1(self):" + ""; expected = " def m1(self):\r\n" + ""; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\r\n")); code = "class C:\n" + " pass\n" + "a = 10"; expected = "class C:\r\n" + " pass\r\n" + "\r\n" + "a = 10" + "\r\n"; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\r\n")); code = "class C:\n" + " \n" + " pass\n" + "a = 10"; expected = "class C:\r\n" + " pass\r\n" + "\r\n" + "a = 10" + "\r\n"; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\r\n")); code = "class AAA:\n" + " \n" + " \n" + " def m1(self):\n" + " self.bla = 10\n" + "\n" + ""; expected = "class AAA:\r\n" + " def m1(self):\r\n" + " self.bla = 10\r\n" + "\r\n"; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\r\n")); code = "a=10" + ""; expected = "\na=10\n" + ""; assertEquals(expected, ParsingUtils.makePythonParseable(code, "\n", new FastStringBuffer(" pass", 16))); } public void testEatLiteralBackwards() throws Exception { String str = "" + "'''\n" + "pass\n" + "'''" + "w" + ""; ParsingUtils parsingUtils = ParsingUtils.create(str, true); FastStringBuffer buf = new FastStringBuffer(); int i = parsingUtils.eatLiteralsBackwards(buf.clear(), 11); assertEquals(0, i); assertEquals('\'', parsingUtils.charAt(i)); assertEquals("'''\npass\n'''", buf.toString()); str = "" + "'ue'" + ""; parsingUtils = ParsingUtils.create(str, true); assertEquals(0, parsingUtils.eatLiteralsBackwards(buf.clear(), 3)); assertEquals("'ue'", buf.toString()); str = "" + "ue'" + ""; parsingUtils = ParsingUtils.create(str, true); try { parsingUtils.eatLiteralsBackwards(buf.clear(), 2); fail("Expecting syntax error"); } catch (SyntaxErrorException e) { //expected assertEquals("", buf.toString()); } str = "" + " ' \\' \\'ue'" + ""; parsingUtils = ParsingUtils.create(str, true); parsingUtils.eatLiteralsBackwards(buf.clear(), str.length() - 1); assertEquals("' \\' \\'ue'", buf.toString()); } public void testRemoveCommentsWhitespacesAndLiterals() throws Exception { FastStringBuffer buf = new FastStringBuffer(); buf.append("#c\n#f\n#c\n"); ParsingUtils.removeCommentsWhitespacesAndLiterals(buf, false, false); assertEquals(buf.toString(), ""); buf = new FastStringBuffer(); buf.append("#\n#\n#\n"); ParsingUtils.removeCommentsWhitespacesAndLiterals(buf, false, false); assertEquals(buf.toString(), ""); buf = new FastStringBuffer(); buf.append("#\n#f\n#\n"); ParsingUtils.removeCommentsWhitespacesAndLiterals(buf, false, false); assertEquals(buf.toString(), ""); } public void testFindNextChar() throws Exception { String s = "aaaaaa()"; ParsingUtils parsingUtils = ParsingUtils.create(s); assertEquals(6, parsingUtils.findNextChar(0, '(')); assertEquals(7, parsingUtils.eatPar(6, null)); } }
epl-1.0
santoslab/aadl-translator
aadl-translator/src/main/java/edu/ksu/cis/projects/mdcf/aadltranslator/model/hazardanalysis/DetectionModel.java
635
package edu.ksu.cis.projects.mdcf.aadltranslator.model.hazardanalysis; import edu.ksu.cis.projects.mdcf.aadltranslator.model.ModelUtil.DetectionApproach; public abstract class DetectionModel { protected DetectionApproach approach; protected String explanation; protected String name; public DetectionModel(String explanation, String name) { this.explanation = explanation; this.name = name; } public String getExplanation() { return explanation; } public String getName() { return name; } public abstract DetectionApproach getApproach(); public String getApproachStr() { return approach.toString(); } }
epl-1.0
bradsdavis/cxml-api
src/main/java/org/cxml/fulfill/Place.java
2588
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.23 at 11:18:10 AM CEST // package org.cxml.fulfill; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "address" }) @XmlRootElement(name = "Place") public class Place { @XmlAttribute(name = "code") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String code; @XmlAttribute(name = "domain") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String domain; @XmlElement(name = "Address") protected Address address; /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the domain property. * * @return * possible object is * {@link String } * */ public String getDomain() { return domain; } /** * Sets the value of the domain property. * * @param value * allowed object is * {@link String } * */ public void setDomain(String value) { this.domain = value; } /** * Gets the value of the address property. * * @return * possible object is * {@link Address } * */ public Address getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link Address } * */ public void setAddress(Address value) { this.address = value; } }
epl-1.0
ribelo/eckersdorf
resources/public/js/out/re_frame/cofx.js
5873
// Compiled by ClojureScript 1.9.946 {} goog.provide('re_frame.cofx'); goog.require('cljs.core'); goog.require('re_frame.db'); goog.require('re_frame.interceptor'); goog.require('re_frame.registrar'); goog.require('re_frame.loggers'); re_frame.cofx.kind = new cljs.core.Keyword(null,"cofx","cofx",2013202907); if(cljs.core.truth_(re_frame.registrar.kinds.call(null,re_frame.cofx.kind))){ } else { throw (new Error("Assert failed: (re-frame.registrar/kinds kind)")); } /** * Register the given coeffect `handler` for the given `id`, for later use * within `inject-cofx`. * * `id` is keyword, often namespaced. * `handler` is a function which takes either one or two arguements, the first of which is * always `coeffects` and which returns an updated `coeffects`. * * See the docs for `inject-cofx` for example use. */ re_frame.cofx.reg_cofx = (function re_frame$cofx$reg_cofx(id,handler){ return re_frame.registrar.register_handler.call(null,re_frame.cofx.kind,id,handler); }); /** * Given an `id`, and an optional, arbitrary `value`, returns an interceptor * whose `:before` adds to the `:coeffects` (map) by calling a pre-registered * 'coeffect handler' identified by the `id`. * * The previous association of a `coeffect handler` with an `id` will have * happened via a call to `re-frame.core/reg-cofx` - generally on program startup. * * Within the created interceptor, this 'looked up' `coeffect handler` will * be called (within the `:before`) with two arguments: * - the current value of `:coeffects` * - optionally, the originally supplied arbitrary `value` * * This `coeffect handler` is expected to modify and return its first, `coeffects` argument. * * Example Of how `inject-cofx` and `reg-cofx` work together * --------------------------------------------------------- * * 1. Early in app startup, you register a `coeffect handler` for `:datetime`: * * (re-frame.core/reg-cofx * :datetime ;; usage (inject-cofx :datetime) * (fn coeffect-handler * [coeffect] * (assoc coeffect :now (js/Date.)))) ;; modify and return first arg * * 2. Later, add an interceptor to an -fx event handler, using `inject-cofx`: * * (re-frame.core/reg-event-fx ;; we are registering an event handler * :event-id * [ ... (inject-cofx :datetime) ... ] ;; <-- create an injecting interceptor * (fn event-handler * [coeffect event] * ... in here can access (:now coeffect) to obtain current datetime ... ))) * * Background * ---------- * * `coeffects` are the input resources required by an event handler * to perform its job. The two most obvious ones are `db` and `event`. * But sometimes an event handler might need other resources. * * Perhaps an event handler needs a random number or a GUID or the current * datetime. Perhaps it needs access to a DataScript database connection. * * If an event handler directly accesses these resources, it stops being * pure and, consequently, it becomes harder to test, etc. So we don't * want that. * * Instead, the interceptor created by this function is a way to 'inject' * 'necessary resources' into the `:coeffects` (map) subsequently given * to the event handler at call time. */ re_frame.cofx.inject_cofx = (function re_frame$cofx$inject_cofx(var_args){ var G__35023 = arguments.length; switch (G__35023) { case 1: return re_frame.cofx.inject_cofx.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return re_frame.cofx.inject_cofx.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); re_frame.cofx.inject_cofx.cljs$core$IFn$_invoke$arity$1 = (function (id){ return re_frame.interceptor.__GT_interceptor.call(null,new cljs.core.Keyword(null,"id","id",-1388402092),new cljs.core.Keyword(null,"coeffects","coeffects",497912985),new cljs.core.Keyword(null,"before","before",-1633692388),(function re_frame$cofx$coeffects_before(context){ var temp__5455__auto__ = re_frame.registrar.get_handler.call(null,re_frame.cofx.kind,id); if(cljs.core.truth_(temp__5455__auto__)){ var handler = temp__5455__auto__; return cljs.core.update.call(null,context,new cljs.core.Keyword(null,"coeffects","coeffects",497912985),handler); } else { return re_frame.loggers.console.call(null,new cljs.core.Keyword(null,"error","error",-978969032),"No cofx handler registered for \"",id,"\""); } })); }); re_frame.cofx.inject_cofx.cljs$core$IFn$_invoke$arity$2 = (function (id,value){ return re_frame.interceptor.__GT_interceptor.call(null,new cljs.core.Keyword(null,"id","id",-1388402092),new cljs.core.Keyword(null,"coeffects","coeffects",497912985),new cljs.core.Keyword(null,"before","before",-1633692388),(function re_frame$cofx$coeffects_before(context){ var temp__5455__auto__ = re_frame.registrar.get_handler.call(null,re_frame.cofx.kind,id); if(cljs.core.truth_(temp__5455__auto__)){ var handler = temp__5455__auto__; return cljs.core.update.call(null,context,new cljs.core.Keyword(null,"coeffects","coeffects",497912985),handler,value); } else { return re_frame.loggers.console.call(null,new cljs.core.Keyword(null,"error","error",-978969032),"No cofx handler registered for \"",id,"\""); } })); }); re_frame.cofx.inject_cofx.cljs$lang$maxFixedArity = 2; re_frame.cofx.reg_cofx.call(null,new cljs.core.Keyword(null,"db","db",993250759),(function re_frame$cofx$db_coeffects_handler(coeffects){ return cljs.core.assoc.call(null,coeffects,new cljs.core.Keyword(null,"db","db",993250759),cljs.core.deref.call(null,re_frame.db.app_db)); })); re_frame.cofx.inject_db = re_frame.cofx.inject_cofx.call(null,new cljs.core.Keyword(null,"db","db",993250759)); //# sourceMappingURL=cofx.js.map?rel=1510703495411
epl-1.0
fawwaz/mallet-modified
src/cc/mallet/share/fawwaz/MyPipe2FeatureVectorSequence.java
1214
package cc.mallet.share.fawwaz; import java.util.ArrayList; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.SerialPipes; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.LabelAlphabet; import cc.mallet.types.LabelSequence; public class MyPipe2FeatureVectorSequence extends Pipe{ /** * */ private static final long serialVersionUID = -1500218237684586833L; public MyPipe2FeatureVectorSequence(){ super(new Alphabet(),new LabelAlphabet()); } @Override public Instance pipe(Instance carrier) { Object inputData = carrier.getData(); Alphabet features = getDataAlphabet(); LabelAlphabet labels; LabelSequence target = null; System.out.println("do something please"); System.out.println("Building Pipe"); ArrayList<Pipe> pipelist = new ArrayList<>(); Pipe mypipe = new SerialPipes(pipelist); return mypipe.pipe(carrier); } // --- Private functions --- private String[][] parseSentence(String sentence) { String[] lines = sentence.split("\n"); String[][] tokens = new String[lines.length][]; for (int i = 0; i < lines.length; i++) tokens[i] = lines[i].split(" "); return tokens; } }
epl-1.0
debrief/debrief
org.mwc.debrief.build/checkstyle/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/IDeepVisitor.java
1320
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ //Tested with BCEL-5.1 //http://jakarta.apache.org/builds/jakarta-bcel/release/v5.1/ package com.puppycrawl.tools.checkstyle.bcel; /** * Deep visitor for classfile and generic traversals. A ClassFile traversal * visits all classfile and all generic nodes. * @author Rick Giles */ public interface IDeepVisitor extends IObjectSetVisitor { /** * Returns the classfile visitor. * @return the classfile visitor. */ org.apache.bcel.classfile.Visitor getClassFileVisitor(); /** * Returns the generic visitor. * @return the generic visitor. */ org.apache.bcel.generic.Visitor getGenericVisitor(); }
epl-1.0
unverbraucht/kura
kura/org.eclipse.kura.linux.net/src/main/java/org/eclipse/kura/linux/net/dns/LinuxNamed.java
20072
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.linux.net.dns; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.core.linux.util.LinuxProcessUtil; import org.eclipse.kura.linux.net.util.KuraConstants; import org.eclipse.kura.net.IP4Address; import org.eclipse.kura.net.IPAddress; import org.eclipse.kura.net.NetworkPair; import org.eclipse.kura.net.dns.DnsServerConfigIP4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LinuxNamed { private static final Logger s_logger = LoggerFactory.getLogger(LinuxNamed.class); private static final String OS_VERSION = System.getProperty("kura.os.version"); private static final String TARGET_NAME = System.getProperty("target.device"); private static LinuxNamed s_linuxNamed = null; private static String s_persistentConfigFileName = null; private static String s_logFileName = null; private static String s_rfc1912ZonesFilename = null; private static String s_procString = null; private DnsServerConfigIP4 m_dnsServerConfigIP4; private LinuxNamed() throws KuraException { if (OS_VERSION .equals(KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion()) || OS_VERSION.equals(KuraConstants.Raspberry_Pi.getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName())) { s_persistentConfigFileName = "/etc/bind/named.conf"; s_procString = "/usr/sbin/named"; if (TARGET_NAME.equals(KuraConstants.ReliaGATE_15_10.getTargetName())) { s_logFileName = "/var/named.log"; s_rfc1912ZonesFilename = "/etc/bind/named.rfc1912.zones"; } else { s_logFileName = "/var/log/named.log"; s_rfc1912ZonesFilename = "/etc/named.rfc1912.zones"; } } else if (OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) { s_persistentConfigFileName = "/etc/bind/named.conf"; s_procString = "/usr/sbin/named"; s_logFileName = "/var/log/named.log"; s_rfc1912ZonesFilename = "/etc/bind/named.rfc1912.zones"; } else { s_persistentConfigFileName = "/etc/named.conf"; s_procString = "named -u named -t"; s_logFileName = "/var/log/named.log"; s_rfc1912ZonesFilename = "/etc/named.rfc1912.zones"; } // initialize the configuration init(); if (this.m_dnsServerConfigIP4 == null) { Set<IP4Address> forwarders = new HashSet<IP4Address>(); HashSet<NetworkPair<IP4Address>> allowedNetworks = new HashSet<NetworkPair<IP4Address>>(); this.m_dnsServerConfigIP4 = new DnsServerConfigIP4(forwarders, allowedNetworks); } } public static synchronized LinuxNamed getInstance() throws KuraException { if (s_linuxNamed == null) { s_linuxNamed = new LinuxNamed(); } return s_linuxNamed; } private void init() throws KuraException { // TODO File configFile = new File(s_persistentConfigFileName); if (configFile.exists()) { s_logger.debug("initing DNS Server configuration"); try { Set<IP4Address> forwarders = new HashSet<IP4Address>(); Set<NetworkPair<IP4Address>> allowedNetworks = new HashSet<NetworkPair<IP4Address>>(); BufferedReader br = new BufferedReader(new FileReader(configFile)); boolean forwardingConfig = true; String line = null; while ((line = br.readLine()) != null) { if (line.trim().equals("forward only;")) { forwardingConfig = true; break; } } br.close(); br = null; if (forwardingConfig) { br = new BufferedReader(new FileReader(configFile)); while ((line = br.readLine()) != null) { // TODO - really simple for now StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equals("forwarders")) { // get the forwarders 'forwarders {192.168.1.1;192.168.2.1;};' StringTokenizer st2 = new StringTokenizer(st.nextToken(), "{} ;"); while (st2.hasMoreTokens()) { String forwarder = st2.nextToken(); if (forwarder != null && !forwarder.trim().equals("")) { s_logger.debug("found forwarder: {}", forwarder); forwarders.add((IP4Address) IPAddress.parseHostAddress(forwarder)); } } } else if (token.equals("allow-query")) { // get the networks 'allow-query {192.168.2.0/24;192.168.3.0/24};' StringTokenizer st2 = new StringTokenizer(st.nextToken(), "{} ;"); while (st2.hasMoreTokens()) { String allowedNetwork = st2.nextToken(); if (allowedNetwork != null && !allowedNetwork.trim().equals("")) { String[] splitNetwork = allowedNetwork.split("/"); allowedNetworks.add(new NetworkPair<IP4Address>( (IP4Address) IPAddress.parseHostAddress(splitNetwork[0]), Short.parseShort(splitNetwork[1]))); } } } } } br.close(); br = null; // set the configuration and return this.m_dnsServerConfigIP4 = new DnsServerConfigIP4(forwarders, allowedNetworks); return; } } catch (FileNotFoundException e) { throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, e); } catch (IOException e) { throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, e); } } else { s_logger.debug("There is no current DNS server configuration that allows forwarding"); } } public boolean isEnabled() throws KuraException { try { // Check if named is running int pid = LinuxProcessUtil.getPid(s_procString); return pid > -1; } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } public boolean enable() throws KuraException { // write config happened during 'set config' step try { // Check if named is running int pid = LinuxProcessUtil.getPid(s_procString); if (pid > -1) { // If so, disable it s_logger.error("DNS server is already running, bringing it down..."); disable(); } // Start named int result = -1; if (OS_VERSION.equals( KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion())) { result = LinuxProcessUtil.start("/etc/init.d/bind start"); } else if (OS_VERSION.equals(KuraConstants.ReliaGATE_10_05.getImageName() + "_" + KuraConstants.ReliaGATE_10_05.getImageVersion())) { result = LinuxProcessUtil.start("/etc/init.d/bind start"); } else if (OS_VERSION.equals(KuraConstants.Raspberry_Pi.getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName())) { result = LinuxProcessUtil.start("/etc/init.d/bind9 start"); } else if (OS_VERSION.equals( KuraConstants.Intel_Edison.getImageName() + "_" + KuraConstants.Intel_Edison.getImageVersion() + "_" + KuraConstants.Intel_Edison.getTargetName())) { result = LinuxProcessUtil.start("/etc/init.d/bind start"); } else if (OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) { result = LinuxProcessUtil.start("/etc/init.d/bind9 start"); } else { s_logger.info("Linux named enable fallback"); result = LinuxProcessUtil.start("/etc/init.d/named start"); } if (result == 0) { s_logger.debug("DNS server started."); s_logger.trace(this.m_dnsServerConfigIP4.toString()); return true; } } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } return false; } public boolean disable() throws KuraException { try { int result = -1; // If so, stop it. if (OS_VERSION.equals( KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion())) { result = LinuxProcessUtil.start("/etc/init.d/bind stop"); } else if (OS_VERSION.equals(KuraConstants.ReliaGATE_10_05.getImageName() + "_" + KuraConstants.ReliaGATE_10_05.getImageVersion())) { result = LinuxProcessUtil.start("/etc/init.d/bind stop"); } else if (OS_VERSION.equals(KuraConstants.Raspberry_Pi.getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName())) { result = LinuxProcessUtil.start("/etc/init.d/bind9 stop"); } else if (OS_VERSION.equals( KuraConstants.Intel_Edison.getImageName() + "_" + KuraConstants.Intel_Edison.getImageVersion() + "_" + KuraConstants.Intel_Edison.getTargetName())) { result = LinuxProcessUtil.start("/etc/init.d/bind stop"); } else if (OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) { result = LinuxProcessUtil.start("/etc/init.d/bind9 stop"); } else { result = LinuxProcessUtil.start("/etc/init.d/named stop"); } if (result == 0) { s_logger.debug("DNS server stopped."); s_logger.trace(this.m_dnsServerConfigIP4.toString()); return true; } else { s_logger.debug("tried to kill DNS server for interface but it is not running"); } } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } return true; } public boolean restart() throws KuraException { try { if (LinuxProcessUtil.start("/etc/init.d/named restart") == 0) { s_logger.debug("DNS server restarted."); } else { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "error restarting"); } } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } return true; } public boolean isConfigured() { if (this.m_dnsServerConfigIP4 != null && this.m_dnsServerConfigIP4.getForwarders() != null && this.m_dnsServerConfigIP4.getForwarders().size() > 0 && this.m_dnsServerConfigIP4.getAllowedNetworks() != null && this.m_dnsServerConfigIP4.getAllowedNetworks().size() > 0) { return true; } else { return false; } } public void setConfig(DnsServerConfigIP4 dnsServerConfigIP4) throws KuraException { try { this.m_dnsServerConfigIP4 = dnsServerConfigIP4; if (this.m_dnsServerConfigIP4 == null) { s_logger.warn("Set DNS server configuration to null"); } writeConfig(); } catch (Exception e) { s_logger.error("Error setting DNS server config"); throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } public DnsServerConfigIP4 getDnsServerConfig() { return this.m_dnsServerConfigIP4; } public String getConfigFilename() { return s_persistentConfigFileName; } private void writeConfig() throws KuraException { try { FileOutputStream fos = new FileOutputStream(s_persistentConfigFileName); PrintWriter pw = new PrintWriter(fos); // build up the file if (this.m_dnsServerConfigIP4 == null || this.m_dnsServerConfigIP4.getForwarders() == null || this.m_dnsServerConfigIP4.getAllowedNetworks() == null || this.m_dnsServerConfigIP4.getForwarders().size() == 0 || this.m_dnsServerConfigIP4.getAllowedNetworks().size() == 0) { s_logger.debug("writing default named.conf to {} with: {}", s_persistentConfigFileName, this.m_dnsServerConfigIP4.toString()); pw.print(getDefaultNamedFile()); } else { s_logger.debug("writing custom named.conf to {} with: {}", s_persistentConfigFileName, this.m_dnsServerConfigIP4.toString()); pw.print(getForwardingNamedFile()); } pw.flush(); fos.getFD().sync(); pw.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, "error while building up new configuration files for dns servers: " + e.getMessage()); } } private String getForwardingNamedFile() { StringBuilder sb = new StringBuilder().append("// Forwarding and Caching Name Server Configuration\n") .append("options {\n") // .append("\tdirectory \"/var/named\";\n") // .append("\tversion \"not currently available\";\n") // .append("\tforwarders {"); Set<IP4Address> forwarders = this.m_dnsServerConfigIP4.getForwarders(); for (IP4Address forwarder : forwarders) { sb.append(forwarder.getHostAddress()).append(";"); } sb.append("};\n"); sb.append("\tforward only;\n") // .append("\tallow-transfer{\"none\";};\n") // .append("\tallow-query {"); Set<NetworkPair<IP4Address>> allowedNetworks = this.m_dnsServerConfigIP4.getAllowedNetworks(); for (NetworkPair<IP4Address> pair : allowedNetworks) { sb.append(pair.getIpAddress().getHostAddress()) // .append("/") // .append(pair.getPrefix()) // .append(";"); } sb.append("};\n"); sb.append("\tmax-cache-ttl 30;\n"); sb.append("\tmax-ncache-ttl 30;\n"); sb.append("};\n") // .append("logging{\n") // .append("\tchannel named_log {\n") // .append("\t\tfile \"") // .append(s_logFileName) // .append("\" versions 3;\n") // .append("\t\tseverity info;\n") // .append("\t\tprint-severity yes;\n") // .append("\t\tprint-time yes;\n") // .append("\t\tprint-category yes;\n") // .append("\t};\n") // .append("\tcategory default{\n") // .append("\t\tnamed_log;\n") // .append("\t};\n") // .append("};\n") // .append("zone \".\" IN {\n") // .append("\ttype hint;\n") // .append("\tfile \"named.ca\";\n") // .append("};\n") // .append("include \"") // .append(s_rfc1912ZonesFilename) // .append("\";\n"); return sb.toString(); } private static final String getDefaultNamedFile() { StringBuilder sb = new StringBuilder().append("//\n") // .append("// named.conf\n") // .append("//\n") // .append("// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS\n") // .append("// server as a caching only nameserver (as a localhost DNS resolver only).\n") // .append("//\n") // .append("// See /usr/share/doc/bind*/sample/ for example named configuration files.\n") // .append("//\n") // .append("\n") // .append("options {\n") // .append("\tlisten-on port 53 { 127.0.0.1; };\n") // .append("\tlisten-on-v6 port 53 { ::1; };\n") // .append("\tdirectory \"/var/named\";\n") // .append("\tdump-file \"/var/named/data/cache_dump.db\";\n") // .append("\tstatistics-file \"/var/named/data/named_stats.txt\";\n") // .append("\tmemstatistics-file \"/var/named/data/named_mem_stats.txt\";\n") // .append("\tallow-query { localhost; };\n") // .append("\trecursion yes;\n") // .append("\n") // .append("\tmax-cache-ttl 30;\n") // .append("\tmax-ncache-ttl 30;\n") // .append("\tdnssec-enable yes;\n") // .append("\tdnssec-validation yes;\n") // .append("\tdnssec-lookaside auto;\n") // .append("\n") // .append("\t/* Path to ISC DLV key */\n") // .append("\nbindkeys-file \"/etc/named.iscdlv.key\";\n") // .append("};\n") // .append("\n") // .append("logging {\n") // .append("\tchannel default_debug {\n") // .append("\t\tfile \"data/named.run\";\n") // .append("\t\tseverity dynamic;\n") // .append("\t};\n") // .append("};\n") // .append("\n") // .append("zone \".\" IN {\n") // .append("\ttype hint;\n") // .append("\tfile \"named.ca\";\n") // .append("};\n") // .append("\n") // .append("include \"") // .append(s_rfc1912ZonesFilename) // .append("\";\n"); // // .append("include \"/etc/named.rfc1912.zones\";\n"); return sb.toString(); } }
epl-1.0
neelance/jface4ruby
jface4ruby/src/org/eclipse/core/commands/ParameterizedCommand.java
23895
/******************************************************************************* * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Benjamin Muskalla - bug 222861 [Commands] ParameterizedCommand#equals broken *******************************************************************************/ package org.eclipse.core.commands; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.core.internal.commands.util.Util; /** * <p> * A command that has had one or more of its parameters specified. This class * serves as a utility class for developers that need to manipulate commands * with parameters. It handles the behaviour of generating a parameter map and a * human-readable name. * </p> * * @since 3.1 */ public final class ParameterizedCommand implements Comparable { /** * The constant integer hash code value meaning the hash code has not yet * been computed. */ private static final int HASH_CODE_NOT_COMPUTED = -1; /** * A factor for computing the hash code for all parameterized commands. */ private static final int HASH_FACTOR = 89; /** * The seed for the hash code for all parameterized commands. */ private static final int HASH_INITIAL = ParameterizedCommand.class .getName().hashCode(); /** * The index of the parameter id in the parameter values. * * @deprecated no longer used */ public static final int INDEX_PARAMETER_ID = 0; /** * The index of the human-readable name of the parameter itself, in the * parameter values. * * @deprecated no longer used */ public static final int INDEX_PARAMETER_NAME = 1; /** * The index of the human-readable name of the value of the parameter for * this command. * * @deprecated no longer used */ public static final int INDEX_PARAMETER_VALUE_NAME = 2; /** * The index of the value of the parameter that the command can understand. * * @deprecated no longer used */ public static final int INDEX_PARAMETER_VALUE_VALUE = 3; /** * Escapes special characters in the command id, parameter ids and parameter * values for {@link #serialize()}. The special characters * {@link CommandManager#PARAMETER_START_CHAR}, * {@link CommandManager#PARAMETER_END_CHAR}, * {@link CommandManager#ID_VALUE_CHAR}, * {@link CommandManager#PARAMETER_SEPARATOR_CHAR} and * {@link CommandManager#ESCAPE_CHAR} are escaped by prepending a * {@link CommandManager#ESCAPE_CHAR} character. * * @param rawText * a <code>String</code> to escape special characters in for * serialization. * @return a <code>String</code> representing <code>rawText</code> with * special serialization characters escaped * @since 3.2 */ private static final String escape(final String rawText) { // defer initialization of a StringBuffer until we know we need one StringBuffer buffer = null; for (int i = 0; i < rawText.length(); i++) { char c = rawText.charAt(i); switch (c) { case CommandManager.PARAMETER_START_CHAR: case CommandManager.PARAMETER_END_CHAR: case CommandManager.ID_VALUE_CHAR: case CommandManager.PARAMETER_SEPARATOR_CHAR: case CommandManager.ESCAPE_CHAR: if (buffer == null) { buffer = new StringBuffer(rawText.substring(0, i)); } buffer.append(CommandManager.ESCAPE_CHAR); buffer.append(c); break; default: if (buffer != null) { buffer.append(c); } break; } } if (buffer == null) { return rawText; } return buffer.toString(); } /** * Generates every possible combination of parameter values for the given * parameters. Parameters values that cannot be initialized are just * ignored. Optional parameters are considered. * * @param startIndex * The index in the <code>parameters</code> that we should * process. This must be a valid index. * @param parameters * The parameters in to process; must not be <code>null</code>. * @return A collection (<code>Collection</code>) of combinations (<code>List</code> * of <code>Parameterization</code>). */ private static final Collection expandParameters(final int startIndex, final IParameter[] parameters) { final int nextIndex = startIndex + 1; final boolean noMoreParameters = (nextIndex >= parameters.length); final IParameter parameter = parameters[startIndex]; final List parameterizations = new ArrayList(); if (parameter.isOptional()) { parameterizations.add(null); } IParameterValues values = null; try { values = parameter.getValues(); } catch (final ParameterValuesException e) { if (noMoreParameters) { return parameterizations; } // Make recursive call return expandParameters(nextIndex, parameters); } final Map parameterValues = values.getParameterValues(); final Iterator parameterValueItr = parameterValues.entrySet() .iterator(); while (parameterValueItr.hasNext()) { final Map.Entry entry = (Map.Entry) parameterValueItr.next(); final Parameterization parameterization = new Parameterization( parameter, (String) entry.getValue()); parameterizations.add(parameterization); } // Check if another iteration will produce any more names. final int parameterizationCount = parameterizations.size(); if (noMoreParameters) { // This is it, so just return the current parameterizations. for (int i = 0; i < parameterizationCount; i++) { final Parameterization parameterization = (Parameterization) parameterizations .get(i); final List combination = new ArrayList(1); combination.add(parameterization); parameterizations.set(i, combination); } return parameterizations; } // Make recursive call final Collection suffixes = expandParameters(nextIndex, parameters); while (suffixes.remove(null)) { // just keep deleting the darn things. } if (suffixes.isEmpty()) { // This is it, so just return the current parameterizations. for (int i = 0; i < parameterizationCount; i++) { final Parameterization parameterization = (Parameterization) parameterizations .get(i); final List combination = new ArrayList(1); combination.add(parameterization); parameterizations.set(i, combination); } return parameterizations; } final Collection returnValue = new ArrayList(); final Iterator suffixItr = suffixes.iterator(); while (suffixItr.hasNext()) { final List combination = (List) suffixItr.next(); final int combinationSize = combination.size(); for (int i = 0; i < parameterizationCount; i++) { final Parameterization parameterization = (Parameterization) parameterizations .get(i); final List newCombination = new ArrayList(combinationSize + 1); newCombination.add(parameterization); newCombination.addAll(combination); returnValue.add(newCombination); } } return returnValue; } /** * <p> * Generates all the possible combinations of command parameterizations for * the given command. If the command has no parameters, then this is simply * a parameterized version of that command. If a parameter is optional, both * the included and not included cases are considered. * </p> * <p> * If one of the parameters cannot be loaded due to a * <code>ParameterValuesException</code>, then it is simply ignored. * </p> * * @param command * The command for which the parameter combinations should be * generated; must not be <code>null</code>. * @return A collection of <code>ParameterizedCommand</code> instances * representing all of the possible combinations. This value is * never empty and it is never <code>null</code>. * @throws NotDefinedException * If the command is not defined. */ public static final Collection generateCombinations(final Command command) throws NotDefinedException { final IParameter[] parameters = command.getParameters(); if (parameters == null) { return Collections .singleton(new ParameterizedCommand(command, null)); } final Collection expansion = expandParameters(0, parameters); final Collection combinations = new ArrayList(expansion.size()); final Iterator expansionItr = expansion.iterator(); while (expansionItr.hasNext()) { final List combination = (List) expansionItr.next(); if (combination == null) { combinations.add(new ParameterizedCommand(command, null)); } else { while (combination.remove(null)) { // Just keep removing while there are null entries left. } if (combination.isEmpty()) { combinations.add(new ParameterizedCommand(command, null)); } else { final Parameterization[] parameterizations = (Parameterization[]) combination .toArray(new Parameterization[combination.size()]); combinations.add(new ParameterizedCommand(command, parameterizations)); } } } return combinations; } /** * Take a command and a map of parameter IDs to values, and generate the * appropriate parameterized command. * * @param command * The command object. Must not be <code>null</code>. * @param parameters * A map of String parameter ids to objects. May be * <code>null</code>. * @return the parameterized command, or <code>null</code> if it could not * be generated * @since 3.4 */ public static final ParameterizedCommand generateCommand(Command command, Map parameters) { // no parameters if (parameters == null || parameters.isEmpty()) { return new ParameterizedCommand(command, null); } try { ArrayList parms = new ArrayList(); Iterator i = parameters.keySet().iterator(); // iterate over given parameters while (i.hasNext()) { String key = (String) i.next(); IParameter parameter = null; // get the parameter from the command parameter = command.getParameter(key); // if the parameter is defined add it to the parameter list if (parameter == null) { return null; } ParameterType parameterType = command.getParameterType(key); if (parameterType == null) { parms.add(new Parameterization(parameter, (String) parameters.get(key))); } else { AbstractParameterValueConverter valueConverter = parameterType .getValueConverter(); if (valueConverter != null) { String val = valueConverter.convertToString(parameters .get(key)); parms.add(new Parameterization(parameter, val)); } else { parms.add(new Parameterization(parameter, (String) parameters.get(key))); } } } // convert the parameters to an Parameterization array and create // the command return new ParameterizedCommand(command, (Parameterization[]) parms .toArray(new Parameterization[parms.size()])); } catch (NotDefinedException e) { } catch (ParameterValueConversionException e) { } return null; } /** * The base command which is being parameterized. This value is never * <code>null</code>. */ private final Command command; /** * The hash code for this object. This value is computed lazily, and marked * as invalid when one of the values on which it is based changes. */ private transient int hashCode = HASH_CODE_NOT_COMPUTED; /** * This is an array of parameterization defined for this command. This value * may be <code>null</code> if the command has no parameters. */ private final Parameterization[] parameterizations; private String name; /** * Constructs a new instance of <code>ParameterizedCommand</code> with * specific values for zero or more of its parameters. * * @param command * The command that is parameterized; must not be * <code>null</code>. * @param parameterizations * An array of parameterizations binding parameters to values for * the command. This value may be <code>null</code>. */ public ParameterizedCommand(final Command command, final Parameterization[] parameterizations) { if (command == null) { throw new NullPointerException( "A parameterized command cannot have a null command"); //$NON-NLS-1$ } this.command = command; IParameter[] parms = null; try { parms = command.getParameters(); } catch (NotDefinedException e) { // This should not happen. } if (parameterizations != null && parameterizations.length>0 && parms != null) { int parmIndex = 0; Parameterization[] params = new Parameterization[parameterizations.length]; for (int j = 0; j < parms.length; j++) { for (int i = 0; i < parameterizations.length; i++) { Parameterization pm = parameterizations[i]; if (parms[j].equals(pm.getParameter())) { params[parmIndex++] = pm; } } } this.parameterizations = params; } else { this.parameterizations = null; } } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public final int compareTo(final Object object) { final ParameterizedCommand command = (ParameterizedCommand) object; final boolean thisDefined = this.command.isDefined(); final boolean otherDefined = command.command.isDefined(); if (!thisDefined || !otherDefined) { return Util.compare(thisDefined, otherDefined); } try { final int compareTo = getName().compareTo(command.getName()); if (compareTo == 0) { return getId().compareTo(command.getId()); } return compareTo; } catch (final NotDefinedException e) { throw new Error( "Concurrent modification of a command's defined state"); //$NON-NLS-1$ } } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public final boolean equals(final Object object) { if (this == object) { return true; } if (!(object instanceof ParameterizedCommand)) { return false; } final ParameterizedCommand command = (ParameterizedCommand) object; if (!Util.equals(this.command, command.command)) { return false; } return Util.equals(this.parameterizations, command.parameterizations); } /** * Executes this command with its parameters. This method will succeed * regardless of whether the command is enabled or defined. It is * preferrable to use {@link #executeWithChecks(Object, Object)}. * * @param trigger * The object that triggered the execution; may be * <code>null</code>. * @param applicationContext * The state of the application at the time the execution was * triggered; may be <code>null</code>. * @return The result of the execution; may be <code>null</code>. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotHandledException * If there is no handler. * @deprecated Please use {@link #executeWithChecks(Object, Object)} * instead. */ public final Object execute(final Object trigger, final Object applicationContext) throws ExecutionException, NotHandledException { return command.execute(new ExecutionEvent(command, getParameterMap(), trigger, applicationContext)); } /** * Executes this command with its parameters. This does extra checking to * see if the command is enabled and defined. If it is not both enabled and * defined, then the execution listeners will be notified and an exception * thrown. * * @param trigger * The object that triggered the execution; may be * <code>null</code>. * @param applicationContext * The state of the application at the time the execution was * triggered; may be <code>null</code>. * @return The result of the execution; may be <code>null</code>. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.2 */ public final Object executeWithChecks(final Object trigger, final Object applicationContext) throws ExecutionException, NotDefinedException, NotEnabledException, NotHandledException { return command.executeWithChecks(new ExecutionEvent(command, getParameterMap(), trigger, applicationContext)); } /** * Returns the base command. It is possible for more than one parameterized * command to have the same identifier. * * @return The command; never <code>null</code>, but may be undefined. */ public final Command getCommand() { return command; } /** * Returns the command's base identifier. It is possible for more than one * parameterized command to have the same identifier. * * @return The command id; never <code>null</code>. */ public final String getId() { return command.getId(); } /** * Returns a human-readable representation of this command with all of its * parameterizations. * * @return The human-readable representation of this parameterized command; * never <code>null</code>. * @throws NotDefinedException * If the underlying command is not defined. */ public final String getName() throws NotDefinedException { if (name == null) { final StringBuffer nameBuffer = new StringBuffer(); nameBuffer.append(command.getName()); if (parameterizations != null) { nameBuffer.append(" ("); //$NON-NLS-1$ final int parameterizationCount = parameterizations.length; for (int i = 0; i < parameterizationCount; i++) { final Parameterization parameterization = parameterizations[i]; nameBuffer .append(parameterization.getParameter().getName()); nameBuffer.append(": "); //$NON-NLS-1$ try { nameBuffer.append(parameterization.getValueName()); } catch (final ParameterValuesException e) { /* * Just let it go for now. If someone complains we can * add more info later. */ } // If there is another item, append a separator. if (i + 1 < parameterizationCount) { nameBuffer.append(", "); //$NON-NLS-1$ } } nameBuffer.append(')'); } name = nameBuffer.toString(); } return name; } /** * Returns the parameter map, as can be used to construct an * <code>ExecutionEvent</code>. * * @return The map of parameter ids (<code>String</code>) to parameter * values (<code>String</code>). This map is never * <code>null</code>, but may be empty. */ public final Map getParameterMap() { if ((parameterizations == null) || (parameterizations.length == 0)) { return Collections.EMPTY_MAP; } final Map parameterMap = new HashMap(); for (int i = 0; i < parameterizations.length; i++) { final Parameterization parameterization = parameterizations[i]; parameterMap.put(parameterization.getParameter().getId(), parameterization.getValue()); } return parameterMap; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ public final int hashCode() { if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode = HASH_INITIAL * HASH_FACTOR + Util.hashCode(command); hashCode = hashCode * HASH_FACTOR; if (parameterizations != null) { for (int i = 0; i < parameterizations.length; i++) { hashCode += Util.hashCode(parameterizations[i]); } } if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode++; } } return hashCode; } /** * Returns a {@link String} containing the command id, parameter ids and * parameter values for this {@link ParameterizedCommand}. The returned * {@link String} can be stored by a client and later used to reconstruct an * equivalent {@link ParameterizedCommand} using the * {@link CommandManager#deserialize(String)} method. * <p> * The syntax of the returned {@link String} is as follows: * </p> * * <blockquote> * <code>serialization = <u>commandId</u> [ '(' parameters ')' ]</code><br> * <code>parameters = parameter [ ',' parameters ]</code><br> * <code>parameter = <u>parameterId</u> [ '=' <u>parameterValue</u> ]</code> * </blockquote> * * <p> * In the syntax above, sections inside square-brackets are optional. The * characters in single quotes (<code>(</code>, <code>)</code>, * <code>,</code> and <code>=</code>) indicate literal characters. * </p> * <p> * <code><u>commandId</u></code> represents the command id encoded with * separator characters escaped. <code><u>parameterId</u></code> and * <code><u>parameterValue</u></code> represent the parameter ids and * values encoded with separator characters escaped. The separator * characters <code>(</code>, <code>)</code>, <code>,</code> and * <code>=</code> are escaped by prepending a <code>%</code>. This * requires <code>%</code> to be escaped, which is also done by prepending * a <code>%</code>. * </p> * <p> * The order of the parameters is not defined (and not important). A missing * <code><u>parameterValue</u></code> indicates that the value of the * parameter is <code>null</code>. * </p> * <p> * For example, the string shown below represents a serialized parameterized * command that can be used to show the Resource perspective: * </p> * <p> * <code>org.eclipse.ui.perspectives.showPerspective(org.eclipse.ui.perspectives.showPerspective.perspectiveId=org.eclipse.ui.resourcePerspective)</code> * </p> * <p> * This example shows the more general form with multiple parameters, * <code>null</code> value parameters, and escaped <code>=</code> in the * third parameter value. * </p> * <p> * <code>command.id(param1.id=value1,param2.id,param3.id=esc%=val3)</code> * </p> * * @return A string containing the escaped command id, parameter ids and * parameter values; never <code>null</code>. * @see CommandManager#deserialize(String) * @since 3.2 */ public final String serialize() { final String escapedId = escape(getId()); if ((parameterizations == null) || (parameterizations.length == 0)) { return escapedId; } final StringBuffer buffer = new StringBuffer(escapedId); buffer.append(CommandManager.PARAMETER_START_CHAR); for (int i = 0; i < parameterizations.length; i++) { if (i > 0) { // insert separator between parameters buffer.append(CommandManager.PARAMETER_SEPARATOR_CHAR); } final Parameterization parameterization = parameterizations[i]; final String parameterId = parameterization.getParameter().getId(); final String escapedParameterId = escape(parameterId); buffer.append(escapedParameterId); final String parameterValue = parameterization.getValue(); if (parameterValue != null) { final String escapedParameterValue = escape(parameterValue); buffer.append(CommandManager.ID_VALUE_CHAR); buffer.append(escapedParameterValue); } } buffer.append(CommandManager.PARAMETER_END_CHAR); return buffer.toString(); } public final String toString() { final StringBuffer buffer = new StringBuffer(); buffer.append("ParameterizedCommand("); //$NON-NLS-1$ buffer.append(command); buffer.append(','); buffer.append(parameterizations); buffer.append(')'); return buffer.toString(); } }
epl-1.0
moji1/MDebugger
PaperEvaluationData/SizeOverhead/Refined/Refined-CounterModel_CDTProject/src/Debug__Top.hh
917
#ifndef DEBUG__TOP_HH #define DEBUG__TOP_HH #include "umlrtcapsule.hh" #include "umlrtcapsuleclass.hh" #include "umlrtmessage.hh" struct UMLRTCapsulePart; struct UMLRTCommsPort; struct UMLRTSlot; class Capsule_Debug__Top : public UMLRTCapsule { public: Capsule_Debug__Top( const UMLRTCapsuleClass * cd, UMLRTSlot * st, const UMLRTCommsPort * * border, const UMLRTCommsPort * * internal, bool isStat ); enum PartId { part_Debug__Counter, part_Debug__Gateway }; protected: const UMLRTCapsulePart * const Debug__Counter; const UMLRTCapsulePart * const Debug__Gateway; public: virtual void bindPort( bool isBorder, int portId, int index ); virtual void unbindPort( bool isBorder, int portId, int index ); virtual void initialize( const UMLRTMessage & msg ); virtual void inject( const UMLRTMessage & msg ); }; extern const UMLRTCapsuleClass Debug__Top; #endif
epl-1.0
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.resources.phaser.examples/phaser3-examples/public/src/game objects/particle emitter/fire max 10 particles.js
1282
/** * @author Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com) */ var config = { type: Phaser.WEBGL, width: 800, height: 600, backgroundColor: '#000', parent: 'phaser-example', scene: { preload: preload, create: create, update: update } }; var game = new Phaser.Game(config); var fpsText; var particles; function preload () { this.load.image('fire', 'assets/particles/muzzleflash3.png'); } function create () { fpsText = this.add.text(10, 10, 'FPS: -- \n-- Particles', { font: 'bold 26px Arial', fill: '#ffffff' }); particles = this.add.particles('fire'); particles.createEmitter({ alpha: { start: 1, end: 0 }, scale: { start: 0.5, end: 2.5 }, //tint: { start: 0xff945e, end: 0xff945e }, speed: 20, accelerationY: -300, angle: { min: -85, max: -95 }, rotate: { min: -180, max: 180 }, lifespan: { min: 1000, max: 1100 }, blendMode: 'ADD', frequency: 110, maxParticles: 10, x: 400, y: 300 }); } function update (time, delta) { fpsText.setText('FPS: ' + (1000/delta).toFixed(3) + '\n' + particles.emitters.first.alive.length + ' Particles'); }
epl-1.0
neelance/jface4ruby
jface4ruby/lib/org/eclipse/jface/text/templates/ContextTypeRegistry.rb
2524
require "rjava" # Copyright (c) 2000, 2005 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # IBM Corporation - initial API and implementation module Org::Eclipse::Jface::Text::Templates module ContextTypeRegistryImports #:nodoc: class_module.module_eval { include ::Java::Lang include ::Org::Eclipse::Jface::Text::Templates include_const ::Java::Util, :Iterator include_const ::Java::Util, :LinkedHashMap include_const ::Java::Util, :Map } end # A registry for context types. Editor implementors will usually instantiate a # registry and configure the context types available in their editor. # <p> # In order to pick up templates contributed using the <code>org.eclipse.ui.editors.templates</code> # extension point, use a <code>ContributionContextTypeRegistry</code>. # </p> # # @since 3.0 class ContextTypeRegistry include_class_members ContextTypeRegistryImports # all known context types attr_accessor :f_context_types alias_method :attr_f_context_types, :f_context_types undef_method :f_context_types alias_method :attr_f_context_types=, :f_context_types= undef_method :f_context_types= typesig { [TemplateContextType] } # Adds a context type to the registry. If there already is a context type # with the same ID registered, it is replaced. # # @param contextType the context type to add def add_context_type(context_type) @f_context_types.put(context_type.get_id, context_type) end typesig { [String] } # Returns the context type if the id is valid, <code>null</code> otherwise. # # @param id the id of the context type to retrieve # @return the context type if <code>name</code> is valid, <code>null</code> otherwise def get_context_type(id) return @f_context_types.get(id) end typesig { [] } # Returns an iterator over all registered context types. # # @return an iterator over all registered context types def context_types return @f_context_types.values.iterator end typesig { [] } def initialize @f_context_types = LinkedHashMap.new end private alias_method :initialize__context_type_registry, :initialize end end
epl-1.0
DavidGutknecht/elexis-3-base
bundles/ch.elexis.ebanking/src-gen/camt/TechnicalInputChannel1Choice.java
2535
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2017.06.14 um 06:06:29 PM CEST // package camt; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für TechnicalInputChannel1Choice complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="TechnicalInputChannel1Choice"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;element name="Cd" type="{urn:iso:std:iso:20022:tech:xsd:camt.054.001.06}ExternalTechnicalInputChannel1Code"/> * &lt;element name="Prtry" type="{urn:iso:std:iso:20022:tech:xsd:camt.054.001.06}Max35Text"/> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TechnicalInputChannel1Choice", propOrder = { "cd", "prtry" }) public class TechnicalInputChannel1Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Ruft den Wert der cd-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Legt den Wert der cd-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; } /** * Ruft den Wert der prtry-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Legt den Wert der prtry-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
epl-1.0
Nodeclipse/eclipse-color-theme
com.github.eclipsecolortheme/src/com/github/eclipsecolortheme/mapper/CEditorMapper.java
367
package com.github.eclipsecolortheme.mapper; import java.util.Map; import com.github.eclipsecolortheme.ColorThemeSetting; public class CEditorMapper extends GenericMapper { @Override public void map(Map<String, ColorThemeSetting> theme) { preferences.putBoolean("sourceHoverBackgroundColor.SystemDefault", false); super.map(theme); } }
epl-1.0
rmcilroy/HeraJVM
libraryInterface/GNUClasspath/CPL/src/java/net/JikesRVMSupport.java
1585
/* * This file is part of the Jikes RVM project (http://jikesrvm.org). * * This file is licensed to You under the Common Public License (CPL); * You may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.opensource.org/licenses/cpl1.0.php * * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. */ package java.net; import org.jikesrvm.VM_SizeConstants; /** * Library support interface of Jikes RVM */ public class JikesRVMSupport implements VM_SizeConstants { private static byte[] toArrayForm(int address) { byte[] addr = new byte[4]; addr[0] = (byte)((address>>(3*BITS_IN_BYTE)) & 0xff); addr[1] = (byte)((address>>(2*BITS_IN_BYTE)) & 0xff); addr[2] = (byte)((address>>BITS_IN_BYTE) & 0xff); addr[3] = (byte)(address & 0xff); return addr; } public static InetAddress createInetAddress(int address) { return createInetAddress(address, null); } public static InetAddress createInetAddress(int address, String hostname) { return new Inet4Address(toArrayForm(address), hostname); } public static int getFamily(InetAddress inetaddress) { if (inetaddress instanceof Inet4Address) { return 2; } else if (inetaddress instanceof Inet6Address) { return 10; } else { throw new org.jikesrvm.VM_UnimplementedError("Unknown InetAddress family"); } } public static void setHostName(InetAddress inetaddress, String hostname) { inetaddress.hostName = hostname; } }
epl-1.0
ELTE-Soft/txtUML
examples/tests/hu.elte.txtuml.seqdiag.tests.models/src/hu/elte/txtuml/seqdiag/tests/models/testmodel/TestSig.java
138
package hu.elte.txtuml.seqdiag.tests.models.testmodel; import hu.elte.txtuml.api.model.Signal; public class TestSig extends Signal { }
epl-1.0
iGoodie/TwitchSpawn
src/main/java/net/programmer/igoodie/twitchspawn/util/CooldownBucket.java
1751
package net.programmer.igoodie.twitchspawn.util; import java.time.Instant; import java.util.HashMap; import java.util.Map; public class CooldownBucket { public int globalCooldownMillis; public int cooldownMillis; public long globalCooldownUntil; public Map<String, Long> individualCooldownUntil; public CooldownBucket(int globalCooldown, int individualCooldown) { this.cooldownMillis = individualCooldown; this.globalCooldownMillis = globalCooldown; this.globalCooldownUntil = now(); this.individualCooldownUntil = new HashMap<>(); } public float getGlobalCooldown() { long now = now(); return Math.max(0, (globalCooldownUntil - now) / 1000f); } public long getGlobalCooldownTimestamp() { return globalCooldownUntil; } public boolean hasGlobalCooldown() { if (globalCooldownMillis == 0) return false; long now = now(); return now <= globalCooldownUntil; } public boolean hasCooldown(String nickname) { long now = now(); Long nextAvailableTime = individualCooldownUntil.get(nickname); return nextAvailableTime != null && now <= nextAvailableTime; } public long getCooldown(String nickname) { return individualCooldownUntil.get(nickname) - now(); } public boolean canConsume(String nickname) { return !hasGlobalCooldown() && !hasCooldown(nickname); } public void consume(String nickname) { long now = now(); globalCooldownUntil = now + globalCooldownMillis; individualCooldownUntil.put(nickname, now + cooldownMillis); } public static long now() { return Instant.now().getEpochSecond() * 1000; } }
epl-1.0
opendaylight/netvirt
vpnmanager/api/src/main/java/org/opendaylight/netvirt/vpnmanager/api/VpnHelper.java
10261
/* * Copyright © 2015, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netvirt.vpnmanager.api; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.mdsal.binding.api.DataBroker; import org.opendaylight.mdsal.binding.api.ReadTransaction; import org.opendaylight.mdsal.common.api.LogicalDatastoreType; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInstanceOpData; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInstanceToVpnId; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnList; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnListKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.VpnInstances; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.VpnInterfaces; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.instances.VpnInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.instances.VpnInstanceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.interfaces.VpnInterface; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.interfaces.VpnInterfaceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.interfaces.vpn._interface.VpnInstanceNames; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.interfaces.vpn._interface.VpnInstanceNames.AssociatedSubnetType; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.l3vpn.rev200204.vpn.interfaces.vpn._interface.VpnInstanceNamesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.common.Uint64; public final class VpnHelper { private VpnHelper() { } //FIXME: Implement caches for DS reads @Nullable public static VpnInstance getVpnInstance(DataBroker broker, String vpnInstanceName) { InstanceIdentifier<VpnInstance> id = InstanceIdentifier.builder(VpnInstances.class).child(VpnInstance.class, new VpnInstanceKey(vpnInstanceName)).build(); Optional<VpnInstance> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id); return (vpnInstance.isPresent()) ? vpnInstance.get() : null; } public static <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) { try (ReadTransaction tx = broker.newReadOnlyTransaction()) { return tx.read(datastoreType, path).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } public static List<VpnInstance> getAllVpnInstances(DataBroker broker) { InstanceIdentifier<VpnInstances> id = InstanceIdentifier.builder(VpnInstances.class).build(); Optional<VpnInstances> optVpnInstances = read(broker, LogicalDatastoreType.CONFIGURATION, id); if (optVpnInstances.isPresent() && optVpnInstances.get().getVpnInstance() != null) { return new ArrayList<VpnInstance>(optVpnInstances.get().nonnullVpnInstance().values()); } else { return Collections.emptyList(); } } /** * Retrieves the dataplane identifier of a specific VPN, searching by its * VpnInstance name. * * @param broker dataBroker service reference * @param vpnName Name of the VPN * @return the dataplane identifier of the VPN, the VrfTag. */ public static long getVpnId(DataBroker broker, String vpnName) { InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn .id.VpnInstance> id = getVpnInstanceToVpnIdIdentifier(vpnName); Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id .VpnInstance> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id); long vpnId = -1; if (vpnInstance.isPresent()) { vpnId = vpnInstance.get().getVpnId().toJava(); } return vpnId; } static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911 .vpn.instance.to.vpn.id.VpnInstance> getVpnInstanceToVpnIdIdentifier(String vpnName) { return InstanceIdentifier.builder(VpnInstanceToVpnId.class).child(org.opendaylight.yang.gen.v1.urn .opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id .VpnInstanceKey(vpnName)).build(); } @Nullable public static VpnInterface getVpnInterface(DataBroker broker, String vpnInterfaceName) { InstanceIdentifier<VpnInterface> id = getVpnInterfaceIdentifier(vpnInterfaceName); Optional<VpnInterface> vpnInterface = read(broker, LogicalDatastoreType.CONFIGURATION, id); return vpnInterface.isPresent() ? vpnInterface.get() : null; } static InstanceIdentifier<VpnInterface> getVpnInterfaceIdentifier(String vpnInterfaceName) { return InstanceIdentifier.builder(VpnInterfaces.class) .child(VpnInterface.class, new VpnInterfaceKey(vpnInterfaceName)).build(); } @Nullable public static String getFirstVpnNameFromVpnInterface(final VpnInterface original) { List<VpnInstanceNames> optList = new ArrayList<VpnInstanceNames>(original.nonnullVpnInstanceNames().values()); if (optList != null && !optList.isEmpty()) { return optList.get(0).getVpnName(); } else { return null; } } @NonNull public static List<String> getVpnInterfaceVpnInstanceNamesString(@Nullable List<VpnInstanceNames> vpnInstanceList) { List<String> listVpn = new ArrayList<>(); if (vpnInstanceList != null) { for (VpnInstanceNames vpnInterfaceVpnInstance : vpnInstanceList) { listVpn.add(vpnInterfaceVpnInstance.getVpnName()); } } return listVpn; } public static VpnInstanceNames getVpnInterfaceVpnInstanceNames(String vpnName, AssociatedSubnetType subnetType) { return new VpnInstanceNamesBuilder().setVpnName(vpnName).setAssociatedSubnetType(subnetType).build(); } public static void removeVpnInterfaceVpnInstanceNamesFromList(String vpnName, List<VpnInstanceNames> vpnInstanceList) { if (vpnInstanceList != null) { vpnInstanceList.removeIf(instance -> vpnName.equals(instance.getVpnName())); } } public static boolean doesVpnInterfaceBelongToVpnInstance(String vpnName, List<VpnInstanceNames> vpnInstanceList) { if (vpnInstanceList != null) { for (VpnInstanceNames vpnInstance : vpnInstanceList) { if (vpnName.equals(vpnInstance.getVpnName())) { return true; } } } return false; } public static boolean isSubnetPartOfVpn(Subnetmap sn, String vpnName) { if (vpnName == null || sn == null) { return false; } if (sn.getVpnId() == null || !sn.getVpnId().getValue().equals(vpnName)) { return false; } return true; } static InstanceIdentifier<Subnetmap> buildSubnetmapIdentifier(Uuid subnetId) { return InstanceIdentifier.builder(Subnetmaps.class) .child(Subnetmap.class, new SubnetmapKey(subnetId)).build(); } /** Get Subnetmap from its Uuid. * @param broker the data broker for look for data * @param subnetUuid the subnet's Uuid * @return the Subnetmap of Uuid or null if it is not found */ @Nullable public static Subnetmap getSubnetmapFromItsUuid(DataBroker broker, Uuid subnetUuid) { Subnetmap sn = null; InstanceIdentifier<Subnetmap> id = buildSubnetmapIdentifier(subnetUuid); Optional<Subnetmap> optionalSn = read(broker, LogicalDatastoreType.CONFIGURATION, id); if (optionalSn.isPresent()) { sn = optionalSn.get(); } return sn; } public static InstanceIdentifier<VpnToDpnList> getVpnToDpnListIdentifier(String rd, Uint64 dpnId) { return InstanceIdentifier.builder(VpnInstanceOpData.class) .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd)) .child(VpnToDpnList.class, new VpnToDpnListKey(dpnId)).build(); } }
epl-1.0
vimil/waffle
Source/JNA/waffle-tests/src/main/java/waffle/mock/MockWindowsIdentity.java
2761
/** * Waffle (https://github.com/dblock/waffle) * * Copyright (c) 2010 - 2015 Application Security, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Application Security, Inc. */ package waffle.mock; import java.util.ArrayList; import java.util.List; import waffle.windows.auth.IWindowsAccount; import waffle.windows.auth.IWindowsIdentity; import waffle.windows.auth.IWindowsImpersonationContext; /** * A Mock windows identity. * * @author dblock[at]dblock[dot]org */ public class MockWindowsIdentity implements IWindowsIdentity { /** The fqn. */ private final String fqn; /** The groups. */ private final List<String> groups; /** * Instantiates a new mock windows identity. * * @param newFqn * the new fqn * @param newGroups * the new groups */ public MockWindowsIdentity(final String newFqn, final List<String> newGroups) { this.fqn = newFqn; this.groups = newGroups; } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#getFqn() */ @Override public String getFqn() { return this.fqn; } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#getGroups() */ @Override public IWindowsAccount[] getGroups() { final List<MockWindowsAccount> groupsList = new ArrayList<>(); for (final String group : this.groups) { groupsList.add(new MockWindowsAccount(group)); } return groupsList.toArray(new IWindowsAccount[0]); } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#getSid() */ @Override public byte[] getSid() { return new byte[0]; } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#getSidString() */ @Override public String getSidString() { return "S-" + this.fqn.hashCode(); } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#dispose() */ @Override public void dispose() { // Do Nothing } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#isGuest() */ @Override public boolean isGuest() { return this.fqn.equals("Guest"); } /* * (non-Javadoc) * @see waffle.windows.auth.IWindowsIdentity#impersonate() */ @Override public IWindowsImpersonationContext impersonate() { return new MockWindowsImpersonationContext(); } }
epl-1.0
PlegmaLabs/openhab
bundles/persistence/org.openhab.persistence.psql/src/main/java/org/openhab/persistence/psql/internal/SqlItem.java
888
package org.openhab.persistence.psql.internal; import java.text.DateFormat; import java.util.Date; import org.openhab.core.persistence.HistoricItem; import org.openhab.core.types.State; /** * This is a Java bean used to return historic items from a SQL database. * * @author Chris Jackson * @since 1.3.0 * */ public class SqlItem implements HistoricItem { final private String name; final private State state; final private Date timestamp; public SqlItem(String name, State state, Date timestamp) { this.name = name; this.state = state; this.timestamp = timestamp; } public String getName() { return name; } public State getState() { return state; } public Date getTimestamp() { return timestamp; } @Override public String toString() { return DateFormat.getDateTimeInstance().format(timestamp) + ": " + name + " -> "+ state.toString(); } }
epl-1.0
scmod/nexus-public
testsuite/legacy-testsuite/src/test/java/org/sonatype/nexus/testsuite/misc/nexus930/Nexus930AutoDiscoverComponentIT.java
6682
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.testsuite.misc.nexus930; import java.io.IOException; import java.util.List; import org.sonatype.nexus.integrationtests.AbstractPrivilegeTest; import org.sonatype.nexus.integrationtests.RequestFacade; import org.sonatype.nexus.integrationtests.TestContainer; import org.sonatype.nexus.rest.model.PlexusComponentListResource; import org.sonatype.nexus.rest.model.PlexusComponentListResourceResponse; import org.sonatype.nexus.rest.model.RepositoryContentClassListResource; import org.sonatype.nexus.rest.model.RepositoryContentClassListResourceResponse; import org.sonatype.plexus.rest.representation.XStreamRepresentation; import com.thoughtworks.xstream.XStream; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Response; /** * Test the AutoDiscoverComponent a */ public class Nexus930AutoDiscoverComponentIT extends AbstractPrivilegeTest { @BeforeClass public static void setSecureTest() { TestContainer.getInstance().getTestContext().setSecureTest(true); } @Test public void testInvalidRole() throws Exception { Response response1 = sendMessage("JUNK-foo-Bar-JUNK", this.getXMLXStream(), MediaType.APPLICATION_XML); Assert.assertTrue(response1.getStatus().isClientError()); Assert.assertEquals(404, response1.getStatus().getCode()); } @Test public void testContentClassComponentListPlexusResource() throws Exception { String role = "repo_content_classes"; // do admin List<RepositoryContentClassListResource> result1 = this.getContentClasses(this.getXMLXStream(), MediaType.APPLICATION_XML); Assert.assertTrue(result1.size() > 0); // 403 test this.overwriteUserRole(TEST_USER_NAME, "login-only" + role, "2"); TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME); TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD); this.getContentClasses(this.getXMLXStream(), MediaType.APPLICATION_XML, 403); // only content class priv this.overwriteUserRole(TEST_USER_NAME, "content-classes" + role, "70"); TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME); TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD); Assert.assertNotNull(this.getContentClasses(this.getXMLXStream(), MediaType.APPLICATION_XML)); } @Test public void testScheduledTaskTypeComonentListPlexusResource() throws Exception { String role = "schedule_types"; // do admin List<PlexusComponentListResource> result1 = this.getResult(role, this.getXMLXStream(), MediaType.APPLICATION_XML); Assert.assertTrue("Expected list larger then 1.", result1.size() > 1); // 403 test this.overwriteUserRole(TEST_USER_NAME, "login-only" + role, "2"); TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME); TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD); Response response = sendMessage(role, this.getXMLXStream(), MediaType.APPLICATION_XML); Assert.assertTrue("Expected Error: Status was: " + response.getStatus().getCode(), response.getStatus().isClientError()); Assert.assertEquals(403, response.getStatus().getCode()); // only content class priv this.overwriteUserRole(TEST_USER_NAME, "schedule_types" + role, "71"); TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME); TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD); response = sendMessage(role, this.getXMLXStream(), MediaType.APPLICATION_XML); Assert.assertTrue(response.getStatus().isSuccess()); } private List<RepositoryContentClassListResource> getContentClasses(XStream xstream, MediaType mediaType) throws IOException { return getContentClasses(xstream, mediaType, -1); } private List<RepositoryContentClassListResource> getContentClasses(XStream xstream, MediaType mediaType, int failureId) throws IOException { XStreamRepresentation representation = new XStreamRepresentation(xstream, "", mediaType); String serviceURI = "service/local/components/repo_content_classes"; Response response = RequestFacade.sendMessage(serviceURI, Method.GET, representation); if (failureId > -1) { Assert.assertEquals(failureId, response.getStatus().getCode()); return null; } else { String responseString = response.getEntity().getText(); representation = new XStreamRepresentation(xstream, responseString, mediaType); RepositoryContentClassListResourceResponse resourceResponse = (RepositoryContentClassListResourceResponse) representation .getPayload(new RepositoryContentClassListResourceResponse()); return resourceResponse.getData(); } } private List<PlexusComponentListResource> getResult(String role, XStream xstream, MediaType mediaType) throws IOException { String responseString = this.sendMessage(role, xstream, mediaType).getEntity().getText(); XStreamRepresentation representation = new XStreamRepresentation(xstream, responseString, mediaType); PlexusComponentListResourceResponse resourceResponse = (PlexusComponentListResourceResponse) representation.getPayload(new PlexusComponentListResourceResponse()); return resourceResponse.getData(); } private Response sendMessage(String role, XStream xstream, MediaType mediaType) throws IOException { XStreamRepresentation representation = new XStreamRepresentation(xstream, "", mediaType); String serviceURI = "service/local/components/" + role; return RequestFacade.sendMessage(serviceURI, Method.GET, representation); } }
epl-1.0
llnek/impactjs
src/web/impact/scripts/zotohlabs/ents/death-explosion.js
2783
// // Copyright (c) 2013 Cherimoia, LLC. All rights reserved. // // This library is distributed in the hope that it will be useful // but without any warranty; without even the implied warranty of // merchantability or fitness for a particular purpose. // // The use and distribution terms for this software are covered by the // Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) // which can be found in the file epl-v10.html at the root of this distribution. // // By using this software in any fashion, you are agreeing to be bound by // the terms of this license. // You must not remove this notice, or any other, from this software. // (function (undef) { "use strict"; var global = this; var _ = global._ ; //////////////////////// ////////////////////////////////////////////////////////////////////////////// // module def ////////////////////////////////////////////////////////////////////////////// ig.module( 'zotohlabs.ents.death-explosion').requires( 'impact.entity').defines(function () { global.EntityDeathExplosion = ig.Entity.extend({ _wmIgnore: true, delay:1, callBack:null, particles:25, update: function () { if (this.idleTimer.delta() > this.delay) { this.kill(); if (this.callBack) { this.callBack(); } } }, init: function (x, y, settings) { this.parent(x, y, settings); _.each(_.range(this.particles),function(n) { ig.game.spawnEntity(EntityDeathExplosionParticle, x, y, { colorOffset: settings.colorOffset ? settings.colorOffset : 0}); }); this.idleTimer = new ig.Timer(); } }); global.EntityDeathExplosionParticle = ig.Entity.extend({ collides:ig.Entity.COLLIDES.NONE, _wmIgnore: true, size:{x:2, y:2}, maxVel:{x:160, y:200}, delay:1, fadetime:1, bounciness:0, vel:{x:100, y:30}, friction:{x:100, y:0}, colorOffset:0, totalColors:7, baseVelocity:{x:2, y:2}, animSheet:new ig.AnimationSheet('media/main/game/blood.png', 2, 2), update: function () { if (this.idleTimer.delta() > this.delay) { this.kill(); return; } this.currentAnim.alpha = this.idleTimer.delta().map( this.delay - this.fadetime, this.delay, 1, 0 ); this.parent(); }, init: function (x, y, settings) { this.parent(x, y, settings); var frameID = Math.round(Math.random() * this.totalColors) + (this.colorOffset * (this.totalColors + 1)); this.addAnim('idle', 0.2, [frameID]); this.vel.x = (Math.random() * this.baseVelocity.x - 1) * this.vel.x; this.vel.y = (Math.random() * this.baseVelocity.y - 1) * this.vel.y; this.idleTimer = new ig.Timer(); } }); }); }).call(this);
epl-1.0
enphoneh/Glide3.6.1_fixbug
src/com/bumptech/glide/load/engine/bitmap_recycle/SizeConfigStrategy.java
8238
package com.bumptech.glide.load.engine.bitmap_recycle; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.os.Build; import com.bumptech.glide.util.Util; import java.util.HashMap; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; /** * Keys {@link android.graphics.Bitmap Bitmaps} using both {@link android.graphics.Bitmap#getAllocationByteCount()} and * the {@link android.graphics.Bitmap.Config} returned from {@link android.graphics.Bitmap#getConfig()}. * * <p> * Using both the config and the byte size allows us to safely re-use a greater variety of * {@link android.graphics.Bitmap Bitmaps}, which increases the hit rate of the pool and therefore the performance * of applications. This class works around #301 by only allowing re-use of {@link android.graphics.Bitmap Bitmaps} * with a matching number of bytes per pixel. * </p> */ @TargetApi(Build.VERSION_CODES.KITKAT) public class SizeConfigStrategy implements LruPoolStrategy { private static final int MAX_SIZE_MULTIPLE = 8; private static final Bitmap.Config[] ARGB_8888_IN_CONFIGS = new Bitmap.Config[] { Bitmap.Config.ARGB_8888, // The value returned by Bitmaps with the hidden Bitmap config. null, }; // We probably could allow ARGB_4444 and RGB_565 to decode into each other, but ARGB_4444 is deprecated and we'd // rather be safe. private static final Bitmap.Config[] RGB_565_IN_CONFIGS = new Bitmap.Config[] { Bitmap.Config.RGB_565 }; private static final Bitmap.Config[] ARGB_4444_IN_CONFIGS = new Bitmap.Config[] { Bitmap.Config.ARGB_4444 }; private static final Bitmap.Config[] ALPHA_8_IN_CONFIGS = new Bitmap.Config[] { Bitmap.Config.ALPHA_8 }; private final KeyPool keyPool = new KeyPool(); private final GroupedLinkedMap<Key, Bitmap> groupedMap = new GroupedLinkedMap<Key, Bitmap>(); private final Map<Bitmap.Config, NavigableMap<Integer, Integer>> sortedSizes = new HashMap<Bitmap.Config, NavigableMap<Integer, Integer>>(); @Override public void put(Bitmap bitmap) { int size = Util.getBitmapByteSize(bitmap); Key key = keyPool.get(size, bitmap.getConfig()); groupedMap.put(key, bitmap); NavigableMap<Integer, Integer> sizes = getSizesForConfig(bitmap.getConfig()); Integer current = sizes.get(key.size); sizes.put(key.size, current == null ? 1 : current + 1); } @Override public Bitmap get(int width, int height, Bitmap.Config config) { int size = Util.getBitmapByteSize(width, height, config); Key targetKey = keyPool.get(size, config); Key bestKey = findBestKey(targetKey, size, config); Bitmap result = groupedMap.get(bestKey); if (result != null) { // Decrement must be called before reconfigure. decrementBitmapOfSize(Util.getBitmapByteSize(result), result.getConfig()); result.reconfigure(width, height, result.getConfig() != null ? result.getConfig() : Bitmap.Config.ARGB_8888); } return result; } private Key findBestKey(Key key, int size, Bitmap.Config config) { Key result = key; for (Bitmap.Config possibleConfig : getInConfigs(config)) { NavigableMap<Integer, Integer> sizesForPossibleConfig = getSizesForConfig(possibleConfig); Integer possibleSize = sizesForPossibleConfig.ceilingKey(size); if (possibleSize != null && possibleSize <= size * MAX_SIZE_MULTIPLE) { if (possibleSize != size || (possibleConfig == null ? config != null : !possibleConfig.equals(config))) { keyPool.offer(key); result = keyPool.get(possibleSize, possibleConfig); } break; } } return result; } @Override public Bitmap removeLast() { Bitmap removed = groupedMap.removeLast(); if (removed != null) { int removedSize = Util.getBitmapByteSize(removed); decrementBitmapOfSize(removedSize, removed.getConfig()); } return removed; } private void decrementBitmapOfSize(Integer size, Bitmap.Config config) { NavigableMap<Integer, Integer> sizes = getSizesForConfig(config); Integer current = sizes.get(size); if (current == 1) { sizes.remove(size); } else { sizes.put(size, current - 1); } } private NavigableMap<Integer, Integer> getSizesForConfig(Bitmap.Config config) { NavigableMap<Integer, Integer> sizes = sortedSizes.get(config); if (sizes == null) { sizes = new TreeMap<Integer, Integer>(); sortedSizes.put(config, sizes); } return sizes; } @Override public String logBitmap(Bitmap bitmap) { int size = Util.getBitmapByteSize(bitmap); return getBitmapString(size, bitmap.getConfig()); } @Override public String logBitmap(int width, int height, Bitmap.Config config) { int size = Util.getBitmapByteSize(width, height, config); return getBitmapString(size, config); } @Override public int getSize(Bitmap bitmap) { return Util.getBitmapByteSize(bitmap); } @Override public String toString() { StringBuilder sb = new StringBuilder() .append("SizeConfigStrategy{groupedMap=") .append(groupedMap) .append(", sortedSizes=("); for (Map.Entry<Bitmap.Config, NavigableMap<Integer, Integer>> entry : sortedSizes.entrySet()) { sb.append(entry.getKey()).append('[').append(entry.getValue()).append("], "); } if (!sortedSizes.isEmpty()) { sb.replace(sb.length() - 2, sb.length(), ""); } return sb.append(")}").toString(); } // Visible for testing. static class KeyPool extends BaseKeyPool<Key> { public Key get(int size, Bitmap.Config config) { Key result = get(); result.init(size, config); return result; } @Override protected Key create() { return new Key(this); } } // Visible for testing. static final class Key implements Poolable { private final KeyPool pool; private int size; private Bitmap.Config config; public Key(KeyPool pool) { this.pool = pool; } // Visible for testing. Key(KeyPool pool, int size, Bitmap.Config config) { this(pool); init(size, config); } public void init(int size, Bitmap.Config config) { this.size = size; this.config = config; } @Override public void offer() { pool.offer(this); } @Override public String toString() { return getBitmapString(size, config); } @Override public boolean equals(Object o) { if (o instanceof Key) { Key other = (Key) o; return size == other.size && (config == null ? other.config == null : config.equals(other.config)); } return false; } @Override public int hashCode() { int result = size; result = 31 * result + (config != null ? config.hashCode() : 0); return result; } } private static String getBitmapString(int size, Bitmap.Config config) { return "[" + size + "](" + config + ")"; } private static Bitmap.Config[] getInConfigs(Bitmap.Config requested) { switch (requested) { case ARGB_8888: return ARGB_8888_IN_CONFIGS; case RGB_565: return RGB_565_IN_CONFIGS; case ARGB_4444: return ARGB_4444_IN_CONFIGS; case ALPHA_8: return ALPHA_8_IN_CONFIGS; default: return new Bitmap.Config[] { requested }; } } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java
34585
/******************************************************************************* * Copyright (c) 2000, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.corext.refactoring; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.resources.IProject; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.WorkingCopyOwner; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.IExtendedModifier; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.QualifiedType; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeParameter; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.TypeNameMatch; import org.eclipse.jdt.internal.corext.dom.ASTFlattener; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.corext.util.TypeNameMatchCollector; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor; import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class TypeContextChecker { private static class MethodTypesChecker { private static final String METHOD_NAME= "__$$__"; //$NON-NLS-1$ private final IMethod fMethod; private final StubTypeContext fStubTypeContext; private final List<ParameterInfo> fParameterInfos; private final ReturnTypeInfo fReturnTypeInfo; public MethodTypesChecker(IMethod method, StubTypeContext stubTypeContext, List<ParameterInfo> parameterInfos, ReturnTypeInfo returnTypeInfo) { fMethod= method; fStubTypeContext= stubTypeContext; fParameterInfos= parameterInfos; fReturnTypeInfo= returnTypeInfo; } public RefactoringStatus[] checkAndResolveMethodTypes() throws CoreException { RefactoringStatus[] results= new MethodTypesSyntaxChecker(fMethod, fParameterInfos, fReturnTypeInfo).checkSyntax(); for (int i= 0; i < results.length; i++) if (results[i] != null && results[i].hasFatalError()) return results; int parameterCount= fParameterInfos.size(); String[] types= new String[parameterCount + 1]; for (int i= 0; i < parameterCount; i++) types[i]= ParameterInfo.stripEllipsis((fParameterInfos.get(i)).getNewTypeName()); types[parameterCount]= fReturnTypeInfo.getNewTypeName(); RefactoringStatus[] semanticsResults= new RefactoringStatus[parameterCount + 1]; ITypeBinding[] typeBindings= resolveBindings(types, semanticsResults, true); boolean needsSecondPass= false; for (int i= 0; i < types.length; i++) if (typeBindings[i] == null || ! semanticsResults[i].isOK()) needsSecondPass= true; RefactoringStatus[] semanticsResults2= new RefactoringStatus[parameterCount + 1]; if (needsSecondPass) typeBindings= resolveBindings(types, semanticsResults2, false); for (int i= 0; i < fParameterInfos.size(); i++) { ParameterInfo parameterInfo= fParameterInfos.get(i); if (!parameterInfo.isResolve()) continue; if (parameterInfo.getOldTypeBinding() != null && ! parameterInfo.isTypeNameChanged()) { parameterInfo.setNewTypeBinding(parameterInfo.getOldTypeBinding()); } else { parameterInfo.setNewTypeBinding(typeBindings[i]); if (typeBindings[i] == null || (needsSecondPass && ! semanticsResults2[i].isOK())) { if (results[i] == null) results[i]= semanticsResults2[i]; else results[i].merge(semanticsResults2[i]); } } } fReturnTypeInfo.setNewTypeBinding(typeBindings[fParameterInfos.size()]); if (typeBindings[parameterCount] == null || (needsSecondPass && ! semanticsResults2[parameterCount].isOK())) { if (results[parameterCount] == null) results[parameterCount]= semanticsResults2[parameterCount]; else results[parameterCount].merge(semanticsResults2[parameterCount]); } return results; } private ITypeBinding[] resolveBindings(String[] types, RefactoringStatus[] results, boolean firstPass) throws CoreException { //TODO: split types into parameterTypes and returnType int parameterCount= types.length - 1; ITypeBinding[] typeBindings= new ITypeBinding[types.length]; StringBuffer cuString= new StringBuffer(); cuString.append(fStubTypeContext.getBeforeString()); int offsetBeforeMethodName= appendMethodDeclaration(cuString, types, parameterCount); cuString.append(fStubTypeContext.getAfterString()); // need a working copy to tell the parser where to resolve (package visible) types ICompilationUnit wc= fMethod.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor()); try { wc.getBuffer().setContents(cuString.toString()); CompilationUnit compilationUnit= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(wc, true); ASTNode method= NodeFinder.perform(compilationUnit, offsetBeforeMethodName, METHOD_NAME.length()).getParent(); Type[] typeNodes= new Type[types.length]; if (method instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) method; typeNodes[parameterCount]= methodDeclaration.getReturnType2(); List<SingleVariableDeclaration> parameters= methodDeclaration.parameters(); for (int i= 0; i < parameterCount; i++) typeNodes[i]= parameters.get(i).getType(); } else if (method instanceof AnnotationTypeMemberDeclaration) { typeNodes[0]= ((AnnotationTypeMemberDeclaration) method).getType(); } for (int i= 0; i < types.length; i++) { Type type= typeNodes[i]; if (type == null) { String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_couldNotResolveType, BasicElementLabels.getJavaElementName(types[i])); results[i]= RefactoringStatus.createErrorStatus(msg); continue; } results[i]= new RefactoringStatus(); IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS); if (problems.length > 0) { for (int p= 0; p < problems.length; p++) if (isError(problems[p], type)) results[i].addError(problems[p].getMessage()); } ITypeBinding binding= handleBug84585(type.resolveBinding()); if (firstPass && (binding == null || binding.isRecovered())) { types[i]= qualifyTypes(type, results[i]); } typeBindings[i]= binding; } return typeBindings; } finally { wc.discardWorkingCopy(); } } /** * Decides if a problem matters. * @param problem the problem * @param type the current type * @return return if a problem matters. */ private boolean isError(IProblem problem, Type type) { return true; } private int appendMethodDeclaration(StringBuffer cuString, String[] types, int parameterCount) throws JavaModelException { int flags= fMethod.getFlags(); if (Flags.isStatic(flags)) { cuString.append("static "); //$NON-NLS-1$ } else if (Flags.isDefaultMethod(flags)) { cuString.append("default "); //$NON-NLS-1$ } ITypeParameter[] methodTypeParameters= fMethod.getTypeParameters(); if (methodTypeParameters.length != 0) { cuString.append('<'); for (int i= 0; i < methodTypeParameters.length; i++) { ITypeParameter typeParameter= methodTypeParameters[i]; if (i > 0) cuString.append(','); cuString.append(typeParameter.getElementName()); } cuString.append("> "); //$NON-NLS-1$ } cuString.append(types[parameterCount]).append(' '); int offsetBeforeMethodName= cuString.length(); cuString.append(METHOD_NAME).append('('); for (int i= 0; i < parameterCount; i++) { if (i > 0) cuString.append(','); cuString.append(types[i]).append(" p").append(i); //$NON-NLS-1$ } cuString.append(");"); //$NON-NLS-1$ return offsetBeforeMethodName; } private String qualifyTypes(Type type, final RefactoringStatus result) throws CoreException { class NestedException extends RuntimeException { private static final long serialVersionUID= 1L; NestedException(CoreException e) { super(e); } } ASTFlattener flattener= new ASTFlattener() { @Override public boolean visit(SimpleName node) { appendResolved(node.getIdentifier()); return false; } @Override public boolean visit(QualifiedName node) { appendResolved(node.getFullyQualifiedName()); return false; } @Override public boolean visit(QualifiedType node) { appendResolved(ASTNodes.getQualifiedTypeName(node)); return false; } @Override public boolean visit(NameQualifiedType node) { appendResolved(ASTNodes.getQualifiedTypeName(node)); return false; } private void appendResolved(String typeName) { String resolvedType; try { resolvedType= resolveType(typeName, result, fMethod.getDeclaringType(), null); } catch (CoreException e) { throw new NestedException(e); } this.fBuffer.append(resolvedType); } }; try { type.accept(flattener); } catch (NestedException e) { throw ((CoreException) e.getCause()); } return flattener.getResult(); } private static String resolveType(String elementTypeName, RefactoringStatus status, IType declaringType, IProgressMonitor pm) throws CoreException { String[][] fqns= declaringType.resolveType(elementTypeName); if (fqns != null) { if (fqns.length == 1) { return JavaModelUtil.concatenateName(fqns[0][0], fqns[0][1]); } else if (fqns.length > 1){ String[] keys= { BasicElementLabels.getJavaElementName(elementTypeName), String.valueOf(fqns.length)}; String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_ambiguous, keys); status.addError(msg); return elementTypeName; } } List<TypeNameMatch> typeRefsFound= findTypeInfos(elementTypeName, declaringType, pm); if (typeRefsFound.size() == 0){ String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_not_unique, BasicElementLabels.getJavaElementName(elementTypeName)); status.addError(msg); return elementTypeName; } else if (typeRefsFound.size() == 1){ TypeNameMatch typeInfo= typeRefsFound.get(0); return typeInfo.getFullyQualifiedName(); } else { Assert.isTrue(typeRefsFound.size() > 1); String[] keys= {BasicElementLabels.getJavaElementName(elementTypeName), String.valueOf(typeRefsFound.size())}; String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_ambiguous, keys); status.addError(msg); return elementTypeName; } } private static List<TypeNameMatch> findTypeInfos(String typeName, IType contextType, IProgressMonitor pm) throws JavaModelException { IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[]{contextType.getJavaProject()}, true); IPackageFragment currPackage= contextType.getPackageFragment(); ArrayList<TypeNameMatch> collectedInfos= new ArrayList<>(); TypeNameMatchCollector requestor= new TypeNameMatchCollector(collectedInfos); int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; new SearchEngine().searchAllTypeNames(null, matchMode, typeName.toCharArray(), matchMode, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, pm); List<TypeNameMatch> result= new ArrayList<>(); for (Iterator<TypeNameMatch> iter= collectedInfos.iterator(); iter.hasNext();) { TypeNameMatch curr= iter.next(); IType type= curr.getType(); if (type != null) { boolean visible=true; try { visible= JavaModelUtil.isVisible(type, currPackage); } catch (JavaModelException e) { //Assume visibile if not available } if (visible) { result.add(curr); } } } return result; } } private static class MethodTypesSyntaxChecker { private final IMethod fMethod; private final List<ParameterInfo> fParameterInfos; private final ReturnTypeInfo fReturnTypeInfo; public MethodTypesSyntaxChecker(IMethod method, List<ParameterInfo> parameterInfos, ReturnTypeInfo returnTypeInfo) { fMethod= method; fParameterInfos= parameterInfos; fReturnTypeInfo= returnTypeInfo; } public RefactoringStatus[] checkSyntax() { int parameterCount= fParameterInfos.size(); RefactoringStatus[] results= new RefactoringStatus[parameterCount + 1]; results[parameterCount]= checkReturnTypeSyntax(); for (int i= 0; i < parameterCount; i++) { ParameterInfo info= fParameterInfos.get(i); if (!info.isDeleted()) results[i]= checkParameterTypeSyntax(info); } return results; } private RefactoringStatus checkParameterTypeSyntax(ParameterInfo info) { if (!info.isAdded() && !info.isTypeNameChanged() && !info.isDeleted()) return null; return TypeContextChecker.checkParameterTypeSyntax(info.getNewTypeName(), fMethod.getJavaProject()); } private RefactoringStatus checkReturnTypeSyntax() { String newTypeName= fReturnTypeInfo.getNewTypeName(); if ("".equals(newTypeName.trim())) { //$NON-NLS-1$ String msg= RefactoringCoreMessages.TypeContextChecker_return_type_not_empty; return RefactoringStatus.createFatalErrorStatus(msg); } List<String> problemsCollector= new ArrayList<>(0); Type parsedType= parseType(newTypeName, fMethod.getJavaProject(), problemsCollector); if (parsedType == null) { String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_return_type, BasicElementLabels.getJavaElementName(newTypeName)); return RefactoringStatus.createFatalErrorStatus(msg); } if (problemsCollector.size() == 0) return null; RefactoringStatus result= new RefactoringStatus(); for (Iterator<String> iter= problemsCollector.iterator(); iter.hasNext();) { String[] keys= new String[]{ BasicElementLabels.getJavaElementName(newTypeName), BasicElementLabels.getJavaElementName(iter.next())}; String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_return_type_syntax, keys); result.addError(msg); } return result; } private static boolean isVoidArrayType(Type type){ if (! type.isArrayType()) return false; ArrayType arrayType= (ArrayType)type; if (! arrayType.getElementType().isPrimitiveType()) return false; PrimitiveType primitiveType= (PrimitiveType) arrayType.getElementType(); return (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID); } } private static Type parseType(String typeString, IJavaProject javaProject, List<String> problemsCollector) { if ("".equals(typeString.trim())) //speed up for a common case //$NON-NLS-1$ return null; if (! typeString.trim().equals(typeString)) return null; StringBuffer cuBuff= new StringBuffer(); cuBuff.append("interface A{"); //$NON-NLS-1$ int offset= cuBuff.length(); cuBuff.append(typeString).append(" m();}"); //$NON-NLS-1$ ASTParser p= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); p.setSource(cuBuff.toString().toCharArray()); p.setProject(javaProject); CompilationUnit cu= (CompilationUnit) p.createAST(null); Selection selection= Selection.createFromStartLength(offset, typeString.length()); SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false); cu.accept(analyzer); ASTNode selected= analyzer.getFirstSelectedNode(); if (!(selected instanceof Type)) return null; Type type= (Type)selected; if (MethodTypesSyntaxChecker.isVoidArrayType(type)) return null; IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS); if (problems.length > 0) { for (int i= 0; i < problems.length; i++) problemsCollector.add(problems[i].getMessage()); } String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type)); if (typeString.equals(typeNodeRange)) return type; else return null; } private static ITypeBinding handleBug84585(ITypeBinding typeBinding) { if (typeBinding == null) return null; else if (typeBinding.isGenericType() && ! typeBinding.isRawType() && ! typeBinding.isParameterizedType()) return null; //see bug 84585 else return typeBinding; } public static RefactoringStatus[] checkAndResolveMethodTypes(IMethod method, StubTypeContext stubTypeContext, List<ParameterInfo> parameterInfos, ReturnTypeInfo returnTypeInfo) throws CoreException { MethodTypesChecker checker= new MethodTypesChecker(method, stubTypeContext, parameterInfos, returnTypeInfo); return checker.checkAndResolveMethodTypes(); } public static RefactoringStatus[] checkMethodTypesSyntax(IMethod method, List<ParameterInfo> parameterInfos, ReturnTypeInfo returnTypeInfo) { MethodTypesSyntaxChecker checker= new MethodTypesSyntaxChecker(method, parameterInfos, returnTypeInfo); return checker.checkSyntax(); } public static RefactoringStatus checkParameterTypeSyntax(String type, IJavaProject project) { String newTypeName= ParameterInfo.stripEllipsis(type.trim()).trim(); String typeLabel= BasicElementLabels.getJavaElementName(type); if ("".equals(newTypeName.trim())){ //$NON-NLS-1$ String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_parameter_type, typeLabel); return RefactoringStatus.createFatalErrorStatus(msg); } if (ParameterInfo.isVarargs(type) && ! JavaModelUtil.is50OrHigher(project)) { String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_no_vararg_below_50, typeLabel); return RefactoringStatus.createFatalErrorStatus(msg); } List<String> problemsCollector= new ArrayList<>(0); Type parsedType= parseType(newTypeName, project, problemsCollector); boolean valid= parsedType != null; if (valid && parsedType instanceof PrimitiveType) valid= ! PrimitiveType.VOID.equals(((PrimitiveType) parsedType).getPrimitiveTypeCode()); if (! valid) { String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_type_name, BasicElementLabels.getJavaElementName(newTypeName)); return RefactoringStatus.createFatalErrorStatus(msg); } if (problemsCollector.size() == 0) return null; RefactoringStatus result= new RefactoringStatus(); for (Iterator<String> iter= problemsCollector.iterator(); iter.hasNext();) { String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_type_syntax, new String[]{BasicElementLabels.getJavaElementName(newTypeName), BasicElementLabels.getJavaElementName(iter.next())}); result.addError(msg); } return result; } public static StubTypeContext createStubTypeContext(ICompilationUnit cu, CompilationUnit root, int focalPosition) throws CoreException { StringBuffer bufBefore= new StringBuffer(); StringBuffer bufAfter= new StringBuffer(); int introEnd= 0; PackageDeclaration pack= root.getPackage(); if (pack != null) introEnd= pack.getStartPosition() + pack.getLength(); List<ImportDeclaration> imports= root.imports(); if (imports.size() > 0) { ImportDeclaration lastImport= imports.get(imports.size() - 1); introEnd= lastImport.getStartPosition() + lastImport.getLength(); } bufBefore.append(cu.getBuffer().getText(0, introEnd)); fillWithTypeStubs(bufBefore, bufAfter, focalPosition, root.types()); bufBefore.append(' '); bufAfter.insert(0, ' '); return new StubTypeContext(cu, bufBefore.toString(), bufAfter.toString()); } private static void fillWithTypeStubs(final StringBuffer bufBefore, final StringBuffer bufAfter, final int focalPosition, List<? extends BodyDeclaration> types) { StringBuffer buf; for (Iterator<? extends BodyDeclaration> iter= types.iterator(); iter.hasNext();) { BodyDeclaration bodyDeclaration= iter.next(); if (! (bodyDeclaration instanceof AbstractTypeDeclaration)) { //account for local classes: if (! (bodyDeclaration instanceof MethodDeclaration)) continue; int bodyStart= bodyDeclaration.getStartPosition(); int bodyEnd= bodyDeclaration.getStartPosition() + bodyDeclaration.getLength(); if (! (bodyStart < focalPosition && focalPosition < bodyEnd)) continue; MethodDeclaration methodDeclaration= (MethodDeclaration) bodyDeclaration; buf= bufBefore; appendModifiers(buf, methodDeclaration.modifiers()); appendTypeParameters(buf, methodDeclaration.typeParameters()); buf.append(" void "); //$NON-NLS-1$ buf.append(methodDeclaration.getName().getIdentifier()); buf.append("(){\n"); //$NON-NLS-1$ Block body= methodDeclaration.getBody(); body.accept(new HierarchicalASTVisitor() { @Override public boolean visit(AbstractTypeDeclaration node) { fillWithTypeStubs(bufBefore, bufAfter, focalPosition, Collections.singletonList(node)); return false; } @Override public boolean visit(ClassInstanceCreation node) { AnonymousClassDeclaration anonDecl= node.getAnonymousClassDeclaration(); if (anonDecl == null) return true; // could be in CIC parameter list int anonStart= anonDecl.getStartPosition(); int anonEnd= anonDecl.getStartPosition() + anonDecl.getLength(); if (! (anonStart < focalPosition && focalPosition < anonEnd)) return false; bufBefore.append(" new "); //$NON-NLS-1$ bufBefore.append(node.getType().toString()); bufBefore.append("(){\n"); //$NON-NLS-1$ fillWithTypeStubs(bufBefore, bufAfter, focalPosition, anonDecl.bodyDeclarations()); bufAfter.append("};\n"); //$NON-NLS-1$ return false; } }); buf= bufAfter; buf.append("}\n"); //$NON-NLS-1$ continue; } AbstractTypeDeclaration decl= (AbstractTypeDeclaration) bodyDeclaration; buf= decl.getStartPosition() < focalPosition ? bufBefore : bufAfter; appendModifiers(buf, decl.modifiers()); if (decl instanceof TypeDeclaration) { TypeDeclaration type= (TypeDeclaration) decl; buf.append(type.isInterface() ? "interface " : "class "); //$NON-NLS-1$//$NON-NLS-2$ buf.append(type.getName().getIdentifier()); appendTypeParameters(buf, type.typeParameters()); if (type.getSuperclassType() != null) { buf.append(" extends "); //$NON-NLS-1$ buf.append(ASTNodes.asString(type.getSuperclassType())); } List<Type> superInterfaces= type.superInterfaceTypes(); appendSuperInterfaces(buf, superInterfaces); } else if (decl instanceof AnnotationTypeDeclaration) { AnnotationTypeDeclaration annotation= (AnnotationTypeDeclaration) decl; buf.append("@interface "); //$NON-NLS-1$ buf.append(annotation.getName().getIdentifier()); } else if (decl instanceof EnumDeclaration) { EnumDeclaration enumDecl= (EnumDeclaration) decl; buf.append("enum "); //$NON-NLS-1$ buf.append(enumDecl.getName().getIdentifier()); List<Type> superInterfaces= enumDecl.superInterfaceTypes(); appendSuperInterfaces(buf, superInterfaces); } buf.append("{\n"); //$NON-NLS-1$ if (decl instanceof EnumDeclaration) buf.append(";\n"); //$NON-NLS-1$ fillWithTypeStubs(bufBefore, bufAfter, focalPosition, decl.bodyDeclarations()); buf= decl.getStartPosition() + decl.getLength() < focalPosition ? bufBefore : bufAfter; buf.append("}\n"); //$NON-NLS-1$ } } private static void appendTypeParameters(StringBuffer buf, List<TypeParameter> typeParameters) { int typeParametersCount= typeParameters.size(); if (typeParametersCount > 0) { buf.append('<'); for (int i= 0; i < typeParametersCount; i++) { TypeParameter typeParameter= typeParameters.get(i); buf.append(ASTNodes.asString(typeParameter)); if (i < typeParametersCount - 1) buf.append(','); } buf.append('>'); } } private static void appendModifiers(StringBuffer buf, List<IExtendedModifier> modifiers) { for (Iterator<IExtendedModifier> iterator= modifiers.iterator(); iterator.hasNext();) { IExtendedModifier extendedModifier= iterator.next(); if (extendedModifier.isModifier()) { Modifier modifier= (Modifier) extendedModifier; buf.append(modifier.getKeyword().toString()).append(' '); } } } private static void appendSuperInterfaces(StringBuffer buf, List<Type> superInterfaces) { int superInterfaceCount= superInterfaces.size(); if (superInterfaceCount > 0) { buf.append(" implements "); //$NON-NLS-1$ for (int i= 0; i < superInterfaceCount; i++) { Type superInterface= superInterfaces.get(i); buf.append(ASTNodes.asString(superInterface)); if (i < superInterfaceCount - 1) buf.append(','); } } } public static StubTypeContext createSuperInterfaceStubTypeContext(String typeName, IType enclosingType, IPackageFragment packageFragment) { return createSupertypeStubTypeContext(typeName, true, enclosingType, packageFragment); } public static StubTypeContext createSuperClassStubTypeContext(String typeName, IType enclosingType, IPackageFragment packageFragment) { return createSupertypeStubTypeContext(typeName, false, enclosingType, packageFragment); } private static StubTypeContext createSupertypeStubTypeContext(String typeName, boolean isInterface, IType enclosingType, IPackageFragment packageFragment) { StubTypeContext stubTypeContext; String prolog= "class " + typeName + (isInterface ? " implements " : " extends "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String epilog= " {} "; //$NON-NLS-1$ if (enclosingType != null) { try { ICompilationUnit cu= enclosingType.getCompilationUnit(); ISourceRange typeSourceRange= enclosingType.getSourceRange(); int focalPosition= typeSourceRange.getOffset() + typeSourceRange.getLength() - 1; // before closing brace ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(cu); parser.setFocalPosition(focalPosition); CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null); stubTypeContext= createStubTypeContext(cu, compilationUnit, focalPosition); stubTypeContext= new StubTypeContext(stubTypeContext.getCuHandle(), stubTypeContext.getBeforeString() + prolog, epilog + stubTypeContext.getAfterString()); } catch (CoreException e) { JavaPlugin.log(e); stubTypeContext= new StubTypeContext(null, null, null); } } else if (packageFragment != null) { ICompilationUnit cu= packageFragment.getCompilationUnit(JavaTypeCompletionProcessor.DUMMY_CU_NAME); stubTypeContext= new StubTypeContext(cu, "package " + packageFragment.getElementName() + ";" + prolog, epilog); //$NON-NLS-1$//$NON-NLS-2$ } else { stubTypeContext= new StubTypeContext(null, null, null); } return stubTypeContext; } public static StubTypeContext createAnnotationStubTypeContext(/*@NonNull*/ IProject project) { try { for (IPackageFragmentRoot root : JavaCore.create(project).getPackageFragmentRoots()) { if (!root.isReadOnly()) { IPackageFragment packageFragment= root.getPackageFragment(""); //$NON-NLS-1$ String prolog= "abstract class __X__ {\n\tabstract @"; //$NON-NLS-1$ String epilog= " __X__ dummy();\n} "; //$NON-NLS-1$ ICompilationUnit cu= packageFragment.getCompilationUnit(JavaTypeCompletionProcessor.DUMMY_CU_NAME); return new StubTypeContext(cu, prolog, epilog); } } } catch (JavaModelException e) { // fall through } return new StubTypeContext(null, null, null); } public static Type parseSuperClass(String superClass) { return parseSuperType(superClass, false); } public static Type parseSuperInterface(String superInterface) { return parseSuperType(superInterface, true); } private static Type parseSuperType(String superType, boolean isInterface) { if (! superType.trim().equals(superType)) { return null; } StringBuffer cuBuff= new StringBuffer(); if (isInterface) cuBuff.append("class __X__ implements "); //$NON-NLS-1$ else cuBuff.append("class __X__ extends "); //$NON-NLS-1$ int offset= cuBuff.length(); cuBuff.append(superType).append(" {}"); //$NON-NLS-1$ ASTParser p= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); p.setSource(cuBuff.toString().toCharArray()); Map<String, String> options= new HashMap<>(); JavaModelUtil.setComplianceOptions(options, JavaModelUtil.VERSION_LATEST); p.setCompilerOptions(options); CompilationUnit cu= (CompilationUnit) p.createAST(null); ASTNode selected= NodeFinder.perform(cu, offset, superType.length()); if (selected instanceof Name) selected= selected.getParent(); if (selected.getStartPosition() != offset || selected.getLength() != superType.length() || ! (selected instanceof Type) || selected instanceof PrimitiveType) { return null; } Type type= (Type) selected; String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type)); if (! superType.equals(typeNodeRange)){ return null; } return type; } public static ITypeBinding resolveSuperClass(String superclass, IType typeHandle, StubTypeContext superClassContext) { StringBuffer cuString= new StringBuffer(); cuString.append(superClassContext.getBeforeString()); cuString.append(superclass); cuString.append(superClassContext.getAfterString()); try { ICompilationUnit wc= typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor()); try { wc.getBuffer().setContents(cuString.toString()); CompilationUnit compilationUnit= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(wc, true); ASTNode type= NodeFinder.perform(compilationUnit, superClassContext.getBeforeString().length(), superclass.length()); if (type instanceof Type) { return handleBug84585(((Type) type).resolveBinding()); } else if (type instanceof Name) { ASTNode parent= type.getParent(); if (parent instanceof Type) return handleBug84585(((Type) parent).resolveBinding()); } throw new IllegalStateException(); } finally { wc.discardWorkingCopy(); } } catch (JavaModelException e) { return null; } } public static ITypeBinding[] resolveSuperInterfaces(String[] interfaces, IType typeHandle, StubTypeContext superInterfaceContext) { ITypeBinding[] result= new ITypeBinding[interfaces.length]; int[] interfaceOffsets= new int[interfaces.length]; StringBuffer cuString= new StringBuffer(); cuString.append(superInterfaceContext.getBeforeString()); int last= interfaces.length - 1; for (int i= 0; i <= last; i++) { interfaceOffsets[i]= cuString.length(); cuString.append(interfaces[i]); if (i != last) cuString.append(", "); //$NON-NLS-1$ } cuString.append(superInterfaceContext.getAfterString()); try { ICompilationUnit wc= typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor()); try { wc.getBuffer().setContents(cuString.toString()); CompilationUnit compilationUnit= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(wc, true); for (int i= 0; i <= last; i++) { ASTNode type= NodeFinder.perform(compilationUnit, interfaceOffsets[i], interfaces[i].length()); if (type instanceof Type) { result[i]= handleBug84585(((Type) type).resolveBinding()); } else if (type instanceof Name) { ASTNode parent= type.getParent(); if (parent instanceof Type) { result[i]= handleBug84585(((Type) parent).resolveBinding()); } else { throw new IllegalStateException(); } } else { throw new IllegalStateException(); } } } finally { wc.discardWorkingCopy(); } } catch (JavaModelException e) { // won't happen } return result; } }
epl-1.0
PDOK/geoserver-workspace-builder
src/main/java/nl/pdok/workspacebuilder/PdokBuilder.java
11992
package nl.pdok.workspacebuilder; import it.geosolutions.geoserver.rest.decoder.RESTCoverageList; import it.geosolutions.geoserver.rest.decoder.RESTFeatureTypeList; import it.geosolutions.geoserver.rest.decoder.RESTWorkspaceList; import it.geosolutions.geoserver.rest.encoder.service.GSServiceSettingsEncoder; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import nl.pdok.catalogus.Catalogus; import nl.pdok.workspacebuilder.exceptions.WorkspaceBuilderException; import nl.pdok.workspacebuilder.model.Service; import nl.pdok.workspacebuilder.model.ServiceInfo; import nl.pdok.workspacebuilder.model.datastore.Datastore; import nl.pdok.workspacebuilder.model.layer.Coverage; import nl.pdok.workspacebuilder.model.layer.GroupLayer; import nl.pdok.workspacebuilder.model.layer.Layer; import nl.pdok.workspacebuilder.model.layer.SingleLayer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to generate a geoserver configuration. * The configuration is generated via REST calls on a live geoserver. */ public class PdokBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(PdokBuilder.class); public static final String BASERASTERDIR = "//usr/data/rasters/"; public static final String METADATATYPE = "TC211"; public static final String METADATACODETYPE = "text/plain"; public static final String METADATABASEURL = "http://www.nationaalgeoregister.nl/geonetwork/srv/dut/xml.metadata.get?uuid="; @SuppressWarnings("unused") private Catalogus catalogus; public PdokBuilder(Catalogus catalogus) { this.catalogus = catalogus; } /** * Check if a workspace exists in geoserver with the given name. * * @return true is the workspace exists */ public boolean workSpaceExist(Service service, GeoserverRestProxy geoserverRestProxy) { String workspaceName = service.getWorkspaceName(); LOGGER.info(workspaceName + ":Check workspace exists"); for (RESTWorkspaceList.RESTShortWorkspace workspace : geoserverRestProxy.getReader().getWorkspaces()) { if (workspace.getName().equals(workspaceName)) { return true; } } return false; } /** * Deletes a workspace and all its content from the geoserver. */ public void removeWorkspace(Service service, GeoserverRestProxy geoserverRestProxy) { String workspaceName = service.getWorkspaceName(); if (workSpaceExist(service, geoserverRestProxy)) { LOGGER.info(workspaceName + ":Remove workspace"); boolean removed = geoserverRestProxy.getPublisher().removeWorkspace(workspaceName, true); if (!removed) { throw new RuntimeException("Error removing workspace " + workspaceName); } } } /** * Creates an empty workspace. */ public void createWorkspace(Service service, GeoserverRestProxy geoserverRestProxy) throws WorkspaceBuilderException { String workspaceName = service.getWorkspaceName(); LOGGER.info(workspaceName + ":Create workspace"); try { URI uri = new URI("http://" + workspaceName + ".geonovum.nl"); boolean created = geoserverRestProxy.getPublisher().createWorkspace(workspaceName, uri); if (!created) { throw new RuntimeException("Error creating workspace " + workspaceName); } } catch (URISyntaxException e) { LOGGER.error("Error creating URI for workspace: " + e.getMessage()); throw new WorkspaceBuilderException("Error creating URI for workspace."); } } public void createStores(Service service, GeoserverRestProxy geoserverRestProxy) { for (Datastore datastore : service.getDatastores()) { datastore.createDatastoreIfNotExists(service.getWorkspaceName(), geoserverRestProxy); } } public void createLayers(Service service, GeoserverRestProxy geoserverRestProxy) { LOGGER.info(service.getWorkspaceName() + ":Create Layers for service " + service.getTitle()); RESTFeatureTypeList availableFeatureTypes = geoserverRestProxy.getReader().getFeatureTypes(service.getWorkspaceName(), "available"); for (SingleLayer layer : service.getLayers()) { if (layer.featureExistsForLayer(service, availableFeatureTypes, geoserverRestProxy)) { layer.addLayerToGeoserver(service, geoserverRestProxy); LOGGER.info("Adding layer " + layer.getName() + " --> succeeded."); } else { LOGGER.info("Adding layer " + layer.getName() + " --> feature doesn't exist."); } } } public void createGroupLayer(Service service, GeoserverRestProxy geoserverRestProxy) { LOGGER.info(service.getWorkspaceName() + ":Create GroupLayers"); for (GroupLayer groupLayer : service.getGroupLayers()) { groupLayer.addLayerToGeoserver(service, geoserverRestProxy); } } public void createCoverages(Service service, GeoserverRestProxy geoserverRestProxy) { LOGGER.info(service.getWorkspaceName() + ":Create Coverages for service " + service.getTitle()); for (Coverage coverage : service.getCoverages()) { RESTCoverageList availableCoverages = geoserverRestProxy.getReader() .getCoverageNames(service.getWorkspaceName(), coverage.getDatastoreName(), "all"); if (coverage.featureExistsForCoverage(service, availableCoverages, geoserverRestProxy)) { coverage.addLayerToGeoserver(service, geoserverRestProxy); LOGGER.info("Adding coverage " + coverage.getName() + " --> succeeded."); } else { LOGGER.info("Adding coverage " + coverage.getName() + " --> coverage doesn't exist."); } } } public void createKaartConfig(Service service) { LOGGER.info("Creating kaartconfig: " + service.getWorkspaceName()); File configFile = new File("generated_files/kaart_config/" + service.getWorkspaceName() + ".xml"); try { FileWriter fw = new FileWriter(configFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for (ServiceInfo info : service.getServiceSettings()) { if (ServiceInfo.ServiceType.WMS == info.getType()) { for (Layer layer : service.getLayers()) { String id = service.getWorkspaceName() + "_" + layer.getName(); bw.write(" " + id.toUpperCase() + ": {\n"); bw.write(" " + "layertype: 'WMS',\n"); bw.write(" " + "name: '" + info.getTitle() + "',\n"); bw.write(" " + "url: 'http://geodata.nationaalgeoregister.nl/" + service.getWorkspaceName() + "/wms',\n"); bw.write(" " + "layers: '" + layer.getName() + "',\n"); bw.write(" " + "transparent: 'true',\n"); bw.write(" " + "format: 'image/png',\n"); bw.write(" " + "visibility: true,\n"); bw.write(" " + "isBaseLayer: false,\n"); bw.write(" " + "singleTile: true\n"); bw.write(" " + "},\n"); } } } bw.close(); } catch (IOException e) { e.printStackTrace(); } } public void createPdokViewerConfig(Service service, GeoserverRestProxy geoserverConfig) { LOGGER.info(service.getWorkspaceName() + ":Create viewer config"); File configFile = new File("generated_files/pdokviewer_config/" + service.getWorkspaceName() + ".xml"); try { FileWriter fw = new FileWriter(configFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write("<contextCollection xmlns=\"http://preview.pdok.nl/1.0\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\"http://preview.pdok.nl/1.0 config.xsd \">\n"); bw.write("\t<contextFolder>\n"); bw.write("\t\t<title>" + service.getTitle() + "</title>\n"); if (service.getGroupLayers() != null && service.getGroupLayers().size() > 0) { for (GroupLayer grouplayer : service.getGroupLayers()) { bw.write("\t<context>\n"); bw.write("\t\t<title>" + grouplayer.getTitle() + "</title>\n"); for (Layer layer : grouplayer.getLayers()) { printViewerLayer(layer, service.getWorkspaceName(), bw); } bw.write("\t</context>\n"); } } else { for (Layer layer : service.getLayers()) { printViewerLayer(layer, service.getWorkspaceName(), bw); } } bw.write("\t</contextFolder>\n"); bw.write("</contextCollection>"); bw.close(); } catch (IOException e) { e.printStackTrace(); } } public void createServiceSettings(Service service, GeoserverRestProxy geoserverConfig) { for (ServiceInfo info : service.getServiceSettings()) { String type = info.getType().toString(); if ("TMS".equals(type) || "WMTS".equals(type) || "WMSC".equals(type) || "ATOM".equals(type)) { LOGGER.info(service.getWorkspaceName() + ":Skipping " + type.toUpperCase() + " service"); continue; } LOGGER.info(service.getWorkspaceName() + ":Create " + type.toUpperCase() + " service"); GSServiceSettingsEncoder encoder = new GSServiceSettingsEncoder(type.toLowerCase(), info.getMetadata_id()); encoder.setTitle(info.getTitle()); encoder.setWorkspace(service.getWorkspaceName()); encoder.setAccessConstraints(info.getAccessConstraints()); encoder.setAbstract(info.getAbstract()); encoder.setFees(info.getFees()); encoder.setSrs(info.getSrs()); for (String keyword : info.getKeywords()) { encoder.addKeyword(keyword); } boolean published = geoserverConfig.getPublisher().publishServiceLayer(service.getWorkspaceName(), type.toLowerCase(), encoder); if (!published) { throw new RuntimeException( "Error publishing WcsServiceLayer of type '" + type + "' for " + info.getTitle()); } } } private void printViewerLayer(Layer layer, String service, BufferedWriter bw) throws IOException { bw.write("\t\t<wmsLayer>\n"); bw.write(" <title>" + layer.getTitle() + " [wms]" + "</title>\n"); bw.write(" <url>{baseUrl}" + service + "/wms?</url>\n"); bw.write(" <isBaseLayer>false</isBaseLayer>\n"); bw.write(" <opacity>1.0</opacity>\n"); bw.write(" <isTransparent>true</isTransparent>\n"); bw.write(" <isVisible>false</isVisible>\n"); //bw.write(" <maxResolution>53.76</maxResolution>\n"); bw.write(" <layers>" + layer.getName() + "</layers>\n"); bw.write(" <format>image/png</format>\n"); bw.write(" <featureInfoFormat>application/vnd.ogc.gml</featureInfoFormat>\n"); bw.write(" <isAlpha>true</isAlpha>\n"); bw.write(" <isSingleTile>true</isSingleTile>\n"); bw.write("\t\t</wmsLayer>\n"); } }
epl-1.0
soctrace-inria/framesoc.importers
fr.inria.soctrace.tools.importer.otf2/src/fr/inria/soctrace/tools/importer/otf2/input/Otf2InputComposite.java
2490
/******************************************************************************* * Copyright (c) 2012-2015 INRIA. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Generoso Pagano - initial API and implementation ******************************************************************************/ package fr.inria.soctrace.tools.importer.otf2.input; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import fr.inria.soctrace.framesoc.core.tools.model.IFramesocToolInput; import fr.inria.soctrace.framesoc.ui.input.DefaultImporterInputComposite; import fr.inria.soctrace.framesoc.ui.listeners.LaunchTextListener; /** * * @author "Generoso Pagano <generoso.pagano@inria.fr>" */ public class Otf2InputComposite extends DefaultImporterInputComposite { private Otf2Input input = new Otf2Input(); public Otf2InputComposite(Composite parent, int style) { super(parent, style); setLayout(new GridLayout(1, false)); final Button btnImportVariables = new Button(this, SWT.CHECK); btnImportVariables.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { input.setImportVariable(btnImportVariables.getSelection()); } }); btnImportVariables.setText("Import Variables"); btnImportVariables.setSelection(input.isImportVariable()); final Button btnParseHierarchy = new Button(this, SWT.CHECK); btnParseHierarchy.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { input.setParseHierarchy(btnParseHierarchy.getSelection()); } }); btnParseHierarchy.setText("Parse Hierarchy"); btnParseHierarchy.setSelection(input.isParseHierarchy()); // customize for single trace file traceFiles.setFileLabel("Trace file"); traceFiles.setFileDialogStyle(SWT.SINGLE); } @Override public IFramesocToolInput getToolInput() { String[] tokens = LaunchTextListener.getTokens(traceFileListener.getText()); if (tokens.length > 0) { input.setTraceFile(tokens[0]); } else { input.setTraceFile(""); } return input; } }
epl-1.0
loliveira/zone
server/resources/public/js/chat.js
3103
var Position = Backbone.Model.extend({ fetch: function() { var that = this; GMaps.geolocate({ success: function(position) { console.log("success"); that.set({position: position}); }, error: function(error) { console.log('Geolocation failed: '+ error.message); }, not_supported: function() { alert("Your browser does not support geolocation"); }, always: function() { console.log("geo done."); } }); }}); window.position = new Position; var PositionView = Backbone.View.extend({ id: "position", initialize: function() { this.listenTo(this.model, "change", this.render); }, render: function() { var p = this.model.get("position"); $("#longitude").text(p.coords.longitude); $("#latitude").text(p.coords.latitude); } }); //window.positionView = new PositionView({model: position}); var Chat = Backbone.Model.extend({ initialize: function(attributes, options) { var host = window.location.host; this.socket = new WebSocket("ws://" + host + "/ws"); var that = this; that.socket.onmessage = function(event) { console.log("onmessage"); console.log(event); that.set({msg: "open"}); } that.socket.onopen = function(event) { console.log("open...."); that.set({state: "open"}); } that.socket.onerror = function(event) { console.log("onerror"); console.log(event); } that.socket.onclose = function(event) { that.set({state: "close"}); } } }); window.chat = new Chat; var ChatView = Backbone.View.extend({ id: "messages", initialize: function() { this.listenTo(this.model, "change", this.render); this.listenTo(this.model, "state", this.onnewstate); }, onnewstate: function () { console.log("onnewstate"); console.log(onnewstate); }, render: function() { // console.log(arguments[0]); // console.log(arguments[1]); } }); window.chatView = new ChatView({model: chat}); function reconnect (callback) { if (window.socket) { window.socket.close(); } //window.socket = Chat(callback); } function sendChat () { var msg = $("#text").val(); var nick = $("#nick").val(); var data = JSON.stringify({msg: msg, nick: nick}); socket.send(data); } function sendPosition () { var data = JSON.stringify({coords: window.coords}); socket.send(data); } function UpdatePosition (position) { window.coords = {}; window.coords.latitude = position.coords.latitude; window.coords.longitude = position.coords.longitude; $("#longitude").text(window.coords.longitude); $("#latitude").text(window.coords.latitude); } function setOnline() { $("#status").text("online"); sendPosition(); } function setOffline() { $("#status").text("offline"); } // $("#messages").append("<li>"+ event.data + "</li>");
epl-1.0
boniatillo-com/PhaserEditor
source/v3/source/client/plugins/phasereditor2d.scene/ui/dialogs/NewSceneFileDialogExtension.ts
1203
namespace phasereditor2d.scene.ui.dialogs { export class NewSceneFileDialogExtension extends files.ui.dialogs.NewFileContentExtension { constructor() { super({ id: "phasereditor2d.scene.ui.wizards.NewSceneFileWizardExtension", wizardName: "Scene File", icon: ScenePlugin.getInstance().getIcon(ICON_GROUP), fileExtension: "scene", initialFileName: "Scene", fileContent: JSON.stringify({ sceneType: "Scene", displayList: [], meta: { app: "Phaser Editor 2D - Scene Editor", url: "https://phasereditor2d.com", contentType: scene.core.CONTENT_TYPE_SCENE } }) }); } getInitialFileLocation() { return super.findInitialFileLocationBasedOnContentType(scene.core.CONTENT_TYPE_SCENE); } } } /* `{ "sceneType": "Scene", "displayList": [], "meta": { } }` */
epl-1.0
IdeS2014OUAMI/DulceriaMaoli
src/com/tlamatini/test/DAOCompraTest.java
1172
package com.tlamatini.test; import static org.junit.Assert.*; import java.sql.Date; import java.util.ArrayList; import com.tlamatini.datos.ConexionDB; import com.tlamatini.modelo.Compra; import com.tlamatini.modelo.Producto; import com.tlamatini.modelo.Venta; import com.tlamatini.persistencia.*; import org.junit.Test; public class DAOCompraTest { int folio = 2, idUsuario = 1; ArrayList<Producto> productos=new ArrayList<Producto>(); double importe = 150.5; Date fechaOperacion= new Date(2014/02/02); String nick = "admin"; String nombreProveedor = "emp"; ConexionDB conexion = new ConexionDB(); boolean iconn = conexion.crearConexion(); DAOCompra daoCompra = new DAOCompra(conexion); Compra c = new Compra(fechaOperacion, idUsuario); Date fechaInicio = new Date(2014/01/01); Date fechaFin = new Date(2015/01/01); private Compra[] compraTempArreglo = new Compra[daoCompra.buscaCompra(fechaInicio, fechaFin).length]; @Test public void testAgregaCompra() { assertTrue(daoCompra.agregaCompra(c)); } @Test public void testBuscaCompra() { assertEquals(compraTempArreglo.length,daoCompra.buscaCompra(fechaInicio, fechaFin).length); } }
epl-1.0
idserda/openhab
bundles/binding/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/bridge/VeluxBridgeGetProducts.java
2901
/** * Copyright (c) 2010-2019 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.velux.bridge; import org.openhab.binding.velux.bridge.comm.BCgetProducts; import org.openhab.binding.velux.internal.config.VeluxBridgeConfiguration; import org.openhab.binding.velux.things.VeluxExistingProducts; import org.openhab.binding.velux.things.VeluxProduct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link VeluxBridgeGetProducts} represents a complete set of transactions * for retrieving of any available products into a structure {@link VeluxExistingProducts} * defined on the <B>Velux</B> bridge. * <P> * It therefore provides a method * <UL> * <LI>{@link VeluxBridgeGetProducts#getProducts} for retrieval of information. * </UL> * Any parameters are controlled by {@link VeluxBridgeConfiguration}. * * @see VeluxProduct * @see VeluxExistingProducts * * @author Guenther Schreiner - Initial contribution */ public class VeluxBridgeGetProducts { private final Logger logger = LoggerFactory.getLogger(VeluxBridgeGetProducts.class); /** * Login into bridge, retrieve all products and logout from bridge based * on a well-prepared environment of a {@link VeluxBridgeProvider}. The results * are stored within a public structure {@link org.openhab.binding.velux.things.VeluxExistingProducts * VeluxExistingProducts}. * * @param bridge Initialized Velux bridge handler. * @return <b>success</b> * of type boolean describing the overall result of this interaction. */ public boolean getProducts(VeluxBridgeProvider bridge) { logger.trace("getProducts() called."); BCgetProducts.Response response = bridge.bridgeCommunicate(new BCgetProducts()); if (response != null) { for (BCgetProducts.BCproduct product : response.getDevices()) { logger.trace("getProducts() found product {} (type {}).", product.getName(), product.getCategory()); VeluxProduct veluxProduct = new VeluxProduct(product); logger.trace("getProducts() storing product {}.", veluxProduct); if (!bridge.getExistingsProducts().isRegistered(veluxProduct)) { bridge.getExistingsProducts().register(veluxProduct); } } logger.debug("getProducts() finally has found products {}.", bridge.getExistingsProducts()); return true; } else { logger.trace("getProducts() finished with failure."); return false; } } } /** * end-of-bridge/VeluxBridgeGetProducts.java */
epl-1.0
ProbonoBonobo/reg-machine
resources/public/cljs/tests/out/quil/util.js
8356
// Compiled by ClojureScript 1.9.293 {} goog.provide('quil.util'); goog.require('cljs.core'); goog.require('clojure.string'); /** * Function that does nothing. */ quil.util.no_fn = (function quil$util$no_fn(){ return null; }); /** * Returns the val associated with key in mappings or key directly if it * is one of the vals in mappings. Otherwise throws an exception. */ quil.util.resolve_constant_key = (function quil$util$resolve_constant_key(key,mappings){ if(cljs.core.truth_(cljs.core.get.call(null,mappings,key))){ return cljs.core.get.call(null,mappings,key); } else { if(cljs.core.truth_(cljs.core.some.call(null,cljs.core.PersistentHashSet.fromArray([key], true),cljs.core.vals.call(null,mappings)))){ return key; } else { throw (new Error([cljs.core.str("Expecting a keyword, got: "),cljs.core.str(key),cljs.core.str(". Expected one of: "),cljs.core.str(cljs.core.vec.call(null,cljs.core.sort.call(null,cljs.core.keys.call(null,mappings))))].join(''))); } } }); /** * Returns the length of the longest key of map m. Assumes m's keys are strings * and returns 0 if map is empty: * (length-of-longest-key {"foo" 1 "barr" 2 "bazzz" 3}) ;=> 5 * (length-of-longest-key {}) ;=> 0 */ quil.util.length_of_longest_key = (function quil$util$length_of_longest_key(m){ var or__6543__auto__ = cljs.core.last.call(null,cljs.core.sort.call(null,cljs.core.map.call(null,(function (p1__66959_SHARP_){ return p1__66959_SHARP_.length(); }),cljs.core.keys.call(null,m)))); if(cljs.core.truth_(or__6543__auto__)){ return or__6543__auto__; } else { return (0); } }); /** * Generates a padding string starting concatting s with len times pad: * (gen-padding "" 5 "b") ;=> "bbbbb" * May be called without starting string s in which case it defaults to the * empty string and also without pad in which case it defaults to a single space */ quil.util.gen_padding = (function quil$util$gen_padding(var_args){ var args66960 = []; var len__7651__auto___66963 = arguments.length; var i__7652__auto___66964 = (0); while(true){ if((i__7652__auto___66964 < len__7651__auto___66963)){ args66960.push((arguments[i__7652__auto___66964])); var G__66965 = (i__7652__auto___66964 + (1)); i__7652__auto___66964 = G__66965; continue; } else { } break; } var G__66962 = args66960.length; switch (G__66962) { case 1: return quil.util.gen_padding.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return quil.util.gen_padding.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return quil.util.gen_padding.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args66960.length)].join(''))); } }); quil.util.gen_padding.cljs$core$IFn$_invoke$arity$1 = (function (len){ return quil.util.gen_padding.call(null,"",len," "); }); quil.util.gen_padding.cljs$core$IFn$_invoke$arity$2 = (function (len,pad){ return quil.util.gen_padding.call(null,"",len,pad); }); quil.util.gen_padding.cljs$core$IFn$_invoke$arity$3 = (function (s,len,pad){ if((len > (0))){ return quil.util.gen_padding.call(null,[cljs.core.str(s),cljs.core.str(pad)].join(''),(len - (1)),pad); } else { return s; } }); quil.util.gen_padding.cljs$lang$maxFixedArity = 3; quil.util.print_definition_list = (function quil$util$print_definition_list(definitions){ var longest_key = quil.util.length_of_longest_key.call(null,definitions); return cljs.core.dorun.call(null,cljs.core.map.call(null,((function (longest_key){ return (function (p__66971){ var vec__66972 = p__66971; var k = cljs.core.nth.call(null,vec__66972,(0),null); var v = cljs.core.nth.call(null,vec__66972,(1),null); var len = k.length(); var diff = (longest_key - len); var pad = quil.util.gen_padding.call(null,diff); return cljs.core.println.call(null,k,pad,"- ",v); });})(longest_key)) ,definitions)); }); quil.util.clj_compilation_QMARK_ = (function quil$util$clj_compilation_QMARK_(){ return false; }); quil.util.prepare_quil_name = (function quil$util$prepare_quil_name(const_keyword){ return clojure.string.replace.call(null,clojure.string.upper_case.call(null,cljs.core.name.call(null,const_keyword)),/-/,"_"); }); quil.util.prepare_quil_clj_constants = (function quil$util$prepare_quil_clj_constants(constants){ return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,(function (p1__66975_SHARP_){ return (new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,[p1__66975_SHARP_,cljs.core.symbol.call(null,[cljs.core.str("PConstants/"),cljs.core.str(quil.util.prepare_quil_name.call(null,p1__66975_SHARP_))].join(''))],null)); }),constants)); }); quil.util.prepare_quil_cljs_constants = (function quil$util$prepare_quil_cljs_constants(constants){ return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,(function (p1__66976_SHARP_){ return (new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,[p1__66976_SHARP_,cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("cljs.core","aget","cljs.core/aget",6345791,null)),cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol("js","Processing.prototype.PConstants","js/Processing.prototype.PConstants",2034048972,null)),(function (){var x__7380__auto__ = quil.util.prepare_quil_name.call(null,p1__66976_SHARP_); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7380__auto__); })())))],null)); }),constants)); }); quil.util.make_quil_constant_map = (function quil$util$make_quil_constant_map(target,const_map_name,const_map){ return cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol(null,"def","def",597100991,null)),(function (){var x__7380__auto__ = const_map_name; return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7380__auto__); })(),(function (){var x__7380__auto__ = ((cljs.core._EQ_.call(null,target,new cljs.core.Keyword(null,"clj","clj",-660495428)))?quil.util.prepare_quil_clj_constants.call(null,const_map):quil.util.prepare_quil_cljs_constants.call(null,const_map)); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7380__auto__); })()))); }); quil.util.generate_quil_constants = (function quil$util$generate_quil_constants(var_args){ var args__7658__auto__ = []; var len__7651__auto___66982 = arguments.length; var i__7652__auto___66983 = (0); while(true){ if((i__7652__auto___66983 < len__7651__auto___66982)){ args__7658__auto__.push((arguments[i__7652__auto___66983])); var G__66984 = (i__7652__auto___66983 + (1)); i__7652__auto___66983 = G__66984; continue; } else { } break; } var argseq__7659__auto__ = ((((3) < args__7658__auto__.length))?(new cljs.core.IndexedSeq(args__7658__auto__.slice((3)),(0),null)):null); return quil.util.generate_quil_constants.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),argseq__7659__auto__); }); quil.util.generate_quil_constants.cljs$core$IFn$_invoke$arity$variadic = (function (_AMPERSAND_form,_AMPERSAND_env,target,opts){ return cljs.core.sequence.call(null,cljs.core.seq.call(null,cljs.core.concat.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,new cljs.core.Symbol(null,"do","do",1686842252,null)),cljs.core.map.call(null,(function (p1__66977_SHARP_){ return quil.util.make_quil_constant_map.call(null,target,cljs.core.first.call(null,p1__66977_SHARP_),cljs.core.second.call(null,p1__66977_SHARP_)); }),cljs.core.partition.call(null,(2),opts))))); }); quil.util.generate_quil_constants.cljs$lang$maxFixedArity = (3); quil.util.generate_quil_constants.cljs$lang$applyTo = (function (seq66978){ var G__66979 = cljs.core.first.call(null,seq66978); var seq66978__$1 = cljs.core.next.call(null,seq66978); var G__66980 = cljs.core.first.call(null,seq66978__$1); var seq66978__$2 = cljs.core.next.call(null,seq66978__$1); var G__66981 = cljs.core.first.call(null,seq66978__$2); var seq66978__$3 = cljs.core.next.call(null,seq66978__$2); return quil.util.generate_quil_constants.cljs$core$IFn$_invoke$arity$variadic(G__66979,G__66980,G__66981,seq66978__$3); }); quil.util.generate_quil_constants.cljs$lang$macro = true; //# sourceMappingURL=util.js.map?rel=1479783854512
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/employee/EmployeeBasicTestModel.java
14964
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.employee; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.queries.Call; import org.eclipse.persistence.queries.SQLCall; import org.eclipse.persistence.tools.schemaframework.PopulationManager; import org.eclipse.persistence.testing.framework.*; import org.eclipse.persistence.testing.models.employee.domain.*; import org.eclipse.persistence.testing.models.employee.relational.EmployeeSystem; /** * This model tests reading/writing/deleting through using the employee demo. */ public class EmployeeBasicTestModel extends TestModel { /** * Return the JUnit suite to allow JUnit runner to find it. * Unfortunately JUnit only allows suite methods to be static, * so it is not possible to generically do this. */ public static junit.framework.TestSuite suite() { return new EmployeeBasicTestModel(); } public EmployeeBasicTestModel() { setDescription("This model tests reading/writing/deleting using the employee demo."); } public EmployeeBasicTestModel(boolean isSRG) { this(); this.isSRG = isSRG; } public void addRequiredSystems() { addRequiredSystem(new EmployeeSystem()); } public void addTests() { addTest(getReadObjectTestSuite()); addTest(getUpdateObjectTestSuite()); addTest(getInsertObjectTestSuite()); addTest(getDeleteObjectTestSuite()); addTest(getReadAllTestSuite()); addTest(getMiscTestSuite()); } //SRG test set is maintained by QA only, do NOT add any new tests into it. public void addSRGTests() { addTest(getSRGReadObjectTestSuite()); addTest(getSRGUpdateObjectTestSuite()); addTest(getSRGInsertObjectTestSuite()); addTest(getSRGDeleteObjectTestSuite()); addTest(getSRGReadAllTestSuite()); addTest(getSRGMiscTestSuite()); } public static TestSuite getDeleteObjectTestSuite() { TestSuite suite = getSRGDeleteObjectTestSuite(); //Add new tests here ... return suite; } //SRG test set is maintained by QA only, do NOT add any new tests into it. public static TestSuite getSRGDeleteObjectTestSuite() { TestSuite suite = new TestSuite(); suite.setName("EmployeeDeleteObjectTestSuite"); suite.setDescription("This suite tests the deletion of each object in the employee demo."); Class employeeClass = org.eclipse.persistence.testing.models.employee.domain.Employee.class; Class largeProjectClass = org.eclipse.persistence.testing.models.employee.domain.LargeProject.class; Class smallProjectClass = org.eclipse.persistence.testing.models.employee.domain.SmallProject.class; PopulationManager manager = PopulationManager.getDefaultManager(); suite.addTest(new EmployeeDeleteTest(manager.getObject(employeeClass, "0001"))); suite.addTest(new EmployeeDeleteTest(manager.getObject(employeeClass, "0002"))); suite.addTest(new EmployeeDeleteTest(manager.getObject(employeeClass, "0003"))); suite.addTest(new EmployeeDeleteTest(manager.getObject(employeeClass, "0004"))); suite.addTest(new EmployeeDeleteTest(manager.getObject(employeeClass, "0005"))); suite.addTest(new ProjectDeleteTest(manager.getObject(smallProjectClass, "0001"))); suite.addTest(new ProjectDeleteTest(manager.getObject(smallProjectClass, "0002"))); suite.addTest(new ProjectDeleteTest(manager.getObject(smallProjectClass, "0003"))); suite.addTest(new ProjectDeleteTest(manager.getObject(largeProjectClass, "0001"))); suite.addTest(new ProjectDeleteTest(manager.getObject(largeProjectClass, "0002"))); suite.addTest(new ProjectDeleteTest(manager.getObject(largeProjectClass, "0003"))); return suite; } public static TestSuite getInsertObjectTestSuite() { TestSuite suite = getSRGInsertObjectTestSuite(); //Add new tests here ... return suite; } //SRG test set is maintained by QA only, do NOT add any new tests into it. public static TestSuite getSRGInsertObjectTestSuite() { TestSuite suite = new TestSuite(); suite.setName("EmployeeInsertObjectTestSuite"); suite.setDescription("This suite tests the insertion of each object in the employee demo."); org.eclipse.persistence.testing.models.employee.domain.EmployeePopulator system = new org.eclipse.persistence.testing.models.employee.domain.EmployeePopulator(); suite.addTest(new InsertObjectTest(system.basicEmployeeExample1())); suite.addTest(new InsertObjectTest(system.basicEmployeeExample2())); suite.addTest(new InsertObjectTest(system.basicEmployeeExample3())); suite.addTest(new InsertObjectTest(system.basicEmployeeExample4())); suite.addTest(new InsertObjectTest(system.basicEmployeeExample5())); suite.addTest(new InsertObjectTest(system.basicSmallProjectExample1())); suite.addTest(new InsertObjectTest(system.basicSmallProjectExample2())); suite.addTest(new InsertObjectTest(system.basicSmallProjectExample3())); suite.addTest(new InsertObjectTest(system.basicLargeProjectExample1())); suite.addTest(new InsertObjectTest(system.basicLargeProjectExample2())); suite.addTest(new InsertObjectTest(system.basicLargeProjectExample3())); return suite; } public static TestSuite getReadAllTestSuite() { TestSuite suite = getSRGReadAllTestSuite(); //Add new tests here ... Expression orderBy = new ExpressionBuilder().get("firstName").ascending(); Call call = new SQLCall("SELECT t0.VERSION, t1.EMP_ID, t0.L_NAME, t0.F_NAME, t1.SALARY, t0.EMP_ID, t0.GENDER, t0.END_DATE, t0.START_DATE, t0.MANAGER_ID, t0.ADDR_ID FROM EMPLOYEE t0, SALARY t1 WHERE t1.EMP_ID = t0.EMP_ID"); suite.addTest(new ReadAllCallWithOrderingTest(org.eclipse.persistence.testing.models.employee.domain.Employee.class, 12, call, orderBy)); return suite; } //SRG test set is maintained by QA only, do NOT add any new tests into it. public static TestSuite getSRGReadAllTestSuite() { TestSuite suite = new TestSuite(); suite.setName("EmployeeReadAllTestSuite"); suite.setDescription("This suite tests the reading of all the objects of each class in the employee demo."); suite.addTest(new ReadAllTest(org.eclipse.persistence.testing.models.employee.domain.Employee.class, 12)); suite.addTest(new ReadAllTest(org.eclipse.persistence.testing.models.employee.domain.Project.class, 15)); suite.addTest(new ReadAllTest(org.eclipse.persistence.testing.models.employee.domain.LargeProject.class, 5)); suite.addTest(new ReadAllTest(org.eclipse.persistence.testing.models.employee.domain.SmallProject.class, 10)); suite.addTest(new ReadAllCallTest(org.eclipse.persistence.testing.models.employee.domain.Employee.class, 12, new SQLCall("SELECT t0.VERSION, t1.EMP_ID, t0.L_NAME, t0.F_NAME, t1.SALARY, t0.EMP_ID, t0.GENDER, t0.END_DATE, t0.START_DATE, t0.MANAGER_ID, t0.ADDR_ID FROM EMPLOYEE t0, SALARY t1 WHERE t1.EMP_ID = t0.EMP_ID"))); return suite; } public static TestSuite getReadObjectTestSuite() { TestSuite suite = getSRGReadObjectTestSuite(); //Add new tests here ... return suite; } //SRG test set is maintained by QA only, do NOT add any new tests into it. public static TestSuite getSRGReadObjectTestSuite() { TestSuite suite = new TestSuite(); suite.setName("EmployeeReadObjectTestSuite"); suite.setDescription("This suite test the reading of each object in the employee demo."); Class employeeClass = org.eclipse.persistence.testing.models.employee.domain.Employee.class; Class largeProjectClass = org.eclipse.persistence.testing.models.employee.domain.LargeProject.class; Class smallProjectClass = org.eclipse.persistence.testing.models.employee.domain.SmallProject.class; PopulationManager manager = PopulationManager.getDefaultManager(); suite.addTest(new ReadObjectTest(manager.getObject(employeeClass, "0001"))); suite.addTest(new ReadObjectTest(manager.getObject(employeeClass, "0002"))); suite.addTest(new ReadObjectTest(manager.getObject(employeeClass, "0003"))); suite.addTest(new ReadObjectTest(manager.getObject(employeeClass, "0004"))); suite.addTest(new ReadObjectTest(manager.getObject(employeeClass, "0005"))); Employee employee = (Employee)manager.getObject(employeeClass, "0001"); suite.addTest(new ReadObjectCallTest(employeeClass, new SQLCall("SELECT t0.VERSION, t1.EMP_ID, t0.L_NAME, t0.F_NAME, t1.SALARY, t0.EMP_ID, t0.GENDER, t0.END_DATE, t0.START_DATE, t0.MANAGER_ID, t0.END_TIME, t0.START_TIME, t0.ADDR_ID FROM EMPLOYEE t0, SALARY t1 WHERE t1.EMP_ID = t0.EMP_ID AND t0.F_NAME = '"+employee.getFirstName()+"' AND t0.L_NAME = '"+employee.getLastName()+"'"))); employee = (Employee)manager.getObject(employeeClass, "0002"); suite.addTest(new ReadObjectCallTest(employeeClass, new SQLCall("SELECT t0.VERSION, t1.EMP_ID, t0.L_NAME, t0.F_NAME, t1.SALARY, t0.EMP_ID, t0.GENDER, t0.END_DATE, t0.START_DATE, t0.MANAGER_ID, t0.END_TIME, t0.START_TIME, t0.ADDR_ID FROM EMPLOYEE t0, SALARY t1 WHERE t1.EMP_ID = t0.EMP_ID AND t0.F_NAME = '"+employee.getFirstName()+"' AND t0.L_NAME = '"+employee.getLastName()+"'"))); employee = (Employee)manager.getObject(employeeClass, "0003"); suite.addTest(new ReadObjectCallTest(employeeClass, new SQLCall("SELECT t0.VERSION, t1.EMP_ID, t0.L_NAME, t0.F_NAME, t1.SALARY, t0.EMP_ID, t0.GENDER, t0.END_DATE, t0.START_DATE, t0.MANAGER_ID, t0.END_TIME, t0.START_TIME, t0.ADDR_ID FROM EMPLOYEE t0, SALARY t1 WHERE t1.EMP_ID = t0.EMP_ID AND t0.F_NAME = '"+employee.getFirstName()+"' AND t0.L_NAME = '"+employee.getLastName()+"'"))); org.eclipse.persistence.testing.models.employee.domain.Project project = (org.eclipse.persistence.testing.models.employee.domain.Project)manager.getObject(largeProjectClass, "0001"); ReadObjectTest test = new ReadObjectTest(project); test.setQuery(new org.eclipse.persistence.queries.ReadObjectQuery(org.eclipse.persistence.testing.models.employee.domain.Project.class, new org.eclipse.persistence.expressions.ExpressionBuilder().get("id").equal(project.getId()))); suite.addTest(test); suite.addTest(new ReadObjectTest(manager.getObject(smallProjectClass, "0001"))); suite.addTest(new ReadObjectTest(manager.getObject(smallProjectClass, "0002"))); suite.addTest(new ReadObjectTest(manager.getObject(smallProjectClass, "0003"))); suite.addTest(new ReadObjectTest(manager.getObject(largeProjectClass, "0001"))); suite.addTest(new ReadObjectTest(manager.getObject(largeProjectClass, "0002"))); suite.addTest(new ReadObjectTest(manager.getObject(largeProjectClass, "0003"))); return suite; } public static TestSuite getUpdateObjectTestSuite() { TestSuite suite = getSRGUpdateObjectTestSuite(); //Add new tests here ... return suite; } //SRG test set is maintained by QA only, do NOT add any new tests into it. public static TestSuite getSRGUpdateObjectTestSuite() { TestSuite suite = new TestSuite(); suite.setName("EmployeeUpdateObjectTestSuite"); suite.setDescription("This suite tests the updating of each object in the employee demo."); Class employeeClass = org.eclipse.persistence.testing.models.employee.domain.Employee.class; Class largeProjectClass = org.eclipse.persistence.testing.models.employee.domain.LargeProject.class; Class smallProjectClass = org.eclipse.persistence.testing.models.employee.domain.SmallProject.class; PopulationManager manager = PopulationManager.getDefaultManager(); suite.addTest(new WriteObjectTest(manager.getObject(employeeClass, "0001"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(employeeClass, "0001"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(employeeClass, "0002"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(employeeClass, "0003"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(employeeClass, "0004"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(employeeClass, "0005"))); suite.addTest(new WriteObjectTest(manager.getObject(smallProjectClass, "0001"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(smallProjectClass, "0001"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(smallProjectClass, "0002"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(smallProjectClass, "0003"))); suite.addTest(new WriteObjectTest(manager.getObject(largeProjectClass, "0001"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(largeProjectClass, "0001"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(largeProjectClass, "0002"))); suite.addTest(new UnitOfWorkBasicUpdateObjectTest(manager.getObject(largeProjectClass, "0003"))); return suite; } public static TestSuite getMiscTestSuite() { TestSuite suite = getSRGMiscTestSuite(); //Add new tests here ... return suite; } //SRG test set is maintained by QA only, do NOT add any new tests into it. public static TestSuite getSRGMiscTestSuite() { TestSuite suite; suite = new TestSuite(); suite.setName("MiscellaneousTests"); suite.addTest(new AddDescriptorsTest()); return suite; } }
epl-1.0
OpenTM2/opentm2-source
Packages/include/xercesc/util/KVStringPair.hpp
7163
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: KVStringPair.hpp 554580 2007-07-09 09:09:51Z amassari $ */ #if !defined(XERCESC_INCLUDE_GUARD_KVSTRINGPAIR_HPP) #define XERCESC_INCLUDE_GUARD_KVSTRINGPAIR_HPP #include <xercesc/util/XMemory.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/internal/XSerializable.hpp> XERCES_CPP_NAMESPACE_BEGIN // // This class provides a commonly used data structure, which is that of // a pair of strings which represent a 'key=value' type mapping. It works // only in terms of XMLCh type raw strings. // class XMLUTIL_EXPORT KVStringPair : public XSerializable, public XMemory { public: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- KVStringPair(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); KVStringPair ( const XMLCh* const key , const XMLCh* const value , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); KVStringPair ( const XMLCh* const key , const XMLCh* const value , const XMLSize_t valueLength , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); KVStringPair ( const XMLCh* const key , const XMLSize_t keyLength , const XMLCh* const value , const XMLSize_t valueLength , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); KVStringPair(const KVStringPair& toCopy); ~KVStringPair(); // ----------------------------------------------------------------------- // Getters // // We support the // ----------------------------------------------------------------------- const XMLCh* getKey() const; XMLCh* getKey(); const XMLCh* getValue() const; XMLCh* getValue(); // ----------------------------------------------------------------------- // Setters // ----------------------------------------------------------------------- void setKey(const XMLCh* const newKey); void setValue(const XMLCh* const newValue); void setKey ( const XMLCh* const newKey , const XMLSize_t newKeyLength ); void setValue ( const XMLCh* const newValue , const XMLSize_t newValueLength ); void set ( const XMLCh* const newKey , const XMLCh* const newValue ); void set ( const XMLCh* const newKey , const XMLSize_t newKeyLength , const XMLCh* const newValue , const XMLSize_t newValueLength ); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(KVStringPair) private : // unimplemented: KVStringPair& operator=(const KVStringPair&); // ----------------------------------------------------------------------- // Private data members // // fKey // The string that represents the key field of this object. // // fKeyAllocSize // The amount of memory allocated for fKey. // // fValue // The string that represents the value of this pair object. // // fValueAllocSize // The amount of memory allocated for fValue. // // ----------------------------------------------------------------------- XMLSize_t fKeyAllocSize; XMLSize_t fValueAllocSize; XMLCh* fKey; XMLCh* fValue; MemoryManager* fMemoryManager; }; // --------------------------------------------------------------------------- // KVStringPair: Getters // --------------------------------------------------------------------------- inline const XMLCh* KVStringPair::getKey() const { return fKey; } inline XMLCh* KVStringPair::getKey() { return fKey; } inline const XMLCh* KVStringPair::getValue() const { return fValue; } inline XMLCh* KVStringPair::getValue() { return fValue; } // --------------------------------------------------------------------------- // KVStringPair: Setters // --------------------------------------------------------------------------- inline void KVStringPair::setKey(const XMLCh* const newKey) { setKey(newKey, XMLString::stringLen(newKey)); } inline void KVStringPair::setValue(const XMLCh* const newValue) { setValue(newValue, XMLString::stringLen(newValue)); } inline void KVStringPair::setKey( const XMLCh* const newKey , const XMLSize_t newKeyLength) { if (newKeyLength >= fKeyAllocSize) { fMemoryManager->deallocate(fKey); //delete [] fKey; fKey = 0; fKeyAllocSize = newKeyLength + 1; fKey = (XMLCh*) fMemoryManager->allocate(fKeyAllocSize * sizeof(XMLCh)); //new XMLCh[fKeyAllocSize]; } memcpy(fKey, newKey, (newKeyLength+1) * sizeof(XMLCh)); // len+1 because of the 0 at the end } inline void KVStringPair::setValue( const XMLCh* const newValue , const XMLSize_t newValueLength) { if (newValueLength >= fValueAllocSize) { fMemoryManager->deallocate(fValue); //delete [] fValue; fValue = 0; fValueAllocSize = newValueLength + 1; fValue = (XMLCh*) fMemoryManager->allocate(fValueAllocSize * sizeof(XMLCh)); //new XMLCh[fValueAllocSize]; } memcpy(fValue, newValue, (newValueLength+1) * sizeof(XMLCh)); // len+1 because of the 0 at the end } inline void KVStringPair::set( const XMLCh* const newKey , const XMLCh* const newValue) { setKey(newKey, XMLString::stringLen(newKey)); setValue(newValue, XMLString::stringLen(newValue)); } inline void KVStringPair::set( const XMLCh* const newKey , const XMLSize_t newKeyLength , const XMLCh* const newValue , const XMLSize_t newValueLength) { setKey(newKey, newKeyLength); setValue(newValue, newValueLength); } XERCES_CPP_NAMESPACE_END #endif
epl-1.0
xiaohanz/softcontroller
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java
14418
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.util.xml; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class XmlElement { public final Element element; private XmlElement(Element element) { this.element = element; } public static XmlElement fromDomElement(Element e) { return new XmlElement(e); } public static XmlElement fromDomDocument(Document xml) { return new XmlElement(xml.getDocumentElement()); } public static XmlElement fromString(String s) { try { return new XmlElement(XmlUtil.readXmlToElement(s)); } catch (IOException | SAXException e) { throw new IllegalArgumentException("Unable to create from " + s, e); } } public static XmlElement fromDomElementWithExpected(Element element, String expectedName) { XmlElement xmlElement = XmlElement.fromDomElement(element); xmlElement.checkName(expectedName); return xmlElement; } public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) { XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName); xmlElement.checkNamespace(expectedNamespace); return xmlElement; } private static Map<String, String> extractNamespaces(Element typeElement) { Map<String, String> namespaces = new HashMap<>(); NamedNodeMap attributes = typeElement.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String attribKey = attribute.getNodeName(); if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) { String prefix; if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) { prefix = ""; } else { Preconditions.checkState(attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")); prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1); } namespaces.put(prefix, attribute.getNodeValue()); } } return namespaces; } public void checkName(String expectedName) { Preconditions.checkArgument(getName().equals(expectedName), "Expected %s xml element but was %s", expectedName, getName()); } public void checkNamespaceAttribute(String expectedNamespace) { Preconditions.checkArgument(getNamespaceAttribute().equals(expectedNamespace), "Unexpected namespace %s for element %s, should be %s", getNamespaceAttribute(), expectedNamespace); } public void checkNamespace(String expectedNamespace) { Preconditions.checkArgument(getNamespace().equals(expectedNamespace), "Unexpected namespace %s for element %s, should be %s", getNamespace(), expectedNamespace); } public String getName() { if (element.getLocalName()!=null && !element.getLocalName().equals("")){ return element.getLocalName(); } return element.getTagName(); } public String getAttribute(String attributeName) { return element.getAttribute(attributeName); } public String getAttribute(String attributeName, String namespace) { return element.getAttributeNS(namespace, attributeName); } public NodeList getElementsByTagName(String name) { return element.getElementsByTagName(name); } public void appendChild(Element element) { this.element.appendChild(element); // Element newElement = (Element) element.cloneNode(true); // newElement.appendChild(configElement); // return XmlElement.fromDomElement(newElement); } public Element getDomElement() { return element; } public Map<String, Attr> getAttributes() { Map<String, Attr> mappedAttributes = Maps.newHashMap(); NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr) attributes.item(i); mappedAttributes.put(attr.getNodeName(), attr); } return mappedAttributes; } /** * Non recursive */ private List<XmlElement> getChildElementsInternal(ElementFilteringStrategy strat) { NodeList childNodes = element.getChildNodes(); final List<XmlElement> result = new ArrayList<>(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); if (item instanceof Element == false) continue; if (strat.accept((Element) item)) result.add(new XmlElement((Element) item)); } return result; } public List<XmlElement> getChildElements() { return getChildElementsInternal(new ElementFilteringStrategy() { @Override public boolean accept(Element e) { return true; } }); } public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) { return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace), new Predicate<XmlElement>() { @Override public boolean apply(@Nullable XmlElement xmlElement) { return xmlElement.getName().equals(childName); } })); } public List<XmlElement> getChildElementsWithinNamespace(final String namespace) { return getChildElementsInternal(new ElementFilteringStrategy() { @Override public boolean accept(Element e) { return XmlElement.fromDomElement(e).getNamespace().equals(namespace); } }); } public List<XmlElement> getChildElements(final String tagName) { return getChildElementsInternal(new ElementFilteringStrategy() { @Override public boolean accept(Element e) { return e.getTagName().equals(tagName); } }); } public XmlElement getOnlyChildElement(String childName) { List<XmlElement> nameElements = getChildElements(childName); Preconditions.checkState(nameElements.size() == 1, "One element " + childName + " expected in " + toString()); return nameElements.get(0); } public Optional<XmlElement> getOnlyChildElementOptionally(String childName) { try { return Optional.of(getOnlyChildElement(childName)); } catch (Exception e) { return Optional.absent(); } } public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) { try { return Optional.of(getOnlyChildElement(childName, namespace)); } catch (Exception e) { return Optional.absent(); } } public XmlElement getOnlyChildElementWithSameNamespace(String childName) { return getOnlyChildElement(childName, getNamespace()); } public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) { try { return Optional.of(getOnlyChildElement(childName, getNamespace())); } catch (Exception e) { return Optional.absent(); } } public XmlElement getOnlyChildElementWithSameNamespace() { XmlElement childElement = getOnlyChildElement(); childElement.checkNamespace(getNamespace()); return childElement; } public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() { try { XmlElement childElement = getOnlyChildElement(); childElement.checkNamespace(getNamespace()); return Optional.of(childElement); } catch (Exception e) { return Optional.absent(); } } public XmlElement getOnlyChildElement(final String childName, String namespace) { List<XmlElement> children = getChildElementsWithinNamespace(namespace); children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() { @Override public boolean apply(@Nullable XmlElement xmlElement) { return xmlElement.getName().equals(childName); } })); Preconditions.checkState(children.size() == 1, "One element %s:%s expected in %s but was %s", namespace, childName, toString(), children.size()); return children.get(0); } public XmlElement getOnlyChildElement() { List<XmlElement> children = getChildElements(); Preconditions.checkState(children.size() == 1, "One element expected in %s but was %s", toString(), children.size()); return children.get(0); } public String getTextContent() { Node textChild = element.getFirstChild(); Preconditions.checkState(textChild instanceof Text, getName() + " should contain text"); String content = textChild.getTextContent(); // Trim needed return content.trim(); } public String getNamespaceAttribute() { String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY); Preconditions.checkState(attribute != null && !attribute.equals(""), "Element %s must specify namespace", toString()); return attribute; } public String getNamespace() { String namespaceURI = element.getNamespaceURI(); Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this); return namespaceURI.toString(); } @Override public String toString() { final StringBuffer sb = new StringBuffer("XmlElement{"); sb.append("name='").append(getName()).append('\''); if (element.getNamespaceURI() != null) { sb.append(", namespace='").append(getNamespace()).append('\''); } sb.append('}'); return sb.toString(); } /** * Search for element's attributes defining namespaces. Look for the one * namespace that matches prefix of element's text content. E.g. * * <pre> * &lt;type * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl"&gt;th-java:threadfactory-naming&lt;/type&gt; * </pre> * * returns {"th-java","urn:.."}. If no prefix is matched, then default * namespace is returned with empty string as key. If no default namespace * is found value will be null. */ public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() { Map<String, String> namespaces = extractNamespaces(element); String textContent = getTextContent(); int indexOfColon = textContent.indexOf(":"); String prefix; if (indexOfColon > -1) { prefix = textContent.substring(0, indexOfColon); } else { prefix = ""; } if (namespaces.containsKey(prefix) == false) { throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is " + prefix + ". Found namespaces " + namespaces); } return Maps.immutableEntry(prefix, namespaces.get(prefix)); } public List<XmlElement> getChildElementsWithSameNamespace(final String childName) { List<XmlElement> children = getChildElementsWithinNamespace(getNamespace()); return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() { @Override public boolean apply(@Nullable XmlElement xmlElement) { return xmlElement.getName().equals(childName); } })); } public void checkUnrecognisedElements(List<XmlElement> recognisedElements, XmlElement... additionalRecognisedElements) { List<XmlElement> childElements = getChildElements(); childElements.removeAll(recognisedElements); for (XmlElement additionalRecognisedElement : additionalRecognisedElements) { childElements.remove(additionalRecognisedElement); } Preconditions.checkState(childElements.isEmpty(), "Unrecognised elements %s in %s", childElements, this); } public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) { checkUnrecognisedElements(Collections.<XmlElement> emptyList(), additionalRecognisedElements); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; XmlElement that = (XmlElement) o; if (!element.isEqualNode(that.element)) return false; return true; } @Override public int hashCode() { return element.hashCode(); } public boolean hasNamespace() { try { getNamespaceAttribute(); } catch (IllegalStateException e) { try { getNamespace(); } catch (IllegalStateException e1) { return false; } return true; } return true; } private static interface ElementFilteringStrategy { boolean accept(Element e); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/annotations/CompositeMember.java
2110
/******************************************************************************* * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * A CompositeMember annotation is ignored unless is in composite member persistence unit. * It may be used in conjunction with a ElementCollection and CollectionTable annotations. * It should be used if target type is a primitive type * and CollectionTable designates the table that belongs to * composite member persistence unit other than the source composite member persistence unit. * That allows the source and target to be mapped to different databases. * * @see javax.persistence.ElementCollection * @see javax.persistence.CollectionTable * @see org.eclipse.persistence.config.PersistenceUnitProperties#COMPOSITE_UNIT * * A CompositeMember can be specified on within an Entity, MappedSuperclass * and Embeddable class. * * @author Andrei Ilitchev * @since Eclipselink 2.3 **/ @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface CompositeMember { /** * The name of a target composite member persistence unit to which element table belongs (if differs from source composite member persistence unit) */ String value(); }
epl-1.0
vertig/tempo
security/src/test/java/org/intalio/tempo/test/SpringTestSupport.java
2059
/** * Copyright (c) 2005-2007 Intalio inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intalio inc. - initial API and implementation */ package org.intalio.tempo.test; import java.io.InputStream; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import junit.framework.TestCase; import junit.framework.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @version $Revision: 603 $ */ public abstract class SpringTestSupport { protected transient Logger _log = LoggerFactory.getLogger( getClass() ); protected AbstractXmlApplicationContext _context; protected void setUp() throws Exception { _context = createBeanFactory(); // TODO: check where this method is //_context.setXmlValidating(false); } protected void tearDown() throws Exception { if (_context != null) { _log.debug("Closing down the spring _context"); _context.destroy(); } } protected Object getBean(String name) { Object answer = null; if (_context != null) { answer = _context.getBean(name); } Assert.assertNotNull("Could not find object in Spring for key: " + name, answer); return answer; } protected abstract AbstractXmlApplicationContext createBeanFactory(); protected Source getSourceFromClassPath(String fileOnClassPath) { InputStream stream = getClass().getResourceAsStream(fileOnClassPath); Assert.assertNotNull("Could not find file: " + fileOnClassPath + " on the classpath", stream); Source content = new StreamSource(stream); return content; } }
epl-1.0
theanuradha/debrief
org.mwc.cmap.grideditor/src/org/mwc/cmap/grideditor/GridEditorView.java
8917
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.mwc.cmap.grideditor; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.operations.RedoActionHandler; import org.eclipse.ui.operations.UndoActionHandler; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.mwc.cmap.core.property_support.EditableWrapper; import org.mwc.cmap.core.ui_support.PartMonitor; import org.mwc.cmap.grideditor.data.GriddableWrapper; import org.mwc.cmap.grideditor.table.actons.GridEditorActionGroup; import org.mwc.cmap.plotViewer.editors.CorePlotEditor; import MWC.GUI.Editable; import MWC.GUI.GriddableSeriesMarker; public class GridEditorView extends ViewPart { private ISelectionListener mySelectionListener; private GridEditorActionGroup myActions; private GridEditorUI myUI; private GridEditorUndoSupport myUndoSupport; private UndoActionHandler myUndoAction; private RedoActionHandler myRedoAction; private PartMonitor _myPartMonitor; private CorePlotEditor displayedPlot; @Override public void createPartControl(final Composite parent) { final GridEditorActionContext actionContext = new GridEditorActionContext( myUndoSupport); myActions = new GridEditorActionGroup(this, actionContext); myUI = new GridEditorUI(parent, myActions); final ISelectionService selectionService = getSite().getWorkbenchWindow() .getSelectionService(); handleWorkspaceSelectionChanged(selectionService.getSelection()); final IActionBars actionBars = getViewSite().getActionBars(); myActions.fillActionBars(actionBars); actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(), myUndoAction); actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(), myRedoAction); _myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService()); _myPartMonitor.addPartListener(CorePlotEditor.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { @Override public void eventTriggered(String type, Object instance, IWorkbenchPart parentPart) { if(instance.equals(displayedPlot)) { //set input null now. myUI.inputSeriesChanged(null); } } }); _myPartMonitor.addPartListener(CorePlotEditor.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { @Override public void eventTriggered(String type, Object instance, IWorkbenchPart parentPart) { if(instance instanceof CorePlotEditor) { displayedPlot = (CorePlotEditor)instance; //activate the outline view activateOutlineView((CorePlotEditor)instance); } } }); } private static void activateOutlineView(CorePlotEditor editor) { IContentOutlinePage outline = (IContentOutlinePage) editor.getAdapter(IContentOutlinePage.class); if(outline!=null) { outline.setFocus(); } } @Override public void dispose() { getSite().getWorkbenchWindow().getSelectionService() .removeSelectionListener(getSelectionListener()); _myPartMonitor.ditch(); super.dispose(); } private static GriddableWrapper extractGriddableSeries(final ISelection selection) { GriddableWrapper res = null; if (false == selection instanceof IStructuredSelection) { return null; } final IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (structuredSelection.isEmpty()) { return null; } final Object firstElement = structuredSelection.getFirstElement(); // right, see if this is a series object already. if it is, we've got // our // data. if it isn't, see // if it's a candidate for editing and collate a series of elements if (firstElement instanceof EditableWrapper) { final EditableWrapper wrapped = (EditableWrapper) firstElement; final Object value = wrapped.getEditableValue(); if (wrapped != null) { if ((value instanceof GriddableSeriesMarker) && !(value instanceof Editable.DoNoInspectChildren)) { res = new GriddableWrapper(wrapped); } } } else { // see if it can be adapted if (firstElement instanceof IAdaptable) { final IAdaptable is = (IAdaptable) firstElement; final EditableWrapper wrapped = (EditableWrapper) is .getAdapter(EditableWrapper.class); if (wrapped != null) { final Object value = wrapped.getEditableValue(); if ((value instanceof GriddableSeriesMarker) && !(value instanceof Editable.DoNoInspectChildren)) { res = new GriddableWrapper(wrapped); } } } } return res; } private ISelectionListener getSelectionListener() { if (mySelectionListener == null) { mySelectionListener = new ISelectionListener() { public void selectionChanged(final IWorkbenchPart part, final ISelection selection) { if (part == GridEditorView.this) { // ignore, we are going to handle our own selection // ourselves return; } handleWorkspaceSelectionChanged(selection); } }; } return mySelectionListener; } public GridEditorUI getUI() { return myUI; } private void handleWorkspaceSelectionChanged(final ISelection actualSelection) { if (myUI.isDisposed()) { return; } // am I even tracking the selection? if (!myUI.getTable().isTrackingSelection()) return; final GriddableWrapper input = extractGriddableSeries(actualSelection); if (input == null) { // not valid data - set input to null (which clears the UI // CHANGED: don't wipe on invalid input. This lets us do Layer Manager edits // based on data in the grid editor // myUI.inputSeriesChanged(null); } else { // yes, but what are we currently looking at? final GriddableWrapper existingInput = (GriddableWrapper) myUI.getTable() .getTableViewer().getInput(); // see if we're currently looking at something final EditableWrapper editable = existingInput != null ? existingInput .getWrapper() : null; // are they the same? if (input.getWrapper() == editable) { // ignore, we're already looking at it } else { myUI.inputSeriesChanged(input); } } } @Override public void init(final IViewSite site) throws PartInitException { super.init(site); final ISelectionService selectionService = site.getWorkbenchWindow() .getSelectionService(); selectionService.addSelectionListener(getSelectionListener()); initUndoSupport(); } private void initUndoSupport() { myUndoSupport = new GridEditorUndoSupport(PlatformUI.getWorkbench() .getOperationSupport().getOperationHistory()); // set up action handlers that operate on the current context myUndoAction = new UndoActionHandler(this.getSite(), myUndoSupport.getUndoContext()); myRedoAction = new RedoActionHandler(this.getSite(), myUndoSupport.getUndoContext()); } public void refreshUndoContext() { if (myUndoAction != null) { myUndoAction.dispose(); myUndoAction = null; } if (myRedoAction != null) { myRedoAction.dispose(); myRedoAction = null; } myUndoAction = new UndoActionHandler(this.getSite(), myUndoSupport.getUndoContext()); myRedoAction = new RedoActionHandler(this.getSite(), myUndoSupport.getUndoContext()); final IActionBars actionBars = getViewSite().getActionBars(); actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(), myUndoAction); actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(), myRedoAction); actionBars.updateActionBars(); } @Override public void setFocus() { myUI.forceTableFocus(); } }
epl-1.0
test-editor/test-editor-xtext
tcl/org.testeditor.tcl.dsl.tests/src/org/testeditor/tcl/util/package-info.java
146
/** * Note that theses tests are actually tests for org.testeditor.tcl.model and should * be moved there... */ package org.testeditor.tcl.util;
epl-1.0
codenotes/dngrep
w32test/win32shelltest/win32shelltest/win32shelltest.cpp
18871
// win32shelltest.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "win32shelltest.h" #include <string> #include <Shtypes.h> #include <Shlobj.h> #include <assert.h> #include <algorithm> #include <thread> #include <cstdlib> #define MAX_LOADSTRING 100 static LPITEMIDLIST GetNextItemID(LPITEMIDLIST pidl) { // Get the size of the specified item identifier. int cb = pidl->mkid.cb; // If the size is zero, it is the end of the list. if (cb == 0) return NULL; // Add cb to pidl (casting to increment by bytes). pidl = (LPITEMIDLIST)(((LPBYTE)pidl) + cb); // Return NULL if it is null-terminating or a pidl otherwise. return (pidl->mkid.cb == 0) ? NULL : pidl; } // CopyItemID - creates an item identifier list containing the first // item identifier in the specified list. // Returns a PIDL if successful or NULL if out of memory. static LPITEMIDLIST CopyItemID(LPITEMIDLIST pidl) { LPMALLOC pMalloc; if (FAILED(SHGetMalloc(&pMalloc))) return NULL; // Get the size of the specified item identifier. int cb = pidl->mkid.cb; // Allocate a new item identifier list. LPITEMIDLIST pidlNew = (LPITEMIDLIST)pMalloc->Alloc(cb + sizeof(USHORT)); if (pidlNew != NULL) { // Copy the specified item identifier. CopyMemory(pidlNew, pidl, cb); // Append a terminating zero. *((USHORT *)(((LPBYTE)pidlNew) + cb)) = 0; } pMalloc->Release(); return pidlNew; } // return an IShellFolder given a pidl to the directory. LPSHELLFOLDER GetIShellFolder(const LPITEMIDLIST pDirPidl) { LPSHELLFOLDER pFolder; LPITEMIDLIST pidl; LPMALLOC pMalloc; if (pDirPidl == NULL) return NULL; if (FAILED(SHGetDesktopFolder(&pFolder))) return NULL; if (FAILED(SHGetMalloc(&pMalloc))) { pFolder->Release(); return NULL; } // step thru the pidl, binding to each subdirectory in turn. // Process each item identifier in the list. for (pidl = pDirPidl; pidl != NULL; pidl = GetNextItemID(pidl)) { LPSHELLFOLDER pSubFolder; LPITEMIDLIST pidlCopy; // Copy the item identifier to a list by itself. if ((pidlCopy = CopyItemID(pidl)) == NULL) break; // Bind to the subfolder. if (!SUCCEEDED(pFolder->BindToObject( pidlCopy, NULL, IID_IShellFolder, (void**)&pSubFolder))) { pMalloc->Free(pidlCopy); pFolder->Release(); pFolder = NULL; break; } // Free the copy of the item identifier. pMalloc->Free(pidlCopy); // Release the parent folder and point to the // subfolder. pFolder->Release(); pFolder = pSubFolder; } if (pMalloc) pMalloc->Release(); // return the last folder that was bound to. return pFolder; } // return an IShellFolder interface or null given the directory. LPSHELLFOLDER GetIShellFolder(const char *pDirName) { LPSHELLFOLDER pFolder = NULL; LPITEMIDLIST DirPidl = NULL; LPMALLOC pMalloc = NULL; ULONG eaten, attribs; USHORT wsz[MAX_PATH]; // setup a shell malloc pointer for the helper funcs. if (FAILED(SHGetMalloc(&pMalloc))) return NULL; // the desktop folder. if (FAILED(SHGetDesktopFolder(&pFolder))) { pMalloc->Release(); return NULL; } // Ensure that the string is Unicode. MultiByteToWideChar(CP_ACP, 0, pDirName, -1, wsz, MAX_PATH); // this should return a pidl to that directory. if (FAILED(pFolder->ParseDisplayName(NULL, 0, wsz, &eaten, &DirPidl, &attribs))) { pFolder->Release(); pMalloc->Release(); return NULL; } // done with the desktop folder. pFolder->Release(); // get the folder we really want. pFolder = GetIShellFolder(DirPidl); // clean up pMalloc->Free(DirPidl); pMalloc->Release(); // return the last folder that was bound to. return pFolder; } // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); // // // HRESULT WINAPI IUnknown_SetSite( // IUnknown *obj, /* [in] OLE object */ // IUnknown *site) /* [in] Site interface */ //{ // HRESULT hr; // IObjectWithSite *iobjwithsite; // IInternetSecurityManager *isecmgr; // // if (!obj) return E_FAIL; // IUnknown_QueryInterface // hr = IUnknown_QueryInterface(obj, &IID_IObjectWithSite, (LPVOID *)&iobjwithsite); // // TRACE("IID_IObjectWithSite QI ret=%08x, %p\n", hr, iobjwithsite); // if (SUCCEEDED(hr)) // { // hr = IObjectWithSite_SetSite(iobjwithsite, site); // //TRACE("done IObjectWithSite_SetSite ret=%08x\n", hr); // IObjectWithSite_Release(iobjwithsite); // } // else // { // hr = IUnknown_QueryInterface(obj, &IID_IInternetSecurityManager, (LPVOID *)&isecmgr); // //TRACE("IID_IInternetSecurityManager QI ret=%08x, %p\n", hr, isecmgr); // if (FAILED(hr)) return hr; // // //hr = IInternetSecurityManager_SetSecuritySite(isecmgr, (IInternetSecurityMgrSite *)site); // //TRACE("done IInternetSecurityManager_SetSecuritySite ret=%08x\n", hr); // //IInternetSecurityManager_Release(isecmgr); // } // return hr; //} // // //LRESULT TestOnContextMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled) // { // WORD x; // WORD y; // UINT uCommand; // DWORD wFlags; // HMENU hMenu; // BOOL fExplore; // HWND hwndTree; // CMINVOKECOMMANDINFO cmi; // HRESULT hResult; // // // for some reason I haven't figured out, we sometimes recurse into this method // if (pCM != NULL) // return 0; // // x = LOWORD(lParam); // y = HIWORD(lParam); // // // TRACE("(%p)->(0x%08x 0x%08x) stub\n", this, x, y); // // fExplore = FALSE; // hwndTree = NULL; // // /* look, what's selected and create a context menu object of it*/ // if (GetSelections()) // { // pSFParent->GetUIObjectOf(hWndParent, cidl, (LPCITEMIDLIST*)apidl, IID_IContextMenu, NULL, (LPVOID *)&pCM); // // if (pCM) // { // TRACE("-- pContextMenu\n"); // hMenu = CreatePopupMenu(); // // if (hMenu) // { // hResult = IUnknown_SetSite(pCM, (IShellView *)this); // // /* See if we are in Explore or Open mode. If the browser's tree is present, we are in Explore mode.*/ // if (SUCCEEDED(pShellBrowser->GetControlWindow(FCW_TREE, &hwndTree)) && hwndTree) // { // TRACE("-- explore mode\n"); // fExplore = TRUE; // } // // /* build the flags depending on what we can do with the selected item */ // wFlags = CMF_NORMAL | (cidl != 1 ? 0 : CMF_CANRENAME) | (fExplore ? CMF_EXPLORE : 0); // // /* let the ContextMenu merge its items in */ // if (SUCCEEDED(pCM->QueryContextMenu(hMenu, 0, FCIDM_SHVIEWFIRST, FCIDM_SHVIEWLAST, wFlags ))) // { // if (FolderSettings.fFlags & FWF_DESKTOP) // SetMenuDefaultItem(hMenu, FCIDM_SHVIEW_OPEN, MF_BYCOMMAND); // // TRACE("-- track popup\n"); // uCommand = TrackPopupMenu(hMenu, // TPM_LEFTALIGN | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, // x, y, 0, m_hWnd, NULL); // // if (uCommand > 0) // { // TRACE("-- uCommand=%u\n", uCommand); // // if (uCommand == FCIDM_SHVIEW_OPEN && pCommDlgBrowser.p != NULL) // { // TRACE("-- dlg: OnDefaultCommand\n"); // if (OnDefaultCommand() != S_OK) // OpenSelectedItems(); // } // else // { // TRACE("-- explore -- invoke command\n"); // ZeroMemory(&cmi, sizeof(cmi)); // cmi.cbSize = sizeof(cmi); // cmi.hwnd = hWndParent; /* this window has to answer CWM_GETISHELLBROWSER */ // cmi.lpVerb = (LPCSTR)MAKEINTRESOURCEA(uCommand); // pCM->InvokeCommand(&cmi); // } // } // // hResult = IUnknown_SetSite(pCM, NULL); // DestroyMenu(hMenu); // } // } // pCM.Release(); // } // } // else /* background context menu */ // { // hMenu = CreatePopupMenu(); // // CDefFolderMenu_Create2(NULL, NULL, cidl, (LPCITEMIDLIST*)apidl, pSFParent, NULL, 0, NULL, (IContextMenu**)&pCM); // pCM->QueryContextMenu(hMenu, 0, FCIDM_SHVIEWFIRST, FCIDM_SHVIEWLAST, 0); // // uCommand = TrackPopupMenu(hMenu, // TPM_LEFTALIGN | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, // x, y, 0, m_hWnd, NULL); // DestroyMenu(hMenu); // // TRACE("-- (%p)->(uCommand=0x%08x )\n", this, uCommand); // // ZeroMemory(&cmi, sizeof(cmi)); // cmi.cbSize = sizeof(cmi); // cmi.lpVerb = (LPCSTR)MAKEINTRESOURCEA(uCommand); // cmi.hwnd = hWndParent; // pCM->InvokeCommand(&cmi); // // pCM.Release(); // } // // return 0; // } // // //ypedef struct _browseinfoW { // HWND hwndOwner; // PCIDLIST_ABSOLUTE pidlRoot; // LPWSTR pszDisplayName; // Return display name of item selected. // LPCWSTR lpszTitle; // text to go in the banner over the tree. // UINT ulFlags; // Flags that control the return stuff // BFFCALLBACK lpfn; // LPARAM lParam; // extra info that's passed back in callbacks // int iImage; // output var: where to return the Image index. //} BROWSEINFOW, *PBROWSEINFOW, *LPBROWSEINFOW; LPITEMIDLIST bshell() { BROWSEINFO bi = { 0 }; bi.ulFlags = BIF_BROWSEINCLUDEFILES; bi.lpszTitle = _T("Pick a Directory"); LPITEMIDLIST pidl = SHBrowseForFolder(&bi); if (pidl != 0) { // get the name of the folder TCHAR path[MAX_PATH]; if (SHGetPathFromIDList(pidl, path)) { _tprintf(_T("Selected Folder: %s\n"), path); } // free memory used IMalloc * imalloc = 0; if (SUCCEEDED(SHGetMalloc(&imalloc))) { imalloc->Free(pidl); imalloc->Release(); } return pidl; } } //Below, this works, but doesn't include the contextmenuhandlers that are in explorer. No different than my other demos. bool openShellContextMenuForObject(const std::wstring &path, int xPos, int yPos, void * parentWindow) { assert(parentWindow); ITEMIDLIST * id = 0; std::wstring windowsPath = path; std::replace(windowsPath.begin(), windowsPath.end(), '/', '\\'); HRESULT result = SHParseDisplayName(windowsPath.c_str(), 0, &id, 0, 0); if (!SUCCEEDED(result) || !id) return false; //CItemIdListReleaser idReleaser(id); LPITEMIDLIST pa=0; LPITEMIDLIST pa2=0; IShellFolder * ifolder = 0; IShellFolder * idesktopfolder = 0; IContextMenu * imenu = 0; IObjectWithSite * isite = 0; //browser will ONLY return the pidl of the folder. //pa=bshell(); //pa2 = bshell(); pa2 = pa; DWORD Eaten; LPITEMIDLIST idChild = 0; LPITEMIDLIST Pidl2; //ifolder gets initialized here. //*************alternate test #if 0 LPITEMIDLIST ParentPidl; result= SHGetDesktopFolder(&idesktopfolder); //desktopfolder->BindToObject() result = idesktopfolder->ParseDisplayName(0, 0, (LPWSTR)windowsPath.c_str(), 0, &ParentPidl, 0); LPSHELLFOLDER ParentFolder; result = idesktopfolder->BindToObject(ParentPidl, 0, IID_IShellFolder, (void**)&ParentFolder); /*ParentFolder->ParseDisplayName( Handle, 0, Path, &Eaten, &Pidl, 0); */ ParentFolder->ParseDisplayName( (HWND)parentWindow, 0, (LPWSTR)windowsPath.c_str(), 0, &Pidl2, 0); LPCONTEXTMENU CM; ParentFolder->GetUIObjectOf( (HWND)parentWindow, 1, (LPCITEMIDLIST*)&Pidl2, IID_IContextMenu, 0, (void**)&CM); HMENU hMenu2 = CreatePopupMenu(); if (!hMenu2) return false; if (SUCCEEDED(CM->QueryContextMenu(hMenu2, 0, 1, 0x7FFF, CMF_NORMAL | CMF_EXPLORE))) { int iCmd = TrackPopupMenuEx(hMenu2, TPM_RETURNCMD, xPos, yPos, (HWND)parentWindow, NULL); if (iCmd > 0) { CMINVOKECOMMANDINFOEX info = { 0 }; info.cbSize = sizeof(info); info.fMask = CMIC_MASK_UNICODE; info.hwnd = (HWND)parentWindow; info.lpVerb = MAKEINTRESOURCEA(iCmd - 1); info.lpVerbW = MAKEINTRESOURCEW(iCmd - 1); info.nShow = SW_SHOWNORMAL; CM->InvokeCommand((LPCMINVOKECOMMANDINFO)&info); } } DestroyMenu(hMenu2); return 0; //****************end alternate #endif //old, working result = SHBindToParent(id, IID_IShellFolder, (void**)&ifolder, (LPCITEMIDLIST*)&idChild); //new test, failed //result = SHBindToParent(id, IID_IShellFolder, (void**)&ifolder, (LPCITEMIDLIST*)&pa); //result = SHBindToParent(pa, IID_IShellFolder, (void**)&ifolder, (LPCITEMIDLIST*)&idChild); if (!SUCCEEDED(result))// || !ifolder) return false; //CComInterfaceReleaser ifolderReleaser(ifolder); //new test //result = ifolder->ParseDisplayName( // (HWND)parentWindow, 0, (LPWSTR)windowsPath.c_str(), 0, &Pidl2, 0); // //result = SHBindToParent(Pidl2, IID_IShellFolder, (void**)&ifolder, (LPCITEMIDLIST*)&idChild); //end test //old,working result = ifolder->GetUIObjectOf((HWND)parentWindow, 1, (const ITEMIDLIST **)&idChild, IID_IContextMenu, 0, (void**)&imenu); //result = idesktopfolder->GetUIObjectOf((HWND)parentWindow, 1, (const ITEMIDLIST **)&id, IID_IContextMenu, 0, (void**)&imenu); // result = ifolder->GetUIObjectOf((HWND)parentWindow, 1, (const ITEMIDLIST **)&pa, IID_IContextMenu, 0, (void**)&imenu); if (!SUCCEEDED(result))// || !ifolder) return false; //CComInterfaceReleaser menuReleaser(imenu); HMENU hMenu = CreatePopupMenu(); if (!hMenu) return false; if (SUCCEEDED(imenu->QueryContextMenu(hMenu, 0, 1, 0x7FFF,CMF_NORMAL| CMF_EXPLORE))) { int iCmd = TrackPopupMenuEx(hMenu, TPM_RETURNCMD, xPos, yPos, (HWND)parentWindow, NULL); if (iCmd > 0) { CMINVOKECOMMANDINFOEX info = { 0 }; info.cbSize = sizeof(info); info.fMask = CMIC_MASK_UNICODE; info.hwnd = (HWND)parentWindow; info.lpVerb = MAKEINTRESOURCEA(iCmd - 1); info.lpVerbW = MAKEINTRESOURCEW(iCmd - 1); info.nShow = SW_SHOWNORMAL; imenu->InvokeCommand((LPCMINVOKECOMMANDINFO)&info); } } DestroyMenu(hMenu); return true; } int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); CoInitialize(0); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WIN32SHELLTEST, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32SHELLTEST)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32SHELLTEST)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WIN32SHELLTEST); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: //DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); openShellContextMenuForObject(L"c:\\temp\\test.xml",30,30,hWnd); // openShellContextMenuForObject(L"c:\\temp", 30, 30, hWnd); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
gpl-2.0
Tornaldo/WebIntelligence
extensions/SemanticMediaWiki/tests/phpunit/includes/serializer/SemanticDataSerializerTest.php
3186
<?php namespace SMW\Tests\Serializers; use SMW\Serializers\SemanticDataSerializer; use SMW\Tests\Utils\SemanticDataFactory; use SMW\DataValueFactory; use SMw\SemanticData; use SMW\DIWikiPage; use SMW\Subobject; use Title; /** * @covers \SMW\Serializers\SemanticDataSerializer * * * @group SMW * @group SMWExtension * * @license GNU GPL v2+ * @since 1.9 * * @author mwjames */ class SemanticDataSerializerTest extends \PHPUnit_Framework_TestCase { private $dataValueFactory; private $semanticDataFactory; public function testCanConstructor() { $this->assertInstanceOf( '\SMW\Serializers\SemanticDataSerializer', new SemanticDataSerializer() ); } public function testInvalidSerializerObjectThrowsException() { $this->setExpectedException( 'OutOfBoundsException' ); $instance = new SemanticDataSerializer(); $instance->serialize( 'Foo' ); } /** * @dataProvider semanticDataProvider */ public function testSerializerDeserializerRountrip( $data ) { $instance = new SemanticDataSerializer(); $this->assertInternalType( 'array', $instance->serialize( $data ) ); } public function semanticDataProvider() { $this->semanticDataFactory = new SemanticDataFactory(); $this->dataValueFactory = DataValueFactory::getInstance(); $title = Title::newFromText( 'Foo' ); #0 Empty container $foo = $this->semanticDataFactory->setSubject( DIWikiPage::newFromTitle( $title ) )->newEmptySemanticData(); $provider[] = array( $foo ); #1 Single entry $foo = $this->semanticDataFactory->setSubject( DIWikiPage::newFromTitle( $title ) )->newEmptySemanticData(); $foo->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has fooQuex', 'Bar' ) ); $provider[] = array( $foo ); // #2 Single + single subobject entry $foo = $this->semanticDataFactory->setSubject( DIWikiPage::newFromTitle( $title ) )->newEmptySemanticData(); $foo->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has fooQuex', 'Bar' ) ); $subobject = new Subobject( $title ); $subobject->setSemanticData( 'Foo' ); $subobject->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has subobjects', 'Bam' ) ); $foo->addPropertyObjectValue( $subobject->getProperty(), $subobject->getContainer() ); $provider[] = array( $foo ); #3 Multiple entries $foo = $this->semanticDataFactory->setSubject( DIWikiPage::newFromTitle( $title ) )->newEmptySemanticData(); $foo->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has fooQuex', 'Bar' ) ); $foo->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has queez', 'Xeey' ) ); $subobject = new Subobject( $title ); $subobject->setSemanticData( 'Foo' ); $subobject->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has subobjects', 'Bam' ) ); $subobject->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has fooQuex', 'Fuz' ) ); $subobject->setSemanticData( 'Bar' ); $subobject->addDataValue( $this->dataValueFactory->newPropertyValue( 'Has fooQuex', 'Fuz' ) ); $foo->addPropertyObjectValue( $subobject->getProperty(), $subobject->getContainer() ); $provider[] = array( $foo ); return $provider; } }
gpl-2.0
agx/git-buildpackage
tests/09_test_git_repository.py
2988
# vim: set fileencoding=utf-8 : """ Test L{GitRepository} Test things here that don't fit nicely into the doctests that also make up the API documentation. """ from . import context # noqa: 401 from . import testutils import os import gbp.log import gbp.git import gbp.errors class TestWriteTree(testutils.DebianGitTestRepo): def _write_testtree(self): """Write a test tree""" paths = [] for i in range(4): path = os.path.join(self.repo.path, 'testfile%d' % i) with open(path, 'w') as f: print("testdata %d" % i, file=f) paths.append(path) return paths def test_write_tree_index_nonexistent(self): """Write out index file to non-existent dir""" paths = self._write_testtree() self.repo.add_files(paths) with self.assertRaises(gbp.git.GitRepositoryError): self.repo.write_tree('/does/not/exist') def test_write_tree(self): """Write out index file to alternate index file""" index = os.path.join(self.repo.git_dir, 'gbp_index') expected_sha1 = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' paths = self._write_testtree() self.repo.add_files(paths) sha1 = self.repo.write_tree(index) self.assertTrue(os.path.exists(index)) self.assertEqual(sha1, expected_sha1) self.assertTrue(self.repo.has_treeish(expected_sha1)) def test_commit_tree(self): """Commit a tree""" expected_sha1 = 'ea63fcee40675a5f82ea6bedbf29ca86d89c5f63' paths = self._write_testtree() self.repo.add_files(paths) sha1 = self.repo.write_tree() self.assertEqual(sha1, expected_sha1) self.assertTrue(self.repo.has_treeish(expected_sha1)) commit = self.repo.commit_tree(sha1, "first commit", parents=[], committer=dict(name='foo', email='foo@example.com'), author=dict(name='bar', email='bar@example.com'), ) self.assertEqual(len(commit), 40) # commit the same tree again using the previous commit as parent self.repo.commit_tree(sha1, "second commit", parents=[commit]) # commit the same tree again using a non-existent parent with self.assertRaises(gbp.errors.GbpError): self.repo.commit_tree(sha1, "failed commit", ['doesnotexist']) class TestHasBranch(testutils.DebianGitTestRepo): def test_has_branch(self): self.add_file('whatever') self.repo.create_branch("foo") self.assertTrue(self.repo.has_branch("foo")) # Don't be too sloppy on (#813298) self.repo.create_branch("refs/heads/bar") self.assertFalse(self.repo.has_branch("bar")) # vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·:
gpl-2.0
nickzman/helios
rsMath/rsVec.cpp
3401
/* * Copyright (C) 1999-2010 Terence M. Welsh * * This file is part of rsMath. * * rsMath is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * rsMath is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "rsMath.h" #include <math.h> rsVec::rsVec(){ } rsVec::rsVec(float xx, float yy, float zz){ v[0] = xx; v[1] = yy; v[2] = zz; } rsVec::~rsVec(){ } void rsVec::set(float xx, float yy, float zz){ v[0] = xx; v[1] = yy; v[2] = zz; } float rsVec::length(){ return(float(sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]))); } float rsVec::normalize(){ float length = sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); if(length == 0.0f){ v[1] = 1.0f; return(0.0f); } const float normalizer(1.0f / length); v[0] *= normalizer; v[1] *= normalizer; v[2] *= normalizer; return(length); } float rsVec::dot(rsVec vec1){ return(v[0] * vec1[0] + v[1] * vec1[1] + v[2] * vec1[2]); } void rsVec::cross(rsVec vec1, rsVec vec2){ v[0] = vec1[1] * vec2[2] - vec2[1] * vec1[2]; v[1] = vec1[2] * vec2[0] - vec2[2] * vec1[0]; v[2] = vec1[0] * vec2[1] - vec2[0] * vec1[1]; } void rsVec::scale(float scale){ v[0] *= scale; v[1] *= scale; v[2] *= scale; } void rsVec::transPoint(const rsMatrix &m){ float x = v[0]; float y = v[1]; float z = v[2]; v[0] = x * m[0] + y * m[4] + z * m[8] + m[12]; v[1] = x * m[1] + y * m[5] + z * m[9] + m[13]; v[2] = x * m[2] + y * m[6] + z * m[10] + m[14]; } void rsVec::transVec(const rsMatrix &m){ float x = v[0]; float y = v[1]; float z = v[2]; v[0] = x * m[0] + y * m[4] + z * m[8]; v[1] = x * m[1] + y * m[5] + z * m[9]; v[2] = x * m[2] + y * m[6] + z * m[10]; } int rsVec::almostEqual(rsVec vec, float tolerance){ if(sqrtf((v[0]-vec[0])*(v[0]-vec[0]) + (v[1]-vec[1])*(v[1]-vec[1]) + (v[2]-vec[2])*(v[2]-vec[2])) <= tolerance) return 1; else return 0; } // Generic vector math functions float rsLength(float *xyz){ return(float(sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2]))); } float rsNormalize(float *xyz){ float length = float(sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2])); if(length == 0.0f) return(0.0f); float reciprocal = 1.0f / length; xyz[0] *= reciprocal; xyz[1] *= reciprocal; xyz[2] *= reciprocal; // Really freakin' stupid compiler bug fix for VC++ 5.0 /*xyz[0] /= length; xyz[1] /= length; xyz[2] /= length;*/ return(length); } float rsDot(float *xyz1, float *xyz2){ return(xyz1[0] * xyz2[0] + xyz1[1] * xyz2[1] + xyz1[2] * xyz2[2]); } void rsCross(float *xyz1, float *xyz2, float *xyzOut){ xyzOut[0] = xyz1[1] * xyz2[2] - xyz2[1] * xyz1[2]; xyzOut[1] = xyz1[2] * xyz2[0] - xyz2[2] * xyz1[0]; xyzOut[2] = xyz1[0] * xyz2[1] - xyz2[0] * xyz1[1]; } void rsScaleVec(float *xyz, float scale){ xyz[0] *= scale; xyz[1] *= scale; xyz[2] *= scale; }
gpl-2.0
mager19/portafolio
template-parts/content.php
1292
<?php /** * Template part for displaying posts * * @link https://codex.wordpress.org/Template_Hierarchy * * @package wiltonwings */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php if ( is_single() ) : the_title( '<h1 class="entry-title">', '</h1>' ); else : the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' ); endif; if ( 'post' === get_post_type() ) : ?> <div class="entry-meta"> <?php wiltonwings_posted_on(); ?> </div><!-- .entry-meta --> <?php endif; ?> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content( sprintf( /* translators: %s: Name of current post. */ wp_kses( __( 'Continue reading %s <span class="meta-nav">&rarr;</span>', 'wiltonwings' ), array( 'span' => array( 'class' => array() ) ) ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ) ); wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'wiltonwings' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php wiltonwings_entry_footer(); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
gpl-2.0
WithoutHaste/TaskManagerX
Tamarin/classes/ConfigSheet.cs
7403
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using OfficeOpenXml; using WithoutHaste.DataFiles.Excel; namespace Tamarin { public class ConfigSheet { public List<Status> Statuses { get; set; } public List<string> Categories { get; set; } public int MaxId { get; set; } public string[] ActiveStatuses { get { return Statuses.Where(x => x.Active).Select(x => x.Name).ToArray(); } } public string[] InactiveStatuses { get { return Statuses.Where(x => !x.Active).Select(x => x.Name).ToArray(); } } public int NextId { get { MaxId++; return MaxId; } } public string DefaultActiveStatus { get { return Statuses.First(x => x.Active).Name; } } public string DefaultCategory { get { return Categories.First(); } } private const string SHEET_NAME = "Config"; private const string STATUS_NAME = "Status"; private const string ACTIVE_NAME = "Active"; private const string CATEGORY_NAME = "Category"; private const string ID_NAME = "Max Id"; private const int DEFAULT_ID = 0; private const string IS_ACTIVE = "Active"; private const string IS_INACTIVE = "Inactive"; //--------------------------------------------- public ConfigSheet() { Init(); } public ConfigSheet(MSExcel2003XmlFile xmlFile) { int tableIndex = xmlFile.GetTableIndex(SHEET_NAME); if(tableIndex == -1) { Init(); return; } Statuses = new List<Status>(); List<string> statusValues = xmlFile.GetColumnValues(tableIndex, STATUS_NAME); List<string> isActiveValues = xmlFile.GetColumnValues(tableIndex, ACTIVE_NAME); if(statusValues == null || isActiveValues == null || statusValues.Count == 0 || isActiveValues.Count == 0) { SetDefaultStatuses(); } else { for(int i = 0; i < statusValues.Count; i++) { if(i >= isActiveValues.Count) break; Statuses.Add(new Status(statusValues[i], isActiveValues[i])); } } Categories = xmlFile.GetColumnValues(tableIndex, CATEGORY_NAME); if(Categories == null || Categories.Count == 0) { SetDefaultCategories(); } List<string> idValues = xmlFile.GetColumnValues(tableIndex, ID_NAME); if(idValues == null || idValues.Count == 0) { MaxId = DEFAULT_ID; } else { MaxId = Int32.Parse(idValues[0]); } } public ConfigSheet(ExcelPackage excelPackage) { ExcelWorksheet configSheet = ExcelPackageHelper.GetWorksheet(excelPackage, SHEET_NAME); if(configSheet == null) { AddDefaultConfigSheet(excelPackage); return; } List<object> statuses = ExcelPackageHelper.GetColumnByHeader(configSheet, STATUS_NAME); List<object> actives = ExcelPackageHelper.GetColumnByHeader(configSheet, ACTIVE_NAME); if(statuses.Count > 0) { Statuses = new List<Status>(); for(int i = 0; i < statuses.Count; i++) { bool isActive = true; if(actives.Count > i) isActive = (actives[i].ToString() == IS_ACTIVE); Statuses.Add(new Status(statuses[i].ToString(), isActive)); } } else { SetDefaultStatuses(); } Categories = ExcelPackageHelper.GetColumnByHeader(configSheet, CATEGORY_NAME).Cast<string>().ToList(); if(Categories.Count == 0) { SetDefaultCategories(); } List<object> ids = ExcelPackageHelper.GetColumnByHeader(configSheet, ID_NAME); if(ids.Count > 0) { MaxId = (int)ids[0]; } else { MaxId = DEFAULT_ID; } WriteConfigSheet(configSheet); //standardize format } //--------------------------------------------- private void Init() { SetDefaultStatuses(); SetDefaultCategories(); MaxId = DEFAULT_ID; } //--------------------------------------------- public void SetCategories(string[] categories) { List<string> validCategories = categories.Where(x => !String.IsNullOrEmpty(x)) .Distinct() .ToList(); if(validCategories.Count() == 0) throw new Exception("Project must contain at least one category."); Categories = validCategories; } public void SetStatuses(string[] active, string[] inactive) { List<string> validActive = active.Where(x => !String.IsNullOrEmpty(x)) .Distinct() .ToList(); if(validActive.Count == 0) throw new Exception("Project must contain at least one Active status."); List<string> validInactive = inactive.Where(x => !String.IsNullOrEmpty(x)) .Distinct() .ToList(); if(validInactive.Count == 0) throw new Exception("Project must contain at least one Inactive status."); string[] intersection = validActive.Intersect(validInactive).ToArray(); if(intersection.Length > 0) throw new Exception(String.Format("Status(es) cannot be both Active and Inactive: {0}", String.Join(", ", intersection))); Statuses.Clear(); Statuses.AddRange(validActive.Select(x => new Status(x, true))); Statuses.AddRange(validInactive.Select(x => new Status(x, false))); } private void SetDefaultStatuses() { Statuses = new List<Status>() { new Status("Todo", active:true), new Status("Done", active:false) }; } private void SetDefaultCategories() { Categories = new List<string>() { "Task", "Bug" }; } private void AddDefaultConfigSheet(ExcelPackage excelPackage) { ExcelWorksheet configSheet = ExcelPackageHelper.AddWorksheet(excelPackage, SHEET_NAME); SetDefaultStatuses(); SetDefaultCategories(); MaxId = DEFAULT_ID; WriteConfigSheet(configSheet); } private void WriteConfigSheet(ExcelWorksheet worksheet) { ExcelPackageHelper.Clear(worksheet); ExcelPackageHelper.AppendRow(worksheet, new List<object>() { STATUS_NAME, ACTIVE_NAME, "", CATEGORY_NAME, "", ID_NAME }); worksheet.Cells["A1:F1"].Style.Font.Bold = true; ExcelPackageHelper.SetColumnByChar(worksheet, "A", Statuses.Select(s => (object)s.Name).ToList(), skipFirstRow: true); ExcelPackageHelper.SetColumnByChar(worksheet, "B", Statuses.Select(s => (object)(s.Active ? IS_ACTIVE : IS_INACTIVE)).ToList(), skipFirstRow: true); ExcelPackageHelper.SetColumnByChar(worksheet, "D", Categories.Select(c => (object)c).ToList(), skipFirstRow: true); ExcelPackageHelper.SetColumnByChar(worksheet, "F", new List<object>() { (object)MaxId }, skipFirstRow: true); } public void WriteTo(ExcelPackage package) { ExcelWorksheet worksheet = ExcelPackageHelper.AddWorksheet(package, SHEET_NAME); WriteConfigSheet(worksheet); } public void WriteTo(MSExcel2003XmlFile xmlFile) { int tableIndex = xmlFile.AddWorksheet(SHEET_NAME); xmlFile.AddHeaderRow(tableIndex, new List<string>() { STATUS_NAME, ACTIVE_NAME, "", CATEGORY_NAME, "", ID_NAME }); List<XmlNode> statusNodes = Statuses.Select(status => xmlFile.GenerateTextCell(status.Name)).ToList(); List<XmlNode> activeNodes = Statuses.Select(status => xmlFile.GenerateTextCell((status.Active ? "Active" : "Inactive"))).ToList(); //todo: make constants, but not connected to table names List<XmlNode> categoryNodes = Categories.Select(category => xmlFile.GenerateTextCell(category)).ToList(); xmlFile.AddColumns(tableIndex, new List<List<XmlNode>>() { statusNodes, activeNodes, new List<XmlNode>(), categoryNodes, new List<XmlNode>(), new List<XmlNode>() { xmlFile.GenerateNumberCell(MaxId) } }); } } }
gpl-2.0
aide-solutions/password-generator
Captcha/Properties/AssemblyInfo.cs
656
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("Captcha")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Captcha")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly )] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-2.0
Esleelkartea/aonGTA
aongta_v1.0.0_src/Fuentes y JavaDoc/aon-ui-common/src/com/code/aon/ui/common/controller/ExceptionBean.java
4631
package com.code.aon.ui.common.controller; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javax.faces.application.Application; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import org.apache.commons.lang.StringEscapeUtils; /** * The Class ExceptionBean handles the exceptions ocurred within the application while it's running. */ public class ExceptionBean { /** The cause of the generated exception */ private Throwable cause; /** The error code of the generated exception */ private int errorCode; /** * The Constructor. */ public ExceptionBean() { FacesContext ctx = FacesContext.getCurrentInstance(); Application app = ctx.getApplication(); ValueBinding ex = app.createValueBinding("#{aon_exception}"); if (ex != null ) { cause = (Throwable) ex.getValue( ctx ); } ValueBinding er = app.createValueBinding("#{aon_http_error_code}"); if (er != null ) { Integer i = (Integer) er.getValue( ctx ); if (i != null) { errorCode = i.intValue(); } } } /** * Gets the cause of the exception. * * @return the cause */ public Throwable getCause() { return cause; } /** * Sets the cause of the exception. * * @param cause the cause */ public void setCause(Throwable cause) { this.cause = cause; } /** * Gets the error code of the exception. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code of the exception. * * @param errorCode the error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the error message. * * @return the error message */ public String getErrorMessage() { FacesContext ctx = FacesContext.getCurrentInstance(); Locale locale = ctx.getApplication().getDefaultLocale(); ResourceBundle bundle = ResourceBundle.getBundle("com.code.aon.ui.common.i18n.error_messages", locale); String m = bundle.getString("aon_http_error_" + getErrorCode()); return m; } /** * Gets the exception message. * * @return the exception message */ public String getExceptionMessage() { return cause == null ? "" : cause.getMessage(); } /** * Gets the messages. * * @return the messages */ public Object[] getMessages() { List<ExceptionMessage> list = new LinkedList<ExceptionMessage>(); if (cause != null) { addMessage(list, cause); } return list.toArray(); } /** * Adds the message. * * @param list the list of messages * @param t the Throwable element to add to the list */ private void addMessage(List<ExceptionMessage> list, Throwable t) { ExceptionMessage em = new ExceptionMessage(t.getClass().getName(), t.getMessage()); list.add(em); if (t.getCause() != null) { addMessage(list, t.getCause()); } } /** * Gets the full stack trace. * * @return the full stack trace */ public String getFullStackTrace() { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); cause.printStackTrace(ps); ps.flush(); String r = out.toString(); return r; } /** * Gets the pretty full stack trace. * * @return the pretty full stack trace */ public String getPrettyFullStackTrace() { String r = getFullStackTrace(); r = r.replace("\r", " "); r = r.replace("\n", "<br/>"); r = r.replace("\t", "&#160;&#160;&#160;&#160;"); return r; } /** * Gets the java script full stack trace. * * @return the java script full stack trace */ public String getJavaScriptFullStackTrace() { return StringEscapeUtils.escapeJavaScript(getFullStackTrace()); } /** * The Class ExceptionMessage. */ public class ExceptionMessage { /** The class of the exception message. */ private String clazz; /** The message. */ private String message; /** * The Constructor. * * @param message the message * @param clazz the clazz */ public ExceptionMessage(String clazz, String message) { this.clazz = clazz; this.message = message; } /** * Gets the clazz. * * @return the clazz */ public String getClazz() { return clazz; } /** * Gets the message. * * @return the message */ public String getMessage() { return message; } } }
gpl-2.0
liuzheng712/Misago
misago/emberapp/app/components/navbar-dropdown.js
395
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['compact-navbar-dropdown', 'hidden-md', 'hidden-lg'], dropdown: Ember.computed.alias('navbar-dropdown'), closeOnLinkClick: function() { var self = this; Ember.$(document).on('click.misagoNavbarDropdown', function() { self.get('navbar-dropdown').hide(); }); }.on('didInsertElement') });
gpl-2.0
bstroebl/QGIS
src/gui/symbology-ng/qgssymbollayerv2widget.cpp
41515
/*************************************************************************** qgssymbollayerv2widget.cpp - symbol layer widgets --------------------- begin : November 2009 copyright : (C) 2009 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgssymbollayerv2widget.h" #include "qgslinesymbollayerv2.h" #include "qgsmarkersymbollayerv2.h" #include "qgsfillsymbollayerv2.h" #include "characterwidget.h" #include "qgsdashspacedialog.h" #include "qgssymbolv2selectordialog.h" #include "qgssvgcache.h" #include "qgssymbollayerv2utils.h" #include "qgsstylev2.h" //for symbol selector dialog #include "qgsapplication.h" #include "qgslogger.h" #include <QAbstractButton> #include <QColorDialog> #include <QCursor> #include <QDir> #include <QFileDialog> #include <QPainter> #include <QSettings> #include <QStandardItemModel> #include <QSvgRenderer> QgsSimpleLineSymbolLayerV2Widget::QgsSimpleLineSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); connect( spinWidth, SIGNAL( valueChanged( double ) ), this, SLOT( penWidthChanged() ) ); connect( btnChangeColor, SIGNAL( clicked() ), this, SLOT( colorChanged() ) ); connect( cboPenStyle, SIGNAL( currentIndexChanged( int ) ), this, SLOT( penStyleChanged() ) ); connect( spinOffset, SIGNAL( valueChanged( double ) ), this, SLOT( offsetChanged() ) ); connect( cboCapStyle, SIGNAL( currentIndexChanged( int ) ), this, SLOT( penStyleChanged() ) ); connect( cboJoinStyle, SIGNAL( currentIndexChanged( int ) ), this, SLOT( penStyleChanged() ) ); updatePatternIcon(); } void QgsSimpleLineSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "SimpleLine" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsSimpleLineSymbolLayerV2*>( layer ); // set values spinWidth->setValue( mLayer->width() ); btnChangeColor->setColor( mLayer->color() ); spinOffset->setValue( mLayer->offset() ); cboPenStyle->blockSignals( true ); cboJoinStyle->blockSignals( true ); cboCapStyle->blockSignals( true ); cboPenStyle->setPenStyle( mLayer->penStyle() ); cboJoinStyle->setPenJoinStyle( mLayer->penJoinStyle() ); cboCapStyle->setPenCapStyle( mLayer->penCapStyle() ); cboPenStyle->blockSignals( false ); cboJoinStyle->blockSignals( false ); cboCapStyle->blockSignals( false ); //use a custom dash pattern? bool useCustomDashPattern = mLayer->useCustomDashPattern(); mChangePatternButton->setEnabled( useCustomDashPattern ); label_3->setEnabled( !useCustomDashPattern ); cboPenStyle->setEnabled( !useCustomDashPattern ); mCustomCheckBox->blockSignals( true ); mCustomCheckBox->setCheckState( useCustomDashPattern ? Qt::Checked : Qt::Unchecked ); mCustomCheckBox->blockSignals( false ); updatePatternIcon(); } QgsSymbolLayerV2* QgsSimpleLineSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsSimpleLineSymbolLayerV2Widget::penWidthChanged() { mLayer->setWidth( spinWidth->value() ); updatePatternIcon(); emit changed(); } void QgsSimpleLineSymbolLayerV2Widget::colorChanged() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel ); #else QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::ShowAlphaChannel ); #endif if ( !color.isValid() ) return; mLayer->setColor( color ); btnChangeColor->setColor( mLayer->color() ); updatePatternIcon(); emit changed(); } void QgsSimpleLineSymbolLayerV2Widget::penStyleChanged() { mLayer->setPenStyle( cboPenStyle->penStyle() ); mLayer->setPenJoinStyle( cboJoinStyle->penJoinStyle() ); mLayer->setPenCapStyle( cboCapStyle->penCapStyle() ); emit changed(); } void QgsSimpleLineSymbolLayerV2Widget::offsetChanged() { mLayer->setOffset( spinOffset->value() ); updatePatternIcon(); emit changed(); } void QgsSimpleLineSymbolLayerV2Widget::on_mCustomCheckBox_stateChanged( int state ) { bool checked = ( state == Qt::Checked ); mChangePatternButton->setEnabled( checked ); label_3->setEnabled( !checked ); cboPenStyle->setEnabled( !checked ); mLayer->setUseCustomDashPattern( checked ); emit changed(); } void QgsSimpleLineSymbolLayerV2Widget::on_mChangePatternButton_clicked() { QgsDashSpaceDialog d( mLayer->customDashVector() ); if ( d.exec() == QDialog::Accepted ) { mLayer->setCustomDashVector( d.dashDotVector() ); updatePatternIcon(); emit changed(); } } void QgsSimpleLineSymbolLayerV2Widget::updatePatternIcon() { if ( !mLayer ) { return; } QgsSimpleLineSymbolLayerV2* layerCopy = dynamic_cast<QgsSimpleLineSymbolLayerV2*>( mLayer->clone() ); if ( !layerCopy ) { return; } layerCopy->setUseCustomDashPattern( true ); QIcon buttonIcon = QgsSymbolLayerV2Utils::symbolLayerPreviewIcon( layerCopy, QgsSymbolV2::MM, mChangePatternButton->iconSize() ); mChangePatternButton->setIcon( buttonIcon ); delete layerCopy; } /////////// QgsSimpleMarkerSymbolLayerV2Widget::QgsSimpleMarkerSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); QSize size = lstNames->iconSize(); QStringList names; names << "circle" << "rectangle" << "diamond" << "pentagon" << "cross" << "cross2" << "triangle" << "equilateral_triangle" << "star" << "regular_star" << "arrow" << "line" << "arrowhead" << "filled_arrowhead"; double markerSize = DEFAULT_POINT_SIZE * 2; for ( int i = 0; i < names.count(); ++i ) { QgsSimpleMarkerSymbolLayerV2* lyr = new QgsSimpleMarkerSymbolLayerV2( names[i], QColor( 200, 200, 200 ), QColor( 0, 0, 0 ), markerSize ); QIcon icon = QgsSymbolLayerV2Utils::symbolLayerPreviewIcon( lyr, QgsSymbolV2::MM, size ); QListWidgetItem* item = new QListWidgetItem( icon, QString(), lstNames ); item->setData( Qt::UserRole, names[i] ); delete lyr; } connect( lstNames, SIGNAL( currentRowChanged( int ) ), this, SLOT( setName() ) ); connect( btnChangeColorBorder, SIGNAL( clicked() ), this, SLOT( setColorBorder() ) ); connect( btnChangeColorFill, SIGNAL( clicked() ), this, SLOT( setColorFill() ) ); connect( spinSize, SIGNAL( valueChanged( double ) ), this, SLOT( setSize() ) ); connect( spinAngle, SIGNAL( valueChanged( double ) ), this, SLOT( setAngle() ) ); connect( spinOffsetX, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); connect( spinOffsetY, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); } void QgsSimpleMarkerSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "SimpleMarker" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsSimpleMarkerSymbolLayerV2*>( layer ); // set values QString name = mLayer->name(); for ( int i = 0; i < lstNames->count(); ++i ) { if ( lstNames->item( i )->data( Qt::UserRole ).toString() == name ) { lstNames->setCurrentRow( i ); break; } } btnChangeColorBorder->setColor( mLayer->borderColor() ); btnChangeColorFill->setColor( mLayer->color() ); spinSize->setValue( mLayer->size() ); spinAngle->setValue( mLayer->angle() ); // without blocking signals the value gets changed because of slot setOffset() spinOffsetX->blockSignals( true ); spinOffsetX->setValue( mLayer->offset().x() ); spinOffsetX->blockSignals( false ); spinOffsetY->blockSignals( true ); spinOffsetY->setValue( mLayer->offset().y() ); spinOffsetY->blockSignals( false ); } QgsSymbolLayerV2* QgsSimpleMarkerSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsSimpleMarkerSymbolLayerV2Widget::setName() { mLayer->setName( lstNames->currentItem()->data( Qt::UserRole ).toString() ); emit changed(); } void QgsSimpleMarkerSymbolLayerV2Widget::setColorBorder() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor borderColor = QColorDialog::getColor( mLayer->borderColor(), this, "", QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel ); #else QColor borderColor = QColorDialog::getColor( mLayer->borderColor(), this, "", QColorDialog::ShowAlphaChannel ); #endif if ( !borderColor.isValid() ) return; mLayer->setBorderColor( borderColor ); btnChangeColorBorder->setColor( mLayer->borderColor() ); emit changed(); } void QgsSimpleMarkerSymbolLayerV2Widget::setColorFill() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel ); #else QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::ShowAlphaChannel ); #endif if ( !color.isValid() ) return; mLayer->setColor( color ); btnChangeColorFill->setColor( mLayer->color() ); emit changed(); } void QgsSimpleMarkerSymbolLayerV2Widget::setSize() { mLayer->setSize( spinSize->value() ); emit changed(); } void QgsSimpleMarkerSymbolLayerV2Widget::setAngle() { mLayer->setAngle( spinAngle->value() ); emit changed(); } void QgsSimpleMarkerSymbolLayerV2Widget::setOffset() { mLayer->setOffset( QPointF( spinOffsetX->value(), spinOffsetY->value() ) ); emit changed(); } /////////// QgsSimpleFillSymbolLayerV2Widget::QgsSimpleFillSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); connect( btnChangeColor, SIGNAL( clicked() ), this, SLOT( setColor() ) ); connect( cboFillStyle, SIGNAL( currentIndexChanged( int ) ), this, SLOT( setBrushStyle() ) ); connect( btnChangeBorderColor, SIGNAL( clicked() ), this, SLOT( setBorderColor() ) ); connect( spinBorderWidth, SIGNAL( valueChanged( double ) ), this, SLOT( borderWidthChanged() ) ); connect( cboBorderStyle, SIGNAL( currentIndexChanged( int ) ), this, SLOT( borderStyleChanged() ) ); connect( spinOffsetX, SIGNAL( valueChanged( double ) ), this, SLOT( offsetChanged() ) ); connect( spinOffsetY, SIGNAL( valueChanged( double ) ), this, SLOT( offsetChanged() ) ); } void QgsSimpleFillSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "SimpleFill" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsSimpleFillSymbolLayerV2*>( layer ); // set values btnChangeColor->setColor( mLayer->color() ); cboFillStyle->setBrushStyle( mLayer->brushStyle() ); btnChangeBorderColor->setColor( mLayer->borderColor() ); cboBorderStyle->setPenStyle( mLayer->borderStyle() ); spinBorderWidth->setValue( mLayer->borderWidth() ); spinOffsetX->blockSignals( true ); spinOffsetX->setValue( mLayer->offset().x() ); spinOffsetX->blockSignals( false ); spinOffsetY->blockSignals( true ); spinOffsetY->setValue( mLayer->offset().y() ); spinOffsetY->blockSignals( false ); } QgsSymbolLayerV2* QgsSimpleFillSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsSimpleFillSymbolLayerV2Widget::setColor() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel ); #else QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::ShowAlphaChannel ); #endif if ( !color.isValid() ) return; mLayer->setColor( color ); btnChangeColor->setColor( mLayer->color() ); emit changed(); } void QgsSimpleFillSymbolLayerV2Widget::setBorderColor() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor color = QColorDialog::getColor( mLayer->borderColor(), this, "", QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel ); #else QColor color = QColorDialog::getColor( mLayer->borderColor(), this, "", QColorDialog::ShowAlphaChannel ); #endif if ( !color.isValid() ) return; mLayer->setBorderColor( color ); btnChangeBorderColor->setColor( mLayer->borderColor() ); emit changed(); } void QgsSimpleFillSymbolLayerV2Widget::setBrushStyle() { mLayer->setBrushStyle( cboFillStyle->brushStyle() ); emit changed(); } void QgsSimpleFillSymbolLayerV2Widget::borderWidthChanged() { mLayer->setBorderWidth( spinBorderWidth->value() ); emit changed(); } void QgsSimpleFillSymbolLayerV2Widget::borderStyleChanged() { mLayer->setBorderStyle( cboBorderStyle->penStyle() ); emit changed(); } void QgsSimpleFillSymbolLayerV2Widget::offsetChanged() { mLayer->setOffset( QPointF( spinOffsetX->value(), spinOffsetY->value() ) ); emit changed(); } /////////// QgsMarkerLineSymbolLayerV2Widget::QgsMarkerLineSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); connect( spinInterval, SIGNAL( valueChanged( double ) ), this, SLOT( setInterval( double ) ) ); connect( chkRotateMarker, SIGNAL( clicked() ), this, SLOT( setRotate() ) ); connect( spinOffset, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); connect( radInterval, SIGNAL( clicked() ), this, SLOT( setPlacement() ) ); connect( radVertex, SIGNAL( clicked() ), this, SLOT( setPlacement() ) ); connect( radVertexLast, SIGNAL( clicked() ), this, SLOT( setPlacement() ) ); connect( radVertexFirst, SIGNAL( clicked() ), this, SLOT( setPlacement() ) ); connect( radCentralPoint, SIGNAL( clicked() ), this, SLOT( setPlacement() ) ); } void QgsMarkerLineSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "MarkerLine" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsMarkerLineSymbolLayerV2*>( layer ); // set values spinInterval->setValue( mLayer->interval() ); chkRotateMarker->setChecked( mLayer->rotateMarker() ); spinOffset->setValue( mLayer->offset() ); if ( mLayer->placement() == QgsMarkerLineSymbolLayerV2::Interval ) radInterval->setChecked( true ); else if ( mLayer->placement() == QgsMarkerLineSymbolLayerV2::Vertex ) radVertex->setChecked( true ); else if ( mLayer->placement() == QgsMarkerLineSymbolLayerV2::LastVertex ) radVertexLast->setChecked( true ); else if ( mLayer->placement() == QgsMarkerLineSymbolLayerV2::CentralPoint ) radCentralPoint->setChecked( true ); else radVertexFirst->setChecked( true ); setPlacement(); // update gui } QgsSymbolLayerV2* QgsMarkerLineSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsMarkerLineSymbolLayerV2Widget::setInterval( double val ) { mLayer->setInterval( val ); emit changed(); } void QgsMarkerLineSymbolLayerV2Widget::setRotate() { mLayer->setRotateMarker( chkRotateMarker->isChecked() ); emit changed(); } void QgsMarkerLineSymbolLayerV2Widget::setOffset() { mLayer->setOffset( spinOffset->value() ); emit changed(); } void QgsMarkerLineSymbolLayerV2Widget::setPlacement() { bool interval = radInterval->isChecked(); spinInterval->setEnabled( interval ); //mLayer->setPlacement( interval ? QgsMarkerLineSymbolLayerV2::Interval : QgsMarkerLineSymbolLayerV2::Vertex ); if ( radInterval->isChecked() ) mLayer->setPlacement( QgsMarkerLineSymbolLayerV2::Interval ); else if ( radVertex->isChecked() ) mLayer->setPlacement( QgsMarkerLineSymbolLayerV2::Vertex ); else if ( radVertexLast->isChecked() ) mLayer->setPlacement( QgsMarkerLineSymbolLayerV2::LastVertex ); else if ( radVertexFirst->isChecked() ) mLayer->setPlacement( QgsMarkerLineSymbolLayerV2::FirstVertex ); else mLayer->setPlacement( QgsMarkerLineSymbolLayerV2::CentralPoint ); emit changed(); } /////////// QgsSvgMarkerSymbolLayerV2Widget::QgsSvgMarkerSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); viewGroups->setHeaderHidden( true ); populateList(); connect( viewImages->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setName( const QModelIndex& ) ) ); connect( viewGroups->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( populateIcons( const QModelIndex& ) ) ); connect( spinSize, SIGNAL( valueChanged( double ) ), this, SLOT( setSize() ) ); connect( spinAngle, SIGNAL( valueChanged( double ) ), this, SLOT( setAngle() ) ); connect( spinOffsetX, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); connect( spinOffsetY, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); } #include <QTime> #include <QAbstractListModel> #include <QPixmapCache> #include <QStyle> class QgsSvgListModel : public QAbstractListModel { public: QgsSvgListModel( QObject* parent ) : QAbstractListModel( parent ) { mSvgFiles = QgsSymbolLayerV2Utils::listSvgFiles(); } // Constructor to create model for icons in a specific path QgsSvgListModel( QObject* parent, QString path ) : QAbstractListModel( parent ) { mSvgFiles = QgsSymbolLayerV2Utils::listSvgFilesAt( path ); } int rowCount( const QModelIndex & parent = QModelIndex() ) const { Q_UNUSED( parent ); return mSvgFiles.count(); } QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const { QString entry = mSvgFiles.at( index.row() ); if ( role == Qt::DecorationRole ) // icon { QPixmap pixmap; if ( !QPixmapCache::find( entry, pixmap ) ) { // render SVG file QColor fill, outline; double outlineWidth; bool fillParam, outlineParam, outlineWidthParam; QgsSvgCache::instance()->containsParams( entry, fillParam, fill, outlineParam, outline, outlineWidthParam, outlineWidth ); const QImage& img = QgsSvgCache::instance()->svgAsImage( entry, 30, fill, outline, outlineWidth, 3.5 /*appr. 88 dpi*/, 1.0 ); pixmap = QPixmap::fromImage( img ); QPixmapCache::insert( entry, pixmap ); } return pixmap; } else if ( role == Qt::UserRole || role == Qt::ToolTipRole ) { return entry; } return QVariant(); } protected: QStringList mSvgFiles; }; class QgsSvgGroupsModel : public QStandardItemModel { public: QgsSvgGroupsModel( QObject* parent ) : QStandardItemModel( parent ) { QStringList svgPaths = QgsApplication::svgPaths(); QStandardItem *parentItem = invisibleRootItem(); for ( int i = 0; i < svgPaths.size(); i++ ) { QDir dir( svgPaths[i] ); QStandardItem *baseGroup; if ( dir.path().contains( QgsApplication::pkgDataPath() ) ) { baseGroup = new QStandardItem( QString( "App Symbols" ) ); } else if ( dir.path().contains( QgsApplication::qgisSettingsDirPath() ) ) { baseGroup = new QStandardItem( QString( "User Symbols" ) ); } else { baseGroup = new QStandardItem( dir.dirName() ); } baseGroup->setData( QVariant( svgPaths[i] ) ); baseGroup->setEditable( false ); baseGroup->setCheckable( false ); baseGroup->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); baseGroup->setToolTip( dir.path() ); parentItem->appendRow( baseGroup ); createTree( baseGroup ); QgsDebugMsg( QString( "SVG base path %1: %2" ).arg( i ).arg( baseGroup->data().toString() ) ); } } private: void createTree( QStandardItem* &parentGroup ) { QDir parentDir( parentGroup->data().toString() ); foreach ( QString item, parentDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) { QStandardItem* group = new QStandardItem( item ); group->setData( QVariant( parentDir.path() + "/" + item ) ); group->setEditable( false ); group->setCheckable( false ); group->setToolTip( parentDir.path() + "/" + item ); group->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); parentGroup->appendRow( group ); createTree( group ); } } }; void QgsSvgMarkerSymbolLayerV2Widget::populateList() { QgsSvgGroupsModel* g = new QgsSvgGroupsModel( viewGroups ); viewGroups->setModel( g ); // Set the tree expanded at the first level int rows = g->rowCount( g->indexFromItem( g->invisibleRootItem() ) ); for ( int i = 0; i < rows; i++ ) { viewGroups->setExpanded( g->indexFromItem( g->item( i ) ), true ); } // Initally load the icons in the List view without any grouping QgsSvgListModel* m = new QgsSvgListModel( viewImages ); viewImages->setModel( m ); } void QgsSvgMarkerSymbolLayerV2Widget::populateIcons( const QModelIndex& idx ) { QString path = idx.data( Qt::UserRole + 1 ).toString(); QgsSvgListModel* m = new QgsSvgListModel( viewImages, path ); viewImages->setModel( m ); connect( viewImages->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setName( const QModelIndex& ) ) ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::setGuiForSvg( const QgsSvgMarkerSymbolLayerV2* layer ) { if ( !layer ) { return; } //activate gui for svg parameters only if supported by the svg file bool hasFillParam, hasOutlineParam, hasOutlineWidthParam; QColor defaultFill, defaultOutline; double defaultOutlineWidth; QgsSvgCache::instance()->containsParams( layer->path(), hasFillParam, defaultFill, hasOutlineParam, defaultOutline, hasOutlineWidthParam, defaultOutlineWidth ); mChangeColorButton->setEnabled( hasFillParam ); mChangeBorderColorButton->setEnabled( hasOutlineParam ); mBorderWidthSpinBox->setEnabled( hasOutlineWidthParam ); if ( hasFillParam ) mChangeColorButton->setColor( defaultFill ); if ( hasOutlineParam ) mChangeBorderColorButton->setColor( defaultOutline ); mFileLineEdit->blockSignals( true ); mFileLineEdit->setText( layer->path() ); mFileLineEdit->blockSignals( false ); mBorderWidthSpinBox->blockSignals( true ); mBorderWidthSpinBox->setValue( layer->outlineWidth() ); mBorderWidthSpinBox->blockSignals( false ); } void QgsSvgMarkerSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( !layer ) { return; } if ( layer->layerType() != "SvgMarker" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsSvgMarkerSymbolLayerV2*>( layer ); // set values QAbstractItemModel* m = viewImages->model(); QItemSelectionModel* selModel = viewImages->selectionModel(); for ( int i = 0; i < m->rowCount(); i++ ) { QModelIndex idx( m->index( i, 0 ) ); if ( m->data( idx ).toString() == mLayer->path() ) { selModel->select( idx, QItemSelectionModel::SelectCurrent ); selModel->setCurrentIndex( idx, QItemSelectionModel::SelectCurrent ); setName( idx ); break; } } spinSize->setValue( mLayer->size() ); spinAngle->setValue( mLayer->angle() ); // without blocking signals the value gets changed because of slot setOffset() spinOffsetX->blockSignals( true ); spinOffsetX->setValue( mLayer->offset().x() ); spinOffsetX->blockSignals( false ); spinOffsetY->blockSignals( true ); spinOffsetY->setValue( mLayer->offset().y() ); spinOffsetY->blockSignals( false ); setGuiForSvg( mLayer ); } QgsSymbolLayerV2* QgsSvgMarkerSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsSvgMarkerSymbolLayerV2Widget::setName( const QModelIndex& idx ) { QString name = idx.data( Qt::UserRole ).toString(); mLayer->setPath( name ); mFileLineEdit->setText( name ); setGuiForSvg( mLayer ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::setSize() { mLayer->setSize( spinSize->value() ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::setAngle() { mLayer->setAngle( spinAngle->value() ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::setOffset() { mLayer->setOffset( QPointF( spinOffsetX->value(), spinOffsetY->value() ) ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::on_mFileToolButton_clicked() { QSettings s; QString file = QFileDialog::getOpenFileName( 0, tr( "Select SVG file" ), s.value( "/UI/lastSVGMarkerDir" ).toString(), tr( "SVG files" ) + " (*.svg)" ); QFileInfo fi( file ); if ( file.isEmpty() || !fi.exists() ) { return; } mFileLineEdit->setText( file ); mLayer->setPath( file ); s.setValue( "/UI/lastSVGMarkerDir", fi.absolutePath() ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::on_mFileLineEdit_textEdited( const QString& text ) { if ( !QFileInfo( text ).exists() ) { return; } mLayer->setPath( text ); setGuiForSvg( mLayer ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::on_mFileLineEdit_editingFinished() { if ( !QFileInfo( mFileLineEdit->text() ).exists() ) { QUrl url( mFileLineEdit->text() ); if ( !url.isValid() ) { return; } } QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) ); mLayer->setPath( mFileLineEdit->text() ); QApplication::restoreOverrideCursor(); setGuiForSvg( mLayer ); emit changed(); } void QgsSvgMarkerSymbolLayerV2Widget::on_mChangeColorButton_clicked() { if ( !mLayer ) { return; } QColor c = QColorDialog::getColor( mLayer->fillColor() ); if ( c.isValid() ) { mLayer->setFillColor( c ); mChangeColorButton->setColor( c ); emit changed(); } } void QgsSvgMarkerSymbolLayerV2Widget::on_mChangeBorderColorButton_clicked() { if ( !mLayer ) { return; } QColor c = QColorDialog::getColor( mLayer->outlineColor() ); if ( c.isValid() ) { mLayer->setOutlineColor( c ); mChangeBorderColorButton->setColor( c ); emit changed(); } } void QgsSvgMarkerSymbolLayerV2Widget::on_mBorderWidthSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setOutlineWidth( d ); emit changed(); } } /////////////// QgsLineDecorationSymbolLayerV2Widget::QgsLineDecorationSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); connect( btnChangeColor, SIGNAL( clicked() ), this, SLOT( colorChanged() ) ); connect( spinWidth, SIGNAL( valueChanged( double ) ), this, SLOT( penWidthChanged() ) ); } void QgsLineDecorationSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "LineDecoration" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsLineDecorationSymbolLayerV2*>( layer ); // set values btnChangeColor->setColor( mLayer->color() ); spinWidth->setValue( mLayer->width() ); } QgsSymbolLayerV2* QgsLineDecorationSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsLineDecorationSymbolLayerV2Widget::colorChanged() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::DontUseNativeDialog ); #else QColor color = QColorDialog::getColor( mLayer->color(), this ); #endif if ( !color.isValid() ) return; mLayer->setColor( color ); btnChangeColor->setColor( mLayer->color() ); emit changed(); } void QgsLineDecorationSymbolLayerV2Widget::penWidthChanged() { mLayer->setWidth( spinWidth->value() ); emit changed(); } ///////////// #include <QFileDialog> QgsSVGFillSymbolLayerWidget::QgsSVGFillSymbolLayerWidget( const QgsVectorLayer* vl, QWidget* parent ): QgsSymbolLayerV2Widget( parent, vl ) { mLayer = 0; setupUi( this ); mSvgTreeView->setHeaderHidden( true ); insertIcons(); connect( mSvgListView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setFile( const QModelIndex& ) ) ); connect( mSvgTreeView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( populateIcons( const QModelIndex& ) ) ); } void QgsSVGFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( !layer ) { return; } if ( layer->layerType() != "SVGFill" ) { return; } mLayer = dynamic_cast<QgsSVGFillSymbolLayer*>( layer ); if ( mLayer ) { double width = mLayer->patternWidth(); mTextureWidthSpinBox->setValue( width ); mSVGLineEdit->setText( mLayer->svgFilePath() ); mRotationSpinBox->setValue( mLayer->angle() ); } updateParamGui(); } QgsSymbolLayerV2* QgsSVGFillSymbolLayerWidget::symbolLayer() { return mLayer; } void QgsSVGFillSymbolLayerWidget::on_mBrowseToolButton_clicked() { QString filePath = QFileDialog::getOpenFileName( 0, tr( "Select svg texture file" ) ); if ( !filePath.isNull() ) { mSVGLineEdit->setText( filePath ); emit changed(); } } void QgsSVGFillSymbolLayerWidget::on_mTextureWidthSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setPatternWidth( d ); emit changed(); } } void QgsSVGFillSymbolLayerWidget::on_mSVGLineEdit_textEdited( const QString & text ) { if ( !mLayer ) { return; } QFileInfo fi( text ); if ( !fi.exists() ) { return; } mLayer->setSvgFilePath( text ); updateParamGui(); emit changed(); } void QgsSVGFillSymbolLayerWidget::on_mSVGLineEdit_editingFinished() { if ( !mLayer ) { return; } QFileInfo fi( mSVGLineEdit->text() ); if ( !fi.exists() ) { QUrl url( mSVGLineEdit->text() ); if ( !url.isValid() ) { return; } } QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) ); mLayer->setSvgFilePath( mSVGLineEdit->text() ); QApplication::restoreOverrideCursor(); updateParamGui(); emit changed(); } void QgsSVGFillSymbolLayerWidget::setFile( const QModelIndex& item ) { QString file = item.data( Qt::UserRole ).toString(); mLayer->setSvgFilePath( file ); mSVGLineEdit->setText( file ); updateParamGui(); emit changed(); } void QgsSVGFillSymbolLayerWidget::insertIcons() { QgsSvgGroupsModel* g = new QgsSvgGroupsModel( mSvgTreeView ); mSvgTreeView->setModel( g ); // Set the tree expanded at the first level int rows = g->rowCount( g->indexFromItem( g->invisibleRootItem() ) ); for ( int i = 0; i < rows; i++ ) { mSvgTreeView->setExpanded( g->indexFromItem( g->item( i ) ), true ); } QgsSvgListModel* m = new QgsSvgListModel( mSvgListView ); mSvgListView->setModel( m ); } void QgsSVGFillSymbolLayerWidget::populateIcons( const QModelIndex& idx ) { QString path = idx.data( Qt::UserRole + 1 ).toString(); QgsSvgListModel* m = new QgsSvgListModel( mSvgListView, path ); mSvgListView->setModel( m ); connect( mSvgListView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setFile( const QModelIndex& ) ) ); emit changed(); } void QgsSVGFillSymbolLayerWidget::on_mRotationSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setAngle( d ); emit changed(); } } void QgsSVGFillSymbolLayerWidget::updateParamGui() { //activate gui for svg parameters only if supported by the svg file bool hasFillParam, hasOutlineParam, hasOutlineWidthParam; QColor defaultFill, defaultOutline; double defaultOutlineWidth; QgsSvgCache::instance()->containsParams( mSVGLineEdit->text(), hasFillParam, defaultFill, hasOutlineParam, defaultOutline, hasOutlineWidthParam, defaultOutlineWidth ); if ( hasFillParam ) mChangeColorButton->setColor( defaultFill ); mChangeColorButton->setEnabled( hasFillParam ); if ( hasOutlineParam ) mChangeBorderColorButton->setColor( defaultOutline ); mChangeBorderColorButton->setEnabled( hasOutlineParam ); mBorderWidthSpinBox->setEnabled( hasOutlineWidthParam ); } void QgsSVGFillSymbolLayerWidget::on_mChangeColorButton_clicked() { if ( !mLayer ) { return; } QColor c = QColorDialog::getColor( mLayer->svgFillColor() ); if ( c.isValid() ) { mLayer->setSvgFillColor( c ); mChangeColorButton->setColor( c ); emit changed(); } } void QgsSVGFillSymbolLayerWidget::on_mChangeBorderColorButton_clicked() { if ( !mLayer ) { return; } QColor c = QColorDialog::getColor( mLayer->svgOutlineColor() ); if ( c.isValid() ) { mLayer->setSvgOutlineColor( c ); mChangeBorderColorButton->setColor( c ); emit changed(); } } void QgsSVGFillSymbolLayerWidget::on_mBorderWidthSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setSvgOutlineWidth( d ); emit changed(); } } ///////////// QgsLinePatternFillSymbolLayerWidget::QgsLinePatternFillSymbolLayerWidget( const QgsVectorLayer* vl, QWidget* parent ): QgsSymbolLayerV2Widget( parent, vl ), mLayer( 0 ) { setupUi( this ); } void QgsLinePatternFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "LinePatternFill" ) { return; } QgsLinePatternFillSymbolLayer* patternLayer = static_cast<QgsLinePatternFillSymbolLayer*>( layer ); if ( patternLayer ) { mLayer = patternLayer; mAngleSpinBox->setValue( mLayer->lineAngle() ); mDistanceSpinBox->setValue( mLayer->distance() ); mLineWidthSpinBox->setValue( mLayer->lineWidth() ); mOffsetSpinBox->setValue( mLayer->offset() ); mColorPushButton->setColor( mLayer->color() ); } } QgsSymbolLayerV2* QgsLinePatternFillSymbolLayerWidget::symbolLayer() { return mLayer; } void QgsLinePatternFillSymbolLayerWidget::on_mAngleSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setLineAngle( d ); emit changed(); } } void QgsLinePatternFillSymbolLayerWidget::on_mDistanceSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setDistance( d ); emit changed(); } } void QgsLinePatternFillSymbolLayerWidget::on_mLineWidthSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setLineWidth( d ); emit changed(); } } void QgsLinePatternFillSymbolLayerWidget::on_mOffsetSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setOffset( d ); emit changed(); } } void QgsLinePatternFillSymbolLayerWidget::on_mColorPushButton_clicked() { if ( mLayer ) { QColor c = QColorDialog::getColor( mLayer->color() ); if ( c.isValid() ) { mLayer->setColor( c ); mColorPushButton->setColor( c ); emit changed(); } } } ///////////// QgsPointPatternFillSymbolLayerWidget::QgsPointPatternFillSymbolLayerWidget( const QgsVectorLayer* vl, QWidget* parent ): QgsSymbolLayerV2Widget( parent, vl ), mLayer( 0 ) { setupUi( this ); } void QgsPointPatternFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( !layer || layer->layerType() != "PointPatternFill" ) { return; } mLayer = static_cast<QgsPointPatternFillSymbolLayer*>( layer ); mHorizontalDistanceSpinBox->setValue( mLayer->distanceX() ); mVerticalDistanceSpinBox->setValue( mLayer->distanceY() ); mHorizontalDisplacementSpinBox->setValue( mLayer->displacementX() ); mVerticalDisplacementSpinBox->setValue( mLayer->displacementY() ); } QgsSymbolLayerV2* QgsPointPatternFillSymbolLayerWidget::symbolLayer() { return mLayer; } void QgsPointPatternFillSymbolLayerWidget::on_mHorizontalDistanceSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setDistanceX( d ); emit changed(); } } void QgsPointPatternFillSymbolLayerWidget::on_mVerticalDistanceSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setDistanceY( d ); emit changed(); } } void QgsPointPatternFillSymbolLayerWidget::on_mHorizontalDisplacementSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setDisplacementX( d ); emit changed(); } } void QgsPointPatternFillSymbolLayerWidget::on_mVerticalDisplacementSpinBox_valueChanged( double d ) { if ( mLayer ) { mLayer->setDisplacementY( d ); emit changed(); } } ///////////// QgsFontMarkerSymbolLayerV2Widget::QgsFontMarkerSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); widgetChar = new CharacterWidget; scrollArea->setWidget( widgetChar ); connect( cboFont, SIGNAL( currentFontChanged( const QFont & ) ), this, SLOT( setFontFamily( const QFont& ) ) ); connect( spinSize, SIGNAL( valueChanged( double ) ), this, SLOT( setSize( double ) ) ); connect( btnColor, SIGNAL( clicked() ), this, SLOT( setColor() ) ); connect( spinAngle, SIGNAL( valueChanged( double ) ), this, SLOT( setAngle( double ) ) ); connect( spinOffsetX, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); connect( spinOffsetY, SIGNAL( valueChanged( double ) ), this, SLOT( setOffset() ) ); connect( widgetChar, SIGNAL( characterSelected( const QChar & ) ), this, SLOT( setCharacter( const QChar & ) ) ); } void QgsFontMarkerSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "FontMarker" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsFontMarkerSymbolLayerV2*>( layer ); // set values cboFont->setCurrentFont( QFont( mLayer->fontFamily() ) ); spinSize->setValue( mLayer->size() ); btnColor->setColor( mLayer->color() ); spinAngle->setValue( mLayer->angle() ); //block spinOffsetX->blockSignals( true ); spinOffsetX->setValue( mLayer->offset().x() ); spinOffsetX->blockSignals( false ); spinOffsetY->blockSignals( true ); spinOffsetY->setValue( mLayer->offset().y() ); spinOffsetY->blockSignals( false ); } QgsSymbolLayerV2* QgsFontMarkerSymbolLayerV2Widget::symbolLayer() { return mLayer; } void QgsFontMarkerSymbolLayerV2Widget::setFontFamily( const QFont& font ) { mLayer->setFontFamily( font.family() ); widgetChar->updateFont( font ); emit changed(); } void QgsFontMarkerSymbolLayerV2Widget::setColor() { #if defined(Q_WS_MAC) && QT_VERSION >= 0x040500 && defined(QT_MAC_USE_COCOA) // Native Mac dialog works only for Qt Carbon // Qt bug: http://bugreports.qt.nokia.com/browse/QTBUG-14889 // FIXME need to also check max QT_VERSION when Qt bug fixed QColor color = QColorDialog::getColor( mLayer->color(), this, "", QColorDialog::DontUseNativeDialog ); #else QColor color = QColorDialog::getColor( mLayer->color(), this ); #endif if ( !color.isValid() ) return; mLayer->setColor( color ); btnColor->setColor( mLayer->color() ); emit changed(); } void QgsFontMarkerSymbolLayerV2Widget::setSize( double size ) { mLayer->setSize( size ); //widgetChar->updateSize(size); emit changed(); } void QgsFontMarkerSymbolLayerV2Widget::setAngle( double angle ) { mLayer->setAngle( angle ); emit changed(); } void QgsFontMarkerSymbolLayerV2Widget::setCharacter( const QChar& chr ) { mLayer->setCharacter( chr ); emit changed(); } void QgsFontMarkerSymbolLayerV2Widget::setOffset() { mLayer->setOffset( QPointF( spinOffsetX->value(), spinOffsetY->value() ) ); emit changed(); } /////////////// QgsCentroidFillSymbolLayerV2Widget::QgsCentroidFillSymbolLayerV2Widget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerV2Widget( parent, vl ) { mLayer = NULL; setupUi( this ); } void QgsCentroidFillSymbolLayerV2Widget::setSymbolLayer( QgsSymbolLayerV2* layer ) { if ( layer->layerType() != "CentroidFill" ) return; // layer type is correct, we can do the cast mLayer = static_cast<QgsCentroidFillSymbolLayerV2*>( layer ); } QgsSymbolLayerV2* QgsCentroidFillSymbolLayerV2Widget::symbolLayer() { return mLayer; }
gpl-2.0
mambax7/oledrion
download.php
3107
<?php /* You may not change or alter any portion of this comment or credits of supporting developers from this source code or any supporting source code which is considered copyrighted (c) material of the original comment or credit authors. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /** * oledrion * * @copyright {@link https://xoops.org/ XOOPS Project} * @license {@link http://www.fsf.org/copyleft/gpl.html GNU public license} * @author Hervé Thouzard (http://www.herve-thouzard.com/) */ /** * Téléchargement de fichier après passage d'une commande (et validation de celle-ci) */ use Xmf\Request; use XoopsModules\Oledrion; require_once __DIR__ . '/header.php'; error_reporting(0); @$xoopsLogger->activated = false; $download_id = Request::getString('download_id', '', 'GET'); // TODO: Permettre au webmaster de réactiver un téléchargement if ('' === xoops_trim($download_id)) { Oledrion\Utility::redirect(_OLEDRION_ERROR13, OLEDRION_URL, 5); } // Recherche dans les caddy du produit associé $caddy = null; $caddy = $caddyHandler->getCaddyFromPassword($download_id); if (!is_object($caddy)) { Oledrion\Utility::redirect(_OLEDRION_ERROR14, OLEDRION_URL, 5); } // Recherche du produit associé $product = null; $product = $productsHandler->get($caddy->getVar('caddy_product_id')); if (null === $product) { Oledrion\Utility::redirect(_OLEDRION_ERROR15, OLEDRION_URL, 5); } // On vérifie que la commande associée est payée $order = null; $order = $commandsHandler->get($caddy->getVar('caddy_cmd_id')); if (null === $order) { Oledrion\Utility::redirect(_OLEDRION_ERROR16, OLEDRION_URL, 5); } // Tout est bon, on peut envoyer le fichier au navigateur, s'il y a un fichier à télécharger, et s'il existe $file = ''; $file = $product->getVar('product_download_url'); if ('' === xoops_trim($file)) { Oledrion\Utility::redirect(_OLEDRION_ERROR17, OLEDRION_URL, 5); } if (!file_exists($file)) { Oledrion\Utility::redirect(_OLEDRION_ERROR18, OLEDRION_URL, 5); } // Mise à jour, le fichier n'est plus disponible au téléchargement $caddyHandler->markCaddyAsNotDownloadableAnyMore($caddy); $fileContent = file_get_contents($file); // Plugins ************************************************ $plugins = Oledrion\Plugin::getInstance(); $parameters = new Oledrion\Parameters( [ 'fileContent' => $fileContent, 'product' => $product, 'order' => $order, 'fullFilename' => $file, ] ); $parameters = $plugins->fireFilter(Oledrion\Plugin::EVENT_ON_PRODUCT_DOWNLOAD, $parameters); if ('' !== trim($parameters['fileContent'])) { $fileContent = $parameters['fileContent']; } // ********************************************************* // Et affichage du fichier avec le type mime qui va bien header('Content-Type: ' . Oledrion\Utility::getMimeType($file)); header('Content-disposition: inline; filename="' . basename($file) . '"'); echo $fileContent;
gpl-2.0
centreon/centreon
lib/Centreon/Object/Dependency/DependencyHostParent.php
1596
<?php /* * Copyright 2005 - 2020 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once "Centreon/Object/Object.php"; /** * Used for interacting with dependencies * */ class Centreon_Object_DependencyHostParent extends Centreon_Object { protected $table = "dependency_hostParent_relation"; protected $primaryKey = "dependency_dep_id"; public function removeRelationLastHostDependency(int $hostId): void { $query = 'SELECT count(dependency_dep_id) AS nb_dependency , dependency_dep_id AS id FROM dependency_hostParent_relation WHERE dependency_dep_id = (SELECT dependency_dep_id FROM dependency_hostParent_relation WHERE host_host_id = ?)'; $result = $this->getResult($query, array($hostId), "fetch"); //is last parent if ($result['nb_dependency'] == 1) { $this->db->query("DELETE FROM dependency WHERE dep_id = " . $result['id']); } } }
gpl-2.0
rex-xxx/mt6572_x201
packages/apps/Exchange/exchange2/src/com/android/exchange/PartRequest.java
1926
/* * Copyright (C) 2008-2009 Marc Blank * Licensed to The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange; import com.android.emailcommon.provider.EmailContent.Attachment; /** * PartRequest is the EAS wrapper for attachment loading requests. In addition to information about * the attachment to be loaded, it also contains the callback to be used for status/progress * updates to the UI. */ public class PartRequest extends Request { public final Attachment mAttachment; public final String mDestination; public final String mContentUriString; public final String mLocation; public volatile boolean mCancelled = false; public PartRequest(Attachment att, String destination, String contentUriString) { super(att.mMessageKey); mAttachment = att; mLocation = mAttachment.mLocation; mDestination = destination; mContentUriString = contentUriString; } // PartRequests are unique by their attachment id (i.e. multiple attachments might be queued // for a particular message, but any individual attachment can only be loaded once) public boolean equals(Object o) { if (!(o instanceof PartRequest)) return false; return ((PartRequest)o).mAttachment.mId == mAttachment.mId; } public int hashCode() { return (int)mAttachment.mId; } }
gpl-2.0
DriwFS/Angas-Engine
SDK/src/org/diverproject/angas/resource/Texture.java
2791
package org.diverproject.angas.resource; import static org.diverproject.log.LogSystem.logDebug; import org.diverproject.angas.Graphic; /** * <p><h1>Textura</h1></p> * * <p>Utilizado para que seja possível trabalhar com recursos do tipo imagem (texturas). * Texturas normalmente são utilizadas para renderizar determinados objetos no jogo. * Como por exemplo personagens, mapas, efeito, interface gráfica do usuário e outros.</p> * * @see Resource * * @author Andrew */ public class Texture extends Resource { /** * Referência do gerenciador gráfico que será usado pela textura. */ Graphic graphic; /** * Constrói uma nova textura a partir de uma raíz de textura especifica. * @param root referência da raíz da textura que será usada para criar a textura. */ public Texture(TextureRoot root) { super(root); if (root == null) logDebug("Texture: raíz nula sendo usada para nova textura?"); } /** * Constrói uma nova textura a partir do caminho de um arquivo no disco. * Verifica se há uma raíz existente desse arquivo e se houver irá utilizá-la. * Caso contrário irá criar uma raíz referente ao arquivo e usar essa para tal. * @param filePath caminho do arquivo em disco respectivo ao diretório para recursos. */ public Texture(String filePath) { super(null); ResourceManager manager = ResourceManager.getIntance(); root = manager.getResource(filePath); if (root == null) root = new TextureRoot(filePath); } /** * Toda textura é formada por uma imagem do qual podemos dimensionar. * @return aquisição do tamanho da largura da imagem em pixels. */ public int getWidth() { return root != null ? ((TextureRoot) root).getBufferedImage().getWidth() : 0; } /** * Toda textura é formada por uma imagem do qual podemos dimensionar. * @return aquisição do tamanho da altura da imagem em pixels. */ public int getHeight() { return root != null ? ((TextureRoot) root).getBufferedImage().getHeight() : 0; } /** * Para que seja possível trabalhar com a textura um controlador gráfico pode ser usado. * @return aquisição do controlador gráfico referente a textura usada ou null se raíz nula. */ public Graphic getGraphic() { if (graphic == null && root != null) graphic = new Graphic(((TextureRoot) root).getBufferedImage()); return graphic; } @Override public void release() { if (root != null) { root.delReference(this); root = null; } if (graphic != null) { graphic.release(); graphic = null; } } @Override public String toStringBody() { return String.format("width: %d, height: %d, %s", getWidth(), getHeight(), super.toStringBody()); } }
gpl-2.0
froksen/FDesktopRecorder
src/module/recordingdevices.cpp
2096
#include "recordingdevices.h" #include <QProcess> #include <QDebug> RecordingDevices::RecordingDevices(QObject *parent) : QObject(parent) { } void RecordingDevices::getRecorddevices(){ //Clears old values RecordDeviceDesc.clear(); RecordDeviceHW.clear(); QProcess p; p.start("arecord -l"); p.waitForFinished(-1); QString p_stdout = p.readAllStandardOutput(); QString p_stderr = p.readAllStandardError(); QTextStream in(&p_stdout); while ( !in.atEnd() ) { QString line = in.readLine(); if(line.left(4) == "card"){ QString orgline = line; // Gets the cardnumber QString CardHW; CardHW = line.remove(6,100); CardHW = line.remove(0,5); //Gets the devicenumber QRegExp devicepattern("(device\\s\\d)"); QString devicenumber; int pos = devicepattern.indexIn(orgline); if (pos > -1) { devicenumber = devicepattern.cap(1); QRegExp patternDVremove ("device\\s"); devicenumber = devicenumber.remove(patternDVremove); } //Adding Cardnumber and devicenumber CardHW = "hw:" + CardHW +","+devicenumber; RecordDeviceHW << CardHW; //Gets the Card Description QRegExp patternCard ("^card\\s\\d:\\s"); QRegExp patternDV2remove ("device\\s\\d.."); QString CardDesc; CardDesc = orgline.remove(patternCard); CardDesc = CardDesc.remove(patternDV2remove); CardDesc = "(" + CardHW + ") " + CardDesc; RecordDeviceDesc << CardDesc; } } RecordDeviceDesc << trUtf8("Pulse Audio (might not work)"); RecordDeviceHW << "pulse"; RecordDeviceDesc << trUtf8("Other"); RecordDeviceHW << ""; qDebug() << "Record devices found:"; foreach(QString device, RecordDeviceDesc){ qDebug() << "-" << device; } }
gpl-2.0
lclsdu/CS
jspxcms/src/com/jspxcms/core/security/CmsLogoutFilter.java
2118
package com.jspxcms.core.security; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authc.LogoutFilter; import org.springframework.beans.factory.annotation.Autowired; import com.jspxcms.common.web.Servlets; import com.jspxcms.core.service.OperationLogService; import com.jspxcms.core.support.Constants; public class CmsLogoutFilter extends LogoutFilter { /** * 返回URL */ public static final String FALLBACK_URL_PARAM = "fallbackUrl"; /** * 后台路径 */ private String backUrl = Constants.CMSCP + "/"; private String backRedirectUrl = Constants.BACK_SUCCESS_URL; @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); Object principal = subject.getPrincipal(); String ip = Servlets.getRemoteAddr(request); boolean result = super.preHandle(request, response); if (principal != null) { logService.logout(ip, principal.toString()); } return result; } protected String getRedirectUrl(ServletRequest req, ServletResponse resp, Subject subject) { HttpServletRequest request = (HttpServletRequest) req; String redirectUrl = request.getParameter(FALLBACK_URL_PARAM); if (StringUtils.isBlank(redirectUrl)) { if (request.getRequestURI().startsWith( request.getContextPath() + backUrl)) { redirectUrl = getBackRedirectUrl(); } else { redirectUrl = getRedirectUrl(); } } return redirectUrl; } public String getBackRedirectUrl() { return backRedirectUrl; } public void setBackRedirectUrl(String backRedirectUrl) { this.backRedirectUrl = backRedirectUrl; } public String getBackUrl() { return backUrl; } public void setBackUrl(String backUrl) { this.backUrl = backUrl; } private OperationLogService logService; @Autowired public void setOperationLogService(OperationLogService logService) { this.logService = logService; } }
gpl-2.0
koying/xbmc-vidonme
xbmc/interfaces/legacy/ListItem.cpp
20388
/* * Copyright (C) 2005-2013 Team XBMC * http://www.xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include <sstream> #include "ListItem.h" #include "AddonUtils.h" #include "video/VideoInfoTag.h" #include "music/tags/MusicInfoTag.h" #include "pictures/PictureInfoTag.h" #include "utils/log.h" #include "utils/Variant.h" #include "utils/StringUtils.h" #include "settings/AdvancedSettings.h" namespace XBMCAddon { namespace xbmcgui { ListItem::ListItem(const String& label, const String& label2, const String& iconImage, const String& thumbnailImage, const String& path) : AddonClass("ListItem") { item.reset(); // create CFileItem item.reset(new CFileItem()); if (!item) // not sure if this is really possible return; if (!label.empty()) item->SetLabel( label ); if (!label2.empty()) item->SetLabel2( label2 ); if (!iconImage.empty()) item->SetIconImage( iconImage ); if (!thumbnailImage.empty()) item->SetArt("thumb", thumbnailImage ); if (!path.empty()) item->SetPath(path); } ListItem::~ListItem() { item.reset(); } String ListItem::getLabel() { if (!item) return ""; String ret; { LOCKGUI; ret = item->GetLabel(); } return ret; } String ListItem::getLabel2() { if (!item) return ""; String ret; { LOCKGUI; ret = item->GetLabel2(); } return ret; } void ListItem::setLabel(const String& label) { if (!item) return; // set label { LOCKGUI; item->SetLabel(label); } } void ListItem::setLabel2(const String& label) { if (!item) return; // set label { LOCKGUI; item->SetLabel2(label); } } void ListItem::setIconImage(const String& iconImage) { if (!item) return; { LOCKGUI; item->SetIconImage(iconImage); } } void ListItem::setThumbnailImage(const String& thumbFilename) { if (!item) return; { LOCKGUI; item->SetArt("thumb", thumbFilename); } } void ListItem::select(bool selected) { if (!item) return; { LOCKGUI; item->Select(selected); } } bool ListItem::isSelected() { if (!item) return false; bool ret; { LOCKGUI; ret = item->IsSelected(); } return ret; } void ListItem::setProperty(const char * key, const String& value) { LOCKGUI; CStdString lowerKey = key; if (lowerKey.CompareNoCase("startoffset") == 0) { // special case for start offset - don't actually store in a property, // we store it in item.m_lStartOffset instead item->m_lStartOffset = (int)(atof(value.c_str()) * 75.0); // we store the offset in frames, or 1/75th of a second } else if (lowerKey.CompareNoCase("mimetype") == 0) { // special case for mime type - don't actually stored in a property, item->SetMimeType(value.c_str()); } else if (lowerKey.CompareNoCase("totaltime") == 0) item->GetVideoInfoTag()->m_resumePoint.totalTimeInSeconds = (float)atof(value.c_str()); else if (lowerKey.CompareNoCase("resumetime") == 0) item->GetVideoInfoTag()->m_resumePoint.timeInSeconds = (float)atof(value.c_str()); else if (lowerKey.CompareNoCase("specialsort") == 0) { if (value == "bottom") item->SetSpecialSort(SortSpecialOnBottom); else if (value == "top") item->SetSpecialSort(SortSpecialOnTop); } else if (lowerKey.CompareNoCase("fanart_image") == 0) item->SetArt("fanart", value); else item->SetProperty(lowerKey.ToLower(), value.c_str()); } String ListItem::getProperty(const char* key) { LOCKGUI; CStdString lowerKey = key; CStdString value; if (lowerKey.CompareNoCase("startoffset") == 0) { // special case for start offset - don't actually store in a property, // we store it in item.m_lStartOffset instead value.Format("%f", item->m_lStartOffset / 75.0); } else if (lowerKey.CompareNoCase("totaltime") == 0) value.Format("%f", item->GetVideoInfoTag()->m_resumePoint.totalTimeInSeconds); else if (lowerKey.CompareNoCase("resumetime") == 0) value.Format("%f", item->GetVideoInfoTag()->m_resumePoint.timeInSeconds); else if (lowerKey.CompareNoCase("fanart_image") == 0) value = item->GetArt("fanart"); else value = item->GetProperty(lowerKey.ToLower()).asString(); return value.c_str(); } void ListItem::setPath(const String& path) { LOCKGUI; item->SetPath(path); } void ListItem::setMimeType(const String& mimetype) { LOCKGUI; item->SetMimeType(mimetype); } String ListItem::getdescription() { return item->GetLabel(); } String ListItem::getduration() { if (item->LoadMusicTag()) { std::ostringstream oss; oss << item->GetMusicInfoTag()->GetDuration(); return oss.str(); } if (item->HasVideoInfoTag()) { std::ostringstream oss; oss << item->GetVideoInfoTag()->GetDuration() / 60; return oss.str(); } return "0"; } String ListItem::getfilename() { return item->GetPath(); } void ListItem::setInfo(const char* type, const Dictionary& infoLabels) { LOCKGUI; if (strcmpi(type, "video") == 0) { for (Dictionary::const_iterator it = infoLabels.begin(); it != infoLabels.end(); it++) { CStdString key = it->first; key.ToLower(); const CStdString value(it->second.c_str()); if (key == "year") item->GetVideoInfoTag()->m_iYear = strtol(value.c_str(), NULL, 10); else if (key == "episode") item->GetVideoInfoTag()->m_iEpisode = strtol(value.c_str(), NULL, 10); else if (key == "season") item->GetVideoInfoTag()->m_iSeason = strtol(value.c_str(), NULL, 10); else if (key == "top250") item->GetVideoInfoTag()->m_iTop250 = strtol(value.c_str(), NULL, 10); else if (key == "tracknumber") item->GetVideoInfoTag()->m_iTrack = strtol(value.c_str(), NULL, 10); else if (key == "count") item->m_iprogramCount = strtol(value.c_str(), NULL, 10); else if (key == "rating") item->GetVideoInfoTag()->m_fRating = (float)strtod(value.c_str(), NULL); else if (key == "size") item->m_dwSize = (int64_t)strtoll(value.c_str(), NULL, 10); else if (key == "watched") // backward compat - do we need it? item->GetVideoInfoTag()->m_playCount = strtol(value.c_str(), NULL, 10); else if (key == "playcount") item->GetVideoInfoTag()->m_playCount = strtol(value.c_str(), NULL, 10); else if (key == "overlay") { long overlay = strtol(value.c_str(), NULL, 10); if (overlay >= 0 && overlay <= 8) item->SetOverlayImage((CGUIListItem::GUIIconOverlay)overlay); } // TODO: This is a dynamic type for the value where a list is expected as the // Dictionary value. // else if (key == "cast" || key == "castandrole") // { // if (!PyObject_TypeCheck(value, &PyList_Type)) continue; // item->GetVideoInfoTag()->m_cast.clear(); // for (int i = 0; i < PyList_Size(value); i++) // { // PyObject *pTuple = NULL; // pTuple = PyList_GetItem(value, i); // if (pTuple == NULL) continue; // PyObject *pActor = NULL; // PyObject *pRole = NULL; // if (PyObject_TypeCheck(pTuple, &PyTuple_Type)) // { // if (!PyArg_ParseTuple(pTuple, (char*)"O|O", &pActor, &pRole)) continue; // } // else // pActor = pTuple; // SActorInfo info; // if (!PyXBMCGetUnicodeString(info.strName, pActor, 1)) continue; // if (pRole != NULL) // PyXBMCGetUnicodeString(info.strRole, pRole, 1); // item->GetVideoInfoTag()->m_cast.push_back(info); // } // } // else if (strcmpi(PyString_AsString(key), "artist") == 0) // { // if (!PyObject_TypeCheck(value, &PyList_Type)) continue; // self->item->GetVideoInfoTag()->m_artist.clear(); // for (int i = 0; i < PyList_Size(value); i++) // { // PyObject *pActor = PyList_GetItem(value, i); // if (pActor == NULL) continue; // String actor; // if (!PyXBMCGetUnicodeString(actor, pActor, 1)) continue; // self->item->GetVideoInfoTag()->m_artist.push_back(actor); // } // } else if (key == "genre") item->GetVideoInfoTag()->m_genre = StringUtils::Split(value, g_advancedSettings.m_videoItemSeparator); else if (key == "director") item->GetVideoInfoTag()->m_director = StringUtils::Split(value, g_advancedSettings.m_videoItemSeparator); else if (key == "mpaa") item->GetVideoInfoTag()->m_strMPAARating = value; else if (key == "plot") item->GetVideoInfoTag()->m_strPlot = value; else if (key == "plotoutline") item->GetVideoInfoTag()->m_strPlotOutline = value; else if (key == "title") item->GetVideoInfoTag()->m_strTitle = value; else if (key == "originaltitle") item->GetVideoInfoTag()->m_strOriginalTitle = value; else if (key == "sorttitle") item->GetVideoInfoTag()->m_strSortTitle = value; else if (key == "duration") item->GetVideoInfoTag()->m_duration = CVideoInfoTag::GetDurationFromMinuteString(value); else if (key == "studio") item->GetVideoInfoTag()->m_studio = StringUtils::Split(value, g_advancedSettings.m_videoItemSeparator); else if (key == "tagline") item->GetVideoInfoTag()->m_strTagLine = value; else if (key == "writer") item->GetVideoInfoTag()->m_writingCredits = StringUtils::Split(value, g_advancedSettings.m_videoItemSeparator); else if (key == "tvshowtitle") item->GetVideoInfoTag()->m_strShowTitle = value; else if (key == "premiered") item->GetVideoInfoTag()->m_premiered.SetFromDateString(value); else if (key == "status") item->GetVideoInfoTag()->m_strStatus = value; else if (key == "code") item->GetVideoInfoTag()->m_strProductionCode = value; else if (key == "aired") item->GetVideoInfoTag()->m_firstAired.SetFromDateString(value); else if (key == "credits") item->GetVideoInfoTag()->m_writingCredits = StringUtils::Split(value, g_advancedSettings.m_videoItemSeparator); else if (key == "lastplayed") item->GetVideoInfoTag()->m_lastPlayed.SetFromDBDateTime(value); else if (key == "album") item->GetVideoInfoTag()->m_strAlbum = value; else if (key == "votes") item->GetVideoInfoTag()->m_strVotes = value; else if (key == "trailer") item->GetVideoInfoTag()->m_strTrailer = value; else if (key == "date") { if (value.length() == 10) item->m_dateTime.SetDate(atoi(value.Right(4).c_str()), atoi(value.Mid(3,4).c_str()), atoi(value.Left(2).c_str())); else CLog::Log(LOGERROR,"NEWADDON Invalid Date Format \"%s\"",value.c_str()); } else if (key == "dateadded") item->GetVideoInfoTag()->m_dateAdded.SetFromDBDateTime(value.c_str()); } } else if (strcmpi(type, "music") == 0) { for (Dictionary::const_iterator it = infoLabels.begin(); it != infoLabels.end(); it++) { CStdString key = it->first; key.ToLower(); const CStdString value(it->second.c_str()); // TODO: add the rest of the infolabels if (key == "tracknumber") item->GetMusicInfoTag()->SetTrackNumber(strtol(value, NULL, 10)); else if (key == "count") item->m_iprogramCount = strtol(value, NULL, 10); else if (key == "size") item->m_dwSize = (int64_t)strtoll(value, NULL, 10); else if (key == "duration") item->GetMusicInfoTag()->SetDuration(strtol(value, NULL, 10)); else if (key == "year") item->GetMusicInfoTag()->SetYear(strtol(value, NULL, 10)); else if (key == "listeners") item->GetMusicInfoTag()->SetListeners(strtol(value, NULL, 10)); else if (key == "playcount") item->GetMusicInfoTag()->SetPlayCount(strtol(value, NULL, 10)); else if (key == "genre") item->GetMusicInfoTag()->SetGenre(value); else if (key == "album") item->GetMusicInfoTag()->SetAlbum(value); else if (key == "artist") item->GetMusicInfoTag()->SetArtist(value); else if (key == "title") item->GetMusicInfoTag()->SetTitle(value); else if (key == "rating") item->GetMusicInfoTag()->SetRating(*value); else if (key == "lyrics") item->GetMusicInfoTag()->SetLyrics(value); else if (key == "lastplayed") item->GetMusicInfoTag()->SetLastPlayed(value); else if (key == "musicbrainztrackid") item->GetMusicInfoTag()->SetMusicBrainzTrackID(value); else if (key == "musicbrainzartistid") item->GetMusicInfoTag()->SetMusicBrainzArtistID(value); else if (key == "musicbrainzalbumid") item->GetMusicInfoTag()->SetMusicBrainzAlbumID(value); else if (key == "musicbrainzalbumartistid") item->GetMusicInfoTag()->SetMusicBrainzAlbumArtistID(value); else if (key == "musicbrainztrmid") item->GetMusicInfoTag()->SetMusicBrainzTRMID(value); else if (key == "comment") item->GetMusicInfoTag()->SetComment(value); else if (key == "date") { if (strlen(value) == 10) item->m_dateTime.SetDate(atoi(value.Right(4)), atoi(value.Mid(3,4)), atoi(value.Left(2))); } else CLog::Log(LOGERROR,"NEWADDON Unknown Music Info Key \"%s\"", key.c_str()); // This should probably be set outside of the loop but since the original // implementation set it inside of the loop, I'll leave it that way. - Jim C. item->GetMusicInfoTag()->SetLoaded(true); } } else if (strcmpi(type,"pictures") == 0) { bool pictureTagLoaded = false; for (Dictionary::const_iterator it = infoLabels.begin(); it != infoLabels.end(); it++) { CStdString key = it->first; key.ToLower(); const CStdString value(it->second.c_str()); if (key == "count") item->m_iprogramCount = strtol(value, NULL, 10); else if (key == "size") item->m_dwSize = (int64_t)strtoll(value, NULL, 10); else if (key == "title") item->m_strTitle = value; else if (key == "picturepath") item->SetPath(value); else if (key == "date") { if (strlen(value) == 10) item->m_dateTime.SetDate(atoi(value.Right(4)), atoi(value.Mid(3,4)), atoi(value.Left(2))); } else { const CStdString& exifkey = key; if (!exifkey.Left(5).Equals("exif:") || exifkey.length() < 6) continue; int info = CPictureInfoTag::TranslateString(exifkey.Mid(5)); item->GetPictureInfoTag()->SetInfo(info, value); pictureTagLoaded = true; } } if (pictureTagLoaded) item->GetPictureInfoTag()->SetLoaded(true); } } // end ListItem::setInfo void ListItem::addStreamInfo(const char* cType, const Dictionary& dictionary) { LOCKGUI; String tmp; if (strcmpi(cType, "video") == 0) { CStreamDetailVideo* video = new CStreamDetailVideo; for (Dictionary::const_iterator it = dictionary.begin(); it != dictionary.end(); it++) { const String& key = it->first; const CStdString value(it->second.c_str()); if (key == "codec") video->m_strCodec = value; else if (key == "aspect") video->m_fAspect = (float)atof(value); else if (key == "width") video->m_iWidth = strtol(value, NULL, 10); else if (key == "height") video->m_iHeight = strtol(value, NULL, 10); else if (key == "duration") video->m_iDuration = strtol(value, NULL, 10); } item->GetVideoInfoTag()->m_streamDetails.AddStream(video); } else if (strcmpi(cType, "audio") == 0) { CStreamDetailAudio* audio = new CStreamDetailAudio; for (Dictionary::const_iterator it = dictionary.begin(); it != dictionary.end(); it++) { const String& key = it->first; const String& value = it->second; if (key == "codec") audio->m_strCodec = value; else if (key == "language") audio->m_strLanguage = value; else if (key == "channels") audio->m_iChannels = strtol(value.c_str(), NULL, 10); } item->GetVideoInfoTag()->m_streamDetails.AddStream(audio); } else if (strcmpi(cType, "subtitle") == 0) { CStreamDetailSubtitle* subtitle = new CStreamDetailSubtitle; for (Dictionary::const_iterator it = dictionary.begin(); it != dictionary.end(); it++) { const String& key = it->first; const String& value = it->second; if (key == "language") subtitle->m_strLanguage = value; } item->GetVideoInfoTag()->m_streamDetails.AddStream(subtitle); } } // end ListItem::addStreamInfo void ListItem::addContextMenuItems(const std::vector<Tuple<String,String> >& items, bool replaceItems /* = false */) throw (ListItemException) { int itemCount = 0; for (std::vector<Tuple<String,String> >::const_iterator iter = items.begin(); iter < items.end(); iter++, itemCount++) { Tuple<String,String> tuple = *iter; if (tuple.GetNumValuesSet() != 2) throw ListItemException("Must pass in a list of tuples of pairs of strings. One entry in the list only has %d elements.",tuple.GetNumValuesSet()); std::string uText = tuple.first(); std::string uAction = tuple.second(); LOCKGUI; CStdString property; property.Format("contextmenulabel(%i)", itemCount); item->SetProperty(property, uText); property.Format("contextmenuaction(%i)", itemCount); item->SetProperty(property, uAction); } // set our replaceItems status if (replaceItems) item->SetProperty("pluginreplacecontextitems", replaceItems); } // end addContextMenuItems } }
gpl-2.0
karianna/jdk8_tl
jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/message/PayloadElementSniffer.java
2814
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.ws.message; import com.sun.xml.internal.ws.encoding.soap.SOAP12Constants; import com.sun.xml.internal.ws.encoding.soap.SOAPConstants; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.namespace.QName; /** * Parses the SOAP message in order to get {@link QName} of a payload element. * It parses message until it * * @author Miroslav Kos (miroslav.kos at oracle.com) */ public class PayloadElementSniffer extends DefaultHandler { // flag if the last element was SOAP body private boolean bodyStarted; // payloadQName used as a return value private QName payloadQName; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (bodyStarted) { payloadQName = new QName(uri, localName); // we have what we wanted - let's skip rest of parsing ... throw new SAXException("Payload element found, interrupting the parsing process."); } // check for both SOAP 1.1/1.2 if (equalsQName(uri, localName, SOAPConstants.QNAME_SOAP_BODY) || equalsQName(uri, localName, SOAP12Constants.QNAME_SOAP_BODY)) { bodyStarted = true; } } private boolean equalsQName(String uri, String localName, QName qname) { return qname.getLocalPart().equals(localName) && qname.getNamespaceURI().equals(uri); } public QName getPayloadQName() { return payloadQName; } }
gpl-2.0
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Microsoft/CDTrackEnabled.php
736
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Microsoft; use PHPExiftool\Driver\AbstractTag; class CDTrackEnabled extends AbstractTag { protected $Id = 'CDTrackEnabled'; protected $Name = 'CDTrackEnabled'; protected $FullName = 'Microsoft::Xtra'; protected $GroupName = 'Microsoft'; protected $g0 = 'QuickTime'; protected $g1 = 'Microsoft'; protected $g2 = 'Video'; protected $Type = '?'; protected $Writable = false; protected $Description = 'CD Track Enabled'; }
gpl-2.0
mzmine/mzmine3
src/main/java/io/github/mzmine/modules/visualization/spectra/simplespectra/datasets/UnifyScansDataSet.java
4084
/* * Copyright 2006-2021 The MZmine Development Team * * This file is part of MZmine. * * MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.modules.visualization.spectra.simplespectra.datasets; import com.google.common.collect.Range; import io.github.mzmine.datamodel.Scan; import io.github.mzmine.modules.visualization.spectra.simplespectra.SpectraPlot; import io.github.mzmine.util.scans.ScanUtils; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.jfree.data.xy.AbstractXYDataset; import org.jfree.data.xy.IntervalXYDataset; /** * Used in {@link SpectraPlot} to unify multiple MS2 (MS3, ...) scans into one spectrum. */ public class UnifyScansDataSet extends AbstractXYDataset implements IntervalXYDataset { private static final long serialVersionUID = 1L; // For comparing small differences. private static final double EPSILON = 0.0000001; private final String label; private final List<Scan> scans; private final Map<Integer, String> annotation = new Hashtable<>(); private final Map<Double, String> mzAnnotationMap = new Hashtable<>(); private final boolean allSameMsLevel; /* * Save a local copy of m/z and intensity values, because accessing the scan every time may cause * reloading the data from HDD */ // private DataPoint dataPoints[]; public UnifyScansDataSet(List<Scan> scans) { this.scans = scans; allSameMsLevel = scans.stream().allMatch(s -> s.getMSLevel() == scans.get(0).getMSLevel()); if (allSameMsLevel) { this.label = String.format("%d Scans (MS%d)", scans.size(), scans.get(0).getMSLevel()); } else { this.label = String.format("%d Scans", scans.size()); } } @Override public int getSeriesCount() { return scans.size(); } @Override public Comparable<?> getSeriesKey(int series) { return label; } @Override public int getItemCount(int series) { return scans.get(series).getNumberOfDataPoints(); } @Override public Number getX(int series, int item) { return scans.get(series).getMzValue(item); } @Override public Number getY(int series, int item) { return scans.get(series).getIntensityValue(item); } @Override public Number getEndX(int series, int item) { return getX(series, item); } @Override public double getEndXValue(int series, int item) { return getXValue(series, item); } @Override public Number getEndY(int series, int item) { return getY(series, item); } @Override public double getEndYValue(int series, int item) { return getYValue(series, item); } @Override public Number getStartX(int series, int item) { return getX(series, item); } @Override public double getStartXValue(int series, int item) { return getXValue(series, item); } @Override public Number getStartY(int series, int item) { return getY(series, item); } @Override public double getStartYValue(int series, int item) { return getYValue(series, item); } /** * This function finds highest data point intensity in given m/z range. It is important for * normalizing isotope patterns. */ public double getHighestIntensity(int series, Range<Double> mzRange) { return series >= 0 && series < scans.size() ? ScanUtils.findBasePeak(scans.get(series), mzRange) .getIntensity() : 0d; } public List<Scan> getScans() { return scans; } }
gpl-2.0
comcow2007/incident-watcher-tool
ACTFBIncidentSource/ACTFBWatchNotification.cs
17175
//ACTFBIncidentSource - This incident source reads the ACTFB public feed for Incident Watcher //Copyright (C) 2011 comicalcow //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either version 2 //of the License, or (at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using InciWatch; namespace ACTFBIncidentSource { internal partial class ACTFBWatchNotification : Form, IWatchNotification { private ACTFBIncidentItem mIncidentItem; private IWatchList mParent; private ACTFBIncidentSourceOptions mOptions; private ACTFBIncidentSource mParentSource; private bool mfFadeOut; public ACTFBWatchNotification(ACTFBIncidentItem IncidentItem, IWatchList Parent, ACTFBIncidentSourceOptions Options, ACTFBIncidentSource ParentSource) { InitializeComponent(); mIncidentItem = IncidentItem; mParent = Parent; mOptions = Options; mParentSource = ParentSource; mfFadeOut = true; UpdateDialog(); //Check if a stream exists for this region if (String.IsNullOrEmpty(mOptions.StreamURL) == false && String.IsNullOrEmpty(mParentSource.GetIncidentWatcher().GetStreamListenerPath()) == false) { //If we have it set to open the stream if (mParentSource.GetIncidentWatcher().GetAutoOpenStreamOnWatch() == true) { OpenStream(); } } } private bool UpdateDialog() { bool returnCode = false; //Check if a stream exists for this region if (String.IsNullOrEmpty(mOptions.StreamURL) == true || String.IsNullOrEmpty(mParentSource.GetIncidentWatcher().GetStreamListenerPath()) == true) { btn2.Visible = false; } else { btn2.Visible = true; } //Set the values. //Address lblAddress.Text = mIncidentItem.Location; ttDisplay.SetToolTip(lblAddress, "Address: "+mIncidentItem.Location); //Suburb lblSuburb.Text = mIncidentItem.Suburb; ttDisplay.SetToolTip(lblSuburb, "Suburb: "+mIncidentItem.Suburb); lblUpdateTime.Text = mIncidentItem.LastUpdate.ToString("HH:mm"); //Appliance Count lblApplianceCount.Text = mIncidentItem.ApplianceCount_GENERIC.ToString(); //Has the incident stopped? returnCode = CheckForJustSafeCheck(); UpdateIncidentStatus(); UpdateIncidentType(); //Hide or UN-Hide the circle square and diamond depending on the values in them if (String.IsNullOrEmpty(mOptions.ActionDiamond) == true) { //Hide the diamond button btn6.Visible = false; } if (String.IsNullOrEmpty(mOptions.ActionSquare) == true) { //Hide the diamond button btn5.Visible = false; } if (String.IsNullOrEmpty(mOptions.ActionCircle) == true) { //Hide the diamond button btn4.Visible = false; } return returnCode; } private bool CheckForJustSafeCheck() { if (lblStatus.Text != "STATUS" && lblStatus.Text != "SAFE" ) { //Wasn't Safe before update, Is the incident now safe? if (mIncidentItem.Status == ACTFBIncidentItem.ACTFBStatus.Stop) { //Just became Safe //Do we want to auto close? if (mParentSource.GetIncidentWatcher().GetAutoCloseWatchOnSafe() == true) { //Is there a time delay if (mParentSource.GetIncidentWatcher().GetAutoCloseWatchOnSafeDelay() > 0) { //Start the timer tmrNotification.Interval = mParentSource.GetIncidentWatcher().GetAutoCloseWatchOnSafeDelay() * 1000; tmrNotification.Start(); } else { //Otherwise Remove this incident item from watch if (mParent.IsKeyBeingWatched(mIncidentItem.ID_GENERIC) == true) { //Return true which says that we should close this watch immediately return true; } } } } } return false; } private void UpdateIncidentType() { //Set the tooptip ttDisplay.SetToolTip(lblType, "Type: " +ACTFBIncidentItem.IncidentTypeToString(mIncidentItem.Type)); switch (mIncidentItem.Type) { case ACTFBIncidentItem.ACTFBTypes.CarFire: lblType.Text = "CARF"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.MVA: lblType.Text = "MVA"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.RubbishFire: lblType.Text = "RUBF"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.StructureFire13: lblType.Text = "LSTR"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.StructureFire47: lblType.Text = "MSTR"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.StructureFire8plus: lblType.Text = "HSTR"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.GasPiplineNoInj: lblType.Text = "GSLK"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.PowerlinesDown: lblType.Text = "PLDN"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.GrassAndBush: lblType.Text = "G&B"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.HouseFireInj: lblType.Text = "HFWI"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.HouseFireNoInj: lblType.Text = "HFNI"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.HazmatNoCBR: lblType.Text = "HZMT"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.StructureBelowGround: lblType.Text = "SFBG"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.TransportFireBusTruck: lblType.Text = "TFBT"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.StructuralCollapseMinor: lblType.Text = "SCMI"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.StructuralCollapseMajor: lblType.Text = "SCMA"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.LPGCylinderNoInj: lblType.Text = "LFNI"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.LPGCylinderInj: lblType.Text = "LFWI"; lblType.ForeColor = Color.White; break; case ACTFBIncidentItem.ACTFBTypes.HospitalsAndInstitutionsFire: lblType.Text = "H/IF"; lblType.ForeColor = Color.White; break; default: lblType.Text = "UNKN"; lblType.ForeColor = Color.White; break; } } private void UpdateIncidentStatus() { //Set the tooptip ttDisplay.SetToolTip(lblStatus, "Status: "+ACTFBIncidentItem.IncidentStatusToString(mIncidentItem.Status)); switch (mIncidentItem.Status) { case ACTFBIncidentItem.ACTFBStatus.Stop: lblStatus.Text = "SAFE"; lblStatus.ForeColor = Color.LimeGreen; break; case ACTFBIncidentItem.ACTFBStatus.OnRoute: lblStatus.Text = "ONWAY"; lblStatus.ForeColor = Color.Red; break; case ACTFBIncidentItem.ACTFBStatus.OnScene: lblStatus.Text = "GOING"; lblStatus.ForeColor = Color.Red; break; case ACTFBIncidentItem.ACTFBStatus.ResourcesPending: lblStatus.Text = "INIT"; lblStatus.ForeColor = Color.Orange; break; case ACTFBIncidentItem.ACTFBStatus.Finished: lblStatus.Text = "FNSH"; lblStatus.ForeColor = Color.LimeGreen; break; case ACTFBIncidentItem.ACTFBStatus.UnderControl: lblStatus.Text = "UCTL"; lblStatus.ForeColor = Color.Orange; break; default: lblStatus.Text = "UNKN"; lblStatus.ForeColor = Color.White; break; } } private void btn1_Click(object sender, EventArgs e) { //Close this watch notification mParent.Remove(mIncidentItem.ID_GENERIC); } private void btn2_Click(object sender, EventArgs e) { OpenStream(); } private void OpenStream() { //Listen to Stream try { //Replace Values in args string String argsString = mOptions.StreamURL; argsString = mOptions.ReplaceInciWatchVarsInString(argsString, mIncidentItem); System.Diagnostics.Process.Start(mParentSource.GetIncidentWatcher().GetStreamListenerPath(), argsString); } catch { MessageBox.Show("Unable to start stream application."); } } private void btn3_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(mIncidentItem.GetMapURL()); } private void btn4_Click(object sender, EventArgs e) { //Circle button try { if (String.IsNullOrEmpty(mOptions.ActionCircle) == false) { //Replace constants in the string String execString = mOptions.ActionCircleArgs; execString = mOptions.ReplaceInciWatchVarsInString(execString, mIncidentItem); //Execute the command System.Diagnostics.Process.Start(mOptions.ActionCircle, execString); } } catch { MessageBox.Show("Unable to run command assigned to the circle action button."); } } private void btn5_Click(object sender, EventArgs e) { //Square button try { if (String.IsNullOrEmpty(mOptions.ActionSquare) == false) { //Replace constants in the string String execString = mOptions.ActionSquareArgs; execString = mOptions.ReplaceInciWatchVarsInString(execString, mIncidentItem); //Execute the command System.Diagnostics.Process.Start(mOptions.ActionSquare, execString); } } catch { MessageBox.Show("Unable to run command assigned to the square action button."); } } private void btn6_Click(object sender, EventArgs e) { //Diamond button try { if (String.IsNullOrEmpty(mOptions.ActionDiamond) == false) { //Replace constants in the string String execString = mOptions.ActionDiamondArgs; execString = mOptions.ReplaceInciWatchVarsInString(execString, mIncidentItem); //Execute the command System.Diagnostics.Process.Start(mOptions.ActionDiamond, execString); } } catch { MessageBox.Show("Unable to run command assigned to the diamond action button."); } } #region Interface Functions public Point GetPosition() { return this.Location; } public void SetPosition(Point newPosition) { this.Location = newPosition; } public int GetWidth() { return this.Width; } public int GetHeight() { return this.Height; } public void SetDimensions(int newWidth, int newHeight) { this.Width = newWidth; this.Height = newHeight; } public void ShowNotification() { this.Show(); } public void CloseNotification() { this.Close(); } public bool RefreshNotification() { bool returnCode = UpdateDialog(); //Redraw this.Refresh(); return returnCode; } #endregion private void tmrNotification_Tick(object sender, EventArgs e) { //Stop the timer tmrNotification.Stop(); //Remove the watch from the parent list if (mParent.IsKeyBeingWatched(mIncidentItem.ID_GENERIC) == true) { mParent.Remove(mIncidentItem.ID_GENERIC); } } private void ACTFBWatchNotification_MouseEnter(object sender, EventArgs e) { tmrFadeout.Stop(); //Set opacity to 100% this.Opacity = 1; } private void ACTFBWatchNotification_MouseLeave(object sender, EventArgs e) { if (mfFadeOut == true) { tmrFadeout.Start(); } } private void tmrFadeout_Tick(object sender, EventArgs e) { if (this.Opacity > .25) { this.Opacity -= .025; } else { tmrFadeout.Stop(); } } private void pbShowZone_Click(object sender, EventArgs e) { if (mfFadeOut == true) mfFadeOut = false; else mfFadeOut = true; } } }
gpl-2.0
avalonfr/avalon_core_v1
src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp
11457
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Prince_Keleseth SD%Complete: 90 SDComment: Needs Prince Movements, Needs adjustments to blizzlike timers, Needs Shadowbolt castbar, Needs right Ressurect Visual, Needs Some Heroic Spells SDCategory: Utgarde Keep EndScriptData */ #include "ScriptPCH.h" #include "utgarde_keep.h" enum eEnums { ACHIEVEMENT_ON_THE_ROCKS = 1919, SPELL_SHADOWBOLT = 43667, SPELL_SHADOWBOLT_HEROIC = 59389, SPELL_FROST_TOMB = 48400, SPELL_FROST_TOMB_SUMMON = 42714, SPELL_DECREPIFY = 42702, SPELL_SCOURGE_RESSURRECTION = 42704, CREATURE_FROSTTOMB = 23965, CREATURE_SKELETON = 23970, SAY_AGGRO = -1574000, SAY_FROST_TOMB = -1574001, SAY_SKELETONS = -1574002, SAY_KILL = -1574003, SAY_DEATH = -1574004 }; #define SKELETONSPAWN_Z 42.8668f float SkeletonSpawnPoint[5][5]= { {156.2559f, 259.2093f}, {156.2559f, 259.2093f}, {156.2559f, 259.2093f}, {156.2559f, 259.2093f}, {156.2559f, 259.2093f}, }; float AttackLoc[3]={197.636f, 194.046f, 40.8164f}; bool ShatterFrostTomb; // needed for achievement: On The Rocks(1919) class mob_frost_tomb : public CreatureScript { public: mob_frost_tomb() : CreatureScript("mob_frost_tomb") { } CreatureAI* GetAI(Creature* creature) const { return new mob_frost_tombAI(creature); } struct mob_frost_tombAI : public ScriptedAI { mob_frost_tombAI(Creature* c) : ScriptedAI(c) { FrostTombGUID = 0; } uint64 FrostTombGUID; void SetPrisoner(Unit* uPrisoner) { FrostTombGUID = uPrisoner->GetGUID(); } void Reset(){ FrostTombGUID = 0; } void EnterCombat(Unit* /*who*/) {} void AttackStart(Unit* /*who*/) {} void MoveInLineOfSight(Unit* /*who*/) {} void JustDied(Unit* killer) { if (killer->GetGUID() != me->GetGUID()) ShatterFrostTomb = true; if (FrostTombGUID) { Unit* FrostTomb = Unit::GetUnit((*me), FrostTombGUID); if (FrostTomb) FrostTomb->RemoveAurasDueToSpell(SPELL_FROST_TOMB); } } void UpdateAI(const uint32 /*diff*/) { Unit* temp = Unit::GetUnit((*me), FrostTombGUID); if ((temp && temp->isAlive() && !temp->HasAura(SPELL_FROST_TOMB)) || !temp) me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } }; }; class boss_keleseth : public CreatureScript { public: boss_keleseth() : CreatureScript("boss_keleseth") { } CreatureAI* GetAI(Creature* creature) const { return new boss_kelesethAI (creature); } struct boss_kelesethAI : public ScriptedAI { boss_kelesethAI(Creature* c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); } InstanceScript* pInstance; uint32 FrostTombTimer; uint32 SummonSkeletonsTimer; uint32 RespawnSkeletonsTimer; uint32 ShadowboltTimer; uint64 SkeletonGUID[5]; bool Skeletons; bool RespawnSkeletons; void Reset() { ShadowboltTimer = 0; Skeletons = false; ShatterFrostTomb = false; ResetTimer(); if (pInstance) pInstance->SetData(DATA_PRINCEKELESETH_EVENT, NOT_STARTED); } void KilledUnit(Unit* victim) { if (victim == me) return; DoScriptText(SAY_KILL, me); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (IsHeroic() && !ShatterFrostTomb) { if (pInstance) pInstance->DoCompleteAchievement(ACHIEVEMENT_ON_THE_ROCKS); } if (pInstance) pInstance->SetData(DATA_PRINCEKELESETH_EVENT, DONE); } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); DoZoneInCombat(); if (pInstance) pInstance->SetData(DATA_PRINCEKELESETH_EVENT, IN_PROGRESS); } void ResetTimer(uint32 inc = 0) { SummonSkeletonsTimer = 5000 + inc; FrostTombTimer = 28000 + inc; } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (ShadowboltTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0); if (target && target->isAlive() && target->GetTypeId() == TYPEID_PLAYER) me->CastSpell(target, DUNGEON_MODE(SPELL_SHADOWBOLT, SPELL_SHADOWBOLT_HEROIC), true); ShadowboltTimer = 10000; } else ShadowboltTimer -= diff; if (!Skeletons) { if ((SummonSkeletonsTimer <= diff)) { Creature* Skeleton; DoScriptText(SAY_SKELETONS, me); for (uint8 i = 0; i < 5; ++i) { Skeleton = me->SummonCreature(CREATURE_SKELETON, SkeletonSpawnPoint[i][0], SkeletonSpawnPoint[i][1] , SKELETONSPAWN_Z, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 20000); if (Skeleton) { Skeleton->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); Skeleton->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY() , me->GetPositionZ()); Skeleton->AddThreat(me->getVictim(), 0.0f); DoZoneInCombat(Skeleton); } } Skeletons = true; } else SummonSkeletonsTimer -= diff; } if (FrostTombTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) if (target->isAlive()) { //DoCast(target, SPELL_FROST_TOMB_SUMMON, true); if (Creature* pChains = me->SummonCreature(CREATURE_FROSTTOMB, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 20000)) { CAST_AI(mob_frost_tomb::mob_frost_tombAI, pChains->AI())->SetPrisoner(target); pChains->CastSpell(target, SPELL_FROST_TOMB, true); DoScriptText(SAY_FROST_TOMB, me); } } FrostTombTimer = 15000; } else FrostTombTimer -= diff; DoMeleeAttackIfReady(); } }; }; class mob_vrykul_skeleton : public CreatureScript { public: mob_vrykul_skeleton() : CreatureScript("mob_vrykul_skeleton") { } CreatureAI* GetAI(Creature* creature) const { return new mob_vrykul_skeletonAI (creature); } struct mob_vrykul_skeletonAI : public ScriptedAI { mob_vrykul_skeletonAI(Creature* c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); } InstanceScript *pInstance; uint32 Respawn_Time; uint64 Target_Guid; uint32 Decrepify_Timer; bool isDead; void Reset() { Respawn_Time = 12000; Decrepify_Timer = urand(10000, 20000); isDead = false; } void EnterCombat(Unit* /*who*/){} void DamageTaken(Unit* done_by, uint32 &damage) { if (done_by->GetGUID() == me->GetGUID()) return; if (damage >= me->GetHealth()) { PretendToDie(); damage = 0; } } void PretendToDie() { isDead = true; me->InterruptNonMeleeSpells(true); me->RemoveAllAuras(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->GetMotionMaster()->MovementExpired(false); me->GetMotionMaster()->MoveIdle(); me->SetStandState(UNIT_STAND_STATE_DEAD); }; void Resurrect() { isDead = false; me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->SetStandState(UNIT_STAND_STATE_STAND); DoCast(me, SPELL_SCOURGE_RESSURRECTION, true); if (me->getVictim()) { me->GetMotionMaster()->MoveChase(me->getVictim()); me->AI()->AttackStart(me->getVictim()); } else me->GetMotionMaster()->Initialize(); }; void UpdateAI(const uint32 diff) { if (pInstance && pInstance->GetData(DATA_PRINCEKELESETH_EVENT) == IN_PROGRESS) { if (isDead) { if (Respawn_Time <= diff) { Resurrect(); Respawn_Time = 12000; } else Respawn_Time -= diff; } else { if (!UpdateVictim()) return; if (Decrepify_Timer <= diff) { DoCast(me->getVictim(), SPELL_DECREPIFY); Decrepify_Timer = 30000; } else Decrepify_Timer -= diff; DoMeleeAttackIfReady(); } }else { if (me->isAlive()) me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } } }; }; void AddSC_boss_keleseth() { new boss_keleseth(); new mob_frost_tomb(); new mob_vrykul_skeleton(); }
gpl-2.0
k9ert/struktor
src/struktor/strukelements/DecList.java
7976
// Copyright 2000 Kim Neunert (k9ert@gmx.de), this is free Software (GNU Public License) package struktor.strukelements; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Enumeration; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import struktor.Presets; import struktor.Save; import struktor.StruktorException; import struktor.Tracer; import struktor.processor.ProcessorException; /** Eine Klasse für den "Deklarationen-Editor" */ public class DecList extends JPanel implements ActionListener, ItemListener, struktor.processor.datatypes.Datatype { /** * */ private static final long serialVersionUID = 1L; // Static Variables private static Vector DecListList = new Vector(); private static DecList addDecList(DecList s) { DecListList.addElement(s); return s; } /** Eine Deklarationsliste zu einem Struktogramm finden */ static public DecList findDecList(Struktogramm sg) { for (Enumeration el=DecListList.elements(); el.hasMoreElements(); ) { DecList r=(DecList)el.nextElement(); if (r.struktogramm == sg) return r; } Tracer.out("OhOh ... no Declist found !"); return null; } static public Dec findArrayDecWithName(String name) { Tracer.out("searching for "+name); for (Enumeration el=DecListList.elements(); el.hasMoreElements(); ) { DecList r=(DecList)el.nextElement(); for (Enumeration el2=r.decList.elements(); el2.hasMoreElements(); ) { Dec dec = (Dec)el2.nextElement(); if (dec.array.isEnabled()) { if (dec.name.getText().equals(name)) { return dec; } } } } return null; } static public int getDim(String name, int dim) throws ProcessorException { switch (dim) { case 1: return Integer.parseInt(findArrayDecWithName(name).indizes.getText()); case 2: return Integer.parseInt(findArrayDecWithName(name).indizes2.getText()) * Integer.parseInt(findArrayDecWithName(name).indizes.getText()); case 3: return Integer.parseInt(findArrayDecWithName(name).indizes3.getText()) * Integer.parseInt(findArrayDecWithName(name).indizes2.getText()) * Integer.parseInt(findArrayDecWithName(name).indizes.getText()); } throw new ProcessorException("invalid Dimension for array identifier "+ name + " and dimension " + dim); } static public int getDim2(String name) { return Integer.parseInt(findArrayDecWithName(name).indizes2.getText()); } static public void deleteDecList(Struktogramm sg) { DecListList.remove(findDecList(sg)); } // Object Variables JButton newDeclaration = new JButton("newDeclaration"); public Struktogramm struktogramm; public Presets presets; Vector decList; JPanel tempPanel; /** Nur für Expr.Calc */ public Vector getDecList() { return decList; } public DecList(Struktogramm s, JPanel tempPanel) { struktogramm = s; presets = s.presets; addDecList(this); Box box = new Box(BoxLayout.X_AXIS); if (presets.enabNewDec) box.add(newDeclaration); add(box); newDeclaration.addActionListener(this); newDeclaration.setVisible(true); decList = new Vector(); this.tempPanel = tempPanel; } /** für ExprCalc */ public DecList(Presets presets) { this.presets = presets; decList = new Vector(); tempPanel = new JPanel(); } /** Die Parameter beim Aufruf von Struktogrammen werden initialisiert indem der Wert * des Arguments in das Textfeld geschrieben wird * @param Die Argumente als Vektor * @exception ProcessorException */ void initializeParameters(Vector parameter) throws ProcessorException { Tracer.out("try to initilize parameters ..."); int parameterCount = getParameterCount(); int i=0; for (Enumeration el=parameter.elements(); el.hasMoreElements(); ) { Object p=(Object)el.nextElement(); Tracer.out("Argument "+i+":"+p.toString()); if (p != null) getParameter(i).setValue(p.toString()); i++; } Tracer.out("ok, Variables initialized !"); if (i != parameterCount) throw new ProcessorException("To less Parameters !"); } /** Hilfsmethode um den xten Parameter zu finden */ private Dec getParameter(int index) throws ProcessorException { int counter=0; Component decs[] = tempPanel.getComponents(); int max = tempPanel.getComponentCount(); for (int i = 0; i < max; i++) { Dec element = (Dec)decs[i]; if (element.isParameter()) { if (index == counter) return element; else counter++; } } throw new ProcessorException("To many Parameters !"); } /** Hilfsmethode: Gibt die Anzahl der Parameter zurück */ private int getParameterCount() { int counter=0; Component decs[] = tempPanel.getComponents(); int max = tempPanel.getComponentCount(); for (int i = 0; i < max; i++) { Dec element = (Dec)decs[i]; if (element.isParameter()) counter++; } Tracer.out("We have " + counter+" parameters here !"); return counter; } /** Hilfsmethode: Gibt die Anzahl der Deklarationen zurück */ private int getDeclarationCount() { return tempPanel.getComponentCount(); } public JPanel getTempPanel() { return tempPanel; } /** Eine neue Deklaration erzeugen (für ExprCalc public) */ public Dec newDeclaration(boolean isPointer, boolean isParameter, boolean isArray, int index, int temptype, String tempname, String value) { Dec dec = new Dec(presets, isPointer, isParameter, isArray, index, temptype, tempname, value); dec.setDecList(this); decList.addElement(dec); Tracer.out("New Dec set ("+isPointer+isParameter+isArray+index+temptype+tempname+value); tempPanel.add(dec); dec.setVisible(true); tempPanel.validate(); return dec; } String getCFormatCode(String varName) throws ProcessorException { Component decs[] = tempPanel.getComponents(); int max = tempPanel.getComponentCount(); for (int i = 0; i < max; i++) { Dec element = (Dec)decs[i]; if (element.getName().equals(varName)) return element.getCFormatCode(); } throw new ProcessorException("Variable not Found: "+varName); } // Event Handling void newDeclaration() { newDeclaration(false, false, false, 10, INTEGER, "name", ""); } /** Deklaration loeschen (delete-Button) */ void delete(Dec dec) { decList.remove(dec); tempPanel.remove(dec); Tracer.out("dec deleted !"); revalidate(); repaint(); } public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == newDeclaration) { newDeclaration(); repaint(); } } public void itemStateChanged(ItemEvent i) { } /** Deklarationen speichern (ohne Parameter) */ void saveDecs(Save saveObject) { if (!presets.makeCCode) { saveObject.println("//@*** Declarations ***"); if (decList.isEmpty() | (getParameterCount()-getDeclarationCount() == 0) ) saveObject.println("// No Declarations"); } for (Enumeration el=decList.elements(); el.hasMoreElements(); ) { Dec r=(Dec)el.nextElement(); if (!r.isParameter()) { // Verwendet als einzigster printTabs weil dec.save auch f�r Parameter verwendet wird (print statt println) saveObject.printTabs(); r.save(saveObject); saveObject.print(" ;\n"); } } if (!decList.isEmpty()) saveObject.println(""); } /** Parameter speichern */ void saveParam(Save saveObject) { int parameterCount = getParameterCount(); int i=0; for (Enumeration el=decList.elements(); el.hasMoreElements(); ) { Dec r=(Dec)el.nextElement(); if (r.isParameter()) { i++; r.save(saveObject); if (i<parameterCount) saveObject.print(", "); } } } }
gpl-2.0
imglib/imglib2-script
src/test/java/net/imglib2/script/TestHistograms.java
16279
/* * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2016 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, * Jean-Yves Tinevez and Michael Zinsmaier. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package net.imglib2.script; import static org.junit.Assert.assertTrue; import ij.ImageJ; import ij.ImagePlus; import ij.ImageStack; import ij.plugin.filter.RankFilters; import ij.process.ImageProcessor; import io.scif.img.ImgOpener; import net.imglib2.Cursor; import net.imglib2.Point; import net.imglib2.RandomAccess; import net.imglib2.exception.ImgLibException; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgFactory; import net.imglib2.img.array.ArrayImgs; import net.imglib2.img.imageplus.ImagePlusImg; import net.imglib2.img.imageplus.ImagePlusImgFactory; import net.imglib2.script.algorithm.integral.histogram.Histogram; import net.imglib2.script.algorithm.integral.histogram.IntegralHistogram; import net.imglib2.script.algorithm.integral.histogram.IntegralHistogramCursor; import net.imglib2.script.algorithm.integral.histogram.LinearHistogram; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.IntegerType; import net.imglib2.type.numeric.integer.IntType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.util.Util; import org.junit.Test; public class TestHistograms { static public final <T extends IntegerType<T> & NativeType<T>> void main(String[] arg) { new ImageJ(); TestHistograms t = new TestHistograms(); //t.testFeatures(); //t.testHistogramOf3x3Img(); //t.comparePerformance(); t.<T>testHistogramOf2x2x2Img(); } public void testCorners() { long[] window = new long[]{10, 10, 10}; int numDimensions = window.length; Point[] offsets = new Point[(int)Math.pow(2, numDimensions)]; for (int i=0; i<offsets.length; ++i) offsets[i] = new Point(numDimensions); int d = 0; while (d < numDimensions) { final int flip = (int)Math.pow(2, d); int sign = -1; for (int i=0; i<offsets.length;) { offsets[i].setPosition(sign * window[d] / 2, d); ++i; if (0 == i % flip) sign *= -1; } ++d; } for (int i=0; i<offsets.length; ++i) { System.out.println(offsets[i].toString()); } } public void testFeatures() { try { Img<UnsignedByteType> img = (Img<UnsignedByteType>) new ImgOpener().openImgs("/home/albert/Desktop/t2/bridge-crop-streched-smoothed.tif").get(0); ImgLib.wrap(img, "Original"); long[] radius = new long[]{10, 10}; // radius=1 is equivalent to ImageJ's radius=1 in RankFilters LinearHistogram<UnsignedByteType> lh = new LinearHistogram<UnsignedByteType>(256, img.numDimensions(), new UnsignedByteType(0), new UnsignedByteType(255)); Img<UnsignedShortType> integralHistogram = IntegralHistogram.create(img, lh, new UnsignedShortType()); HistogramFeatures<UnsignedByteType, UnsignedShortType> features = new HistogramFeatures<UnsignedByteType, UnsignedShortType>(img, integralHistogram, lh, radius); ImgLib.wrap(features, "Features for " + radius[0] + "x" + radius[1]); } catch (Exception e) { e.printStackTrace(); } } public void comparePerformance() { try { ij.Prefs.setThreads(1); Img<UnsignedByteType> img = (Img<UnsignedByteType>) new ImgOpener().openImgs("/home/albert/Desktop/t2/bridge.tif").get(0); ImgLib.wrap(img, "Original"); long t0 = System.currentTimeMillis(); final UnsignedByteType min = new UnsignedByteType(0); final UnsignedByteType max = new UnsignedByteType(255); final int nBins = 128; // 32 delivers speeds close to ImageJ's when not using median final LinearHistogram<UnsignedByteType> lh = new LinearHistogram<UnsignedByteType>(nBins, img.numDimensions(), min, max); final Img<IntType> integralHistogram = IntegralHistogram.create(img, lh, new IntType()); System.out.println("Creating integral histogram took " + (System.currentTimeMillis() - t0) + " ms"); long[] radius = new long[]{25, 25}; // radius=1 is equivalent to ImageJ's radius=1 in RankFilters HistogramFeatures<UnsignedByteType, IntType> features = new HistogramFeatures<UnsignedByteType, IntType>(img, integralHistogram, lh, radius); long t1 = System.currentTimeMillis(); ImagePlus imp = ImgLib.wrap(img); long t2 = System.currentTimeMillis(); RankFilters rf = new RankFilters(); ImageProcessor ip1 = imp.getProcessor().duplicate(); rf.rank(ip1, radius[0], RankFilters.MIN); ImageProcessor ip2 = imp.getProcessor().duplicate(); rf.rank(ip2, radius[0], RankFilters.MAX); ImageProcessor ip3 = imp.getProcessor().duplicate(); rf.rank(ip3, radius[0], RankFilters.MEAN); ImageProcessor ip4 = imp.getProcessor().duplicate(); rf.rank(ip4, radius[0], RankFilters.MEDIAN); long t3 = System.currentTimeMillis(); System.out.println("Integral features: " + (t1 - t0) + " ms"); System.out.println("Regular features: " + (t3 - t2) + " ms"); // Show them both ImgLib.wrap(features, "Integral Histogram Features for " + radius[0] + "x" + radius[1]); ImageStack stack = new ImageStack(imp.getWidth(), imp.getHeight()); stack.addSlice("min", ip1); stack.addSlice("max", ip2); stack.addSlice("mean", ip3); stack.addSlice("median", ip4); new ImagePlus("Regular features for " + radius[0] + "x" + radius[1], stack); } catch (Exception e) { e.printStackTrace(); } } /** * * 1 2 3 * 2 4 6 * 3 6 9 * * In the histogram, the bottom right should have: * {1:1, 2:2, 3:2, 4:1, 5:0, 6:2, 7:0, 8:0, 9:0} * */ @Test public <T extends IntegerType<T> & NativeType<T> >void testHistogramOf3x3Img() { Img< UnsignedByteType > img = ArrayImgs.unsignedBytes( 3, 3 ); Cursor<UnsignedByteType> c = img.cursor(); long[] position = new long[3]; int sum = 0; while (c.hasNext()) { c.fwd(); c.localize(position); int v = 1; for (int i=0; i<position.length; ++i) v *= position[i] + 1; c.get().set(v); sum += v; } assertTrue("Test image isn't right", sum == 36); // try { ImgLib.wrap(img, "image"); } catch (ImgLibException e) { e.printStackTrace(); } // Histogram UnsignedByteType min = new UnsignedByteType(1); UnsignedByteType max = new UnsignedByteType(9); LinearHistogram<UnsignedByteType> lh = new LinearHistogram<UnsignedByteType>(9, img.numDimensions(), min, max); Img<T> h = IntegralHistogram.create(img, lh); // Expected cummulative: final int[] expected = new int[]{1, 2, 2, 1, 0, 2, 0, 0, 1}; RandomAccess<T> ra = h.randomAccess(); StringBuilder sb = new StringBuilder("{"); ra.setPosition(3, 0); ra.setPosition(3, 1); for (int i=0; i<9; ++i) { ra.setPosition(i, 2); if (i > 0) sb.append(',').append(' '); sb.append(i+1).append(':').append(ra.get().getInteger()); assertTrue("Cummulative histogram isn't right", expected[i] == ra.get().getInteger()); } sb.append('}'); System.out.println("Cummulative Histogram: " + sb.toString()); try { ImgLib.wrap((Img)h, "histogram"); } catch (ImgLibException e) { e.printStackTrace(); } // Test extracting the histogram for the last pixel long[] px = new long[]{1, 2, 1, 2}; long[] py = new long[]{1, 1, 2, 2}; int[] sign = new int[]{1, -1, -1, 1}; long[] hist = new long[9]; for (int i=0; i<4; ++i) { ra.setPosition(px[i] + 1, 0); ra.setPosition(py[i] + 1, 1); for (int bin=0; bin<9; ++bin) { ra.setPosition(bin, 2); hist[bin] += sign[i] * ra.get().getIntegerLong(); } } for (int bin=0; bin<9; ++bin) { if (8 == bin) assertTrue(1 == hist[bin]); else assertTrue(0 == hist[bin]); } System.out.println(Util.printCoordinates(hist)); // Test extracting the histogram for the lower right 2x2 area px = new long[]{0, 2, 0, 2}; py = new long[]{0, 0, 2, 2}; sign = new int[]{1, -1, -1, 1}; hist = new long[9]; for (int i=0; i<4; ++i) { ra.setPosition(px[i] + 1, 0); ra.setPosition(py[i] + 1, 1); for (int bin=0; bin<9; ++bin) { ra.setPosition(bin, 2); hist[bin] += sign[i] * ra.get().getIntegerLong(); } } for (int bin=0; bin<9; ++bin) { switch (bin) { case 3: case 8: assertTrue(1 == hist[bin]); break; case 5: assertTrue(2 == hist[bin]); break; default: assertTrue(0 == hist[bin]); break; } } System.out.println(Util.printCoordinates(hist)); // Histograms long[] radius = new long[]{0, 0}; lh = new LinearHistogram<UnsignedByteType>(9, 2, min, max); IntegralHistogramCursor<T, UnsignedByteType> hs = new IntegralHistogramCursor<T, UnsignedByteType>(h, lh, radius); hs.setPosition(2, 0); hs.setPosition(2, 1); hist = hs.get().bins; System.out.println("From Histograms, 0x0: " + Util.printCoordinates(hist)); for (int bin=0; bin<9; ++bin) { if (8 == bin) assertTrue(1 == hist[bin]); else assertTrue(0 == hist[bin]); } radius = new long[]{1, 1}; // means 3x3 centered on the pixel hs = new IntegralHistogramCursor<T, UnsignedByteType>(h, lh, radius); hs.setPosition(2, 0); hs.setPosition(2, 1); hist = hs.get().bins; System.out.println("From Histograms, 3x3: " + Util.printCoordinates(hist)); for (int bin=0; bin<9; ++bin) { switch (bin) { case 3: case 8: assertTrue(1 == hist[bin]); break; case 5: assertTrue(2 == hist[bin]); break; default: assertTrue(0 == hist[bin]); break; } } radius = new long[]{0, 0}; lh = new LinearHistogram<UnsignedByteType>(9, 2, new UnsignedByteType(1), new UnsignedByteType(9)); Img<UnsignedByteType> integralHistogram = IntegralHistogram.create(img, lh, new UnsignedByteType()); HistogramFeatures<UnsignedByteType, UnsignedByteType> features = new HistogramFeatures<UnsignedByteType, UnsignedByteType>(img, integralHistogram, lh, radius); try { ImgLib.wrap(features, "features for 0x0"); } catch (ImgLibException e) { e.printStackTrace(); } } /** * 3x3x3 * * 1 2 3 2 4 6 3 6 9 * 2 4 6 4 8 12 6 12 18 * 3 6 9 6 12 18 9 18 27 * * 36 + 72 + 108 * * * In the histogram, the bottom right should have: * {1:1, 2:3, 3:3, 4:3, 5:0, 6:6, 7:0, 8:1, 9:3, * 10:0, 11:0, 12:3, 13:0, 14:0, 15:0, 16:0, 17:0, 18:3, * 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, 27:1} * */ @Test public <T extends IntegerType<T> & NativeType<T> >void testHistogramOf3x3x3Img() { Img< UnsignedByteType > img = ArrayImgs.unsignedBytes( 3, 3, 3 ); Cursor<UnsignedByteType> c = img.cursor(); long[] position = new long[3]; int sum = 0; while (c.hasNext()) { c.fwd(); c.localize(position); int v = 1; for (int i=0; i<position.length; ++i) v *= position[i] + 1; c.get().set(v); sum += v; } System.out.println("sum is " + sum); assertTrue("Test image isn't right", sum == 36 + 72 + 108); // // Histogram UnsignedByteType min = new UnsignedByteType(1); UnsignedByteType max = new UnsignedByteType(27); LinearHistogram<UnsignedByteType> lh = new LinearHistogram<UnsignedByteType>(27, img.numDimensions(), min, max); Img<T> h = IntegralHistogram.create(img, lh); // Expected cummulative: final int[] expected = new int[]{ 1, 3, 3, 3, 0, 6, 0, 1, 3, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; IntegralHistogramCursor<T, UnsignedByteType> ihc = new IntegralHistogramCursor<T, UnsignedByteType>(h, lh, new long[]{1, 1, 1}); ihc.setPosition(new long[]{3, 3, 3, 0}); Histogram<UnsignedByteType> lastHistogram = ihc.get(); System.out.println(Util.printCoordinates(lastHistogram.bins)); StringBuilder sb = new StringBuilder("{"); RandomAccess<T> ra = h.randomAccess(); ra.setPosition(3, 0); ra.setPosition(3, 1); ra.setPosition(3, 2); for (int i=0; i<27; ++i) { ra.setPosition(i, 3); if (i > 0) sb.append(',').append(' '); sb.append(i+1).append(':').append(ra.get().getInteger()); //assertTrue("Cummulative histogram isn't right: " + sb.toString(), expected[i] == ra.get().getInteger()); } sb.append('}'); System.out.println("Cummulative Histogram: " + sb.toString()); } /** * 1 2 2 4 * 2 4 4 8 */ @Test public <T extends IntegerType<T> & NativeType<T>> void testHistogramOf2x2x2Img() { Img< UnsignedByteType > img = ArrayImgs.unsignedBytes( 2, 2, 2 ); Cursor<UnsignedByteType> c = img.cursor(); long[] position = new long[3]; int sum = 0; while (c.hasNext()) { c.fwd(); c.localize(position); int v = 1; for (int i=0; i<position.length; ++i) v *= position[i] + 1; c.get().set(v); sum += v; } System.out.println("sum is " + sum); assertTrue("Test image isn't right", sum == 27); // // Histogram UnsignedByteType min = new UnsignedByteType(1); UnsignedByteType max = new UnsignedByteType(8); LinearHistogram<UnsignedByteType> lh = new LinearHistogram<UnsignedByteType>(8, img.numDimensions(), min, max); Img<T> h = IntegralHistogram.create(img, lh); // Show img try { ImgLib.wrap(img, "2x2x2"); } catch (ImgLibException e1) { e1.printStackTrace(); } // Show integral histogram try { ImagePlusImg< UnsignedByteType, ? > ii = new ImagePlusImgFactory<>( new UnsignedByteType() ).create( h ); Cursor<UnsignedByteType> c1 = ii.cursor(); Cursor<T> c2 = h.cursor(); while (c1.hasNext()) { c1.next().setReal(c2.next().getRealDouble()); } ii.getImagePlus(); } catch (ImgLibException e) { e.printStackTrace(); } long[] radius = new long[]{0, 0, 0}; IntegralHistogramCursor<T, UnsignedByteType> ihc = new IntegralHistogramCursor<T, UnsignedByteType>(h, lh, radius); ihc.setPosition(new long[]{2, 2, 2, 0}); Histogram<UnsignedByteType> lastHistogram = ihc.get(); System.out.println("Histogram at 2x2x2 for radius " + Util.printCoordinates(radius) + ": " + Util.printCoordinates(lastHistogram.bins)); // Expected cumulative: final int[] expected = new int[]{ 1, 3, 0, 3, 0, 0, 0, 1 }; StringBuilder sb = new StringBuilder("{"); RandomAccess<T> ra = h.randomAccess(); ra.setPosition(2, 0); ra.setPosition(2, 1); ra.setPosition(2, 2); for (int i=0; i<8; ++i) { ra.setPosition(i, 3); if (i > 0) sb.append(',').append(' '); sb.append(i+1).append(':').append(ra.get().getInteger()); //assertTrue("Cummulative histogram isn't right: " + sb.toString(), expected[i] == ra.get().getInteger()); } sb.append('}'); System.out.println("Cummulative Histogram at 2,2,2: " + sb.toString()); // Print all cumulative histograms RandomAccess<T> r = h.randomAccess(); for (int z=0; z<2; ++z) { r.setPosition(z, 2); for (int y=0; y<2; ++y) { r.setPosition(y, 1); for (int x=0; x<2; ++x) { r.setPosition(x, 0); StringBuffer s = new StringBuffer("("); for (int bin=0; bin<8; ++bin) { r.setPosition(bin, 3); s.append(r.get().getIntegerLong()); if (bin < 7) s.append(", "); } s.append(')'); System.out.println(Util.printCoordinates(r) + " --> " + s); } } } // Print each histogram System.out.println("All histograms:"); ihc.reset(); while (ihc.hasNext()) { ihc.fwd(); Histogram<UnsignedByteType> a = ihc.get(); System.out.println(Util.printCoordinates(ihc) + " -- " + Util.printCoordinates(a.bins)); } } }
gpl-2.0
alexanderfefelov/nav
python/nav/ipdevpoll/plugins/ciscovlan.py
4983
# # Copyright (C) 2009-2012 UNINETT AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. You should have received a copy of the GNU General Public # License along with NAV. If not, see <http://www.gnu.org/licenses/>. # """ipdevpoll plugin to collect 802.1q VLAN information from Cisco devices. CISCO-VTP-MIB and CISCO-VLAN-MEMBERSHIP-MIB are used as sources for this plugin. """ from twisted.internet import defer from nav.mibs.if_mib import IfMib from nav.mibs.cisco_vtp_mib import CiscoVTPMib from nav.mibs.cisco_vlan_membership_mib import CiscoVlanMembershipMib from nav.mibs.cisco_vlan_iftable_relationship_mib \ import CiscoVlanIftableRelationshipMib from nav.ipdevpoll import Plugin from nav.ipdevpoll import shadows VENDORID_CISCO = 9 class CiscoVlan(Plugin): """Collect 802.1q info from CISCO-VTP-MIB and CISCO-VLAN-MEMBERSHIP-MIB.""" _valid_ifindexes = () @classmethod def can_handle(cls, netbox): daddy_says_ok = super(CiscoVlan, cls).can_handle(netbox) if netbox.type: vendor_id = netbox.type.get_enterprise_id() if vendor_id != VENDORID_CISCO: return False return daddy_says_ok @defer.inlineCallbacks def handle(self): ciscovtp = CiscoVTPMib(self.agent) ciscovm = CiscoVlanMembershipMib(self.agent) ciscovlanif = CiscoVlanIftableRelationshipMib(self.agent) enabled_vlans = yield ciscovtp.get_trunk_enabled_vlans( as_bitvector=True) native_vlans = yield ciscovtp.get_trunk_native_vlans() vlan_membership = yield ciscovm.get_vlan_membership() vlan_ifindex = yield ciscovlanif.get_routed_vlan_ifindexes() if vlan_membership or native_vlans or enabled_vlans or vlan_ifindex: self._logger.debug("vlan_membership: %r", vlan_membership) self._logger.debug("native_vlans: %r", native_vlans) self._logger.debug("enabled_vlans: %r", enabled_vlans) self._logger.debug("vlan_ifindex: %r", vlan_ifindex) self._valid_ifindexes = yield self._get_ifindexes() self._store_access_ports(vlan_membership) self._store_trunk_ports(native_vlans, enabled_vlans) self._store_vlan_ifc_relationships(vlan_ifindex) @defer.inlineCallbacks def _get_ifindexes(self): ifmib = IfMib(self.agent) indexes = yield ifmib.get_ifindexes() defer.returnValue(set(indexes)) def _store_access_ports(self, vlan_membership): """Store vlan memberships for all ports.""" for ifindex, vlan in vlan_membership.items(): if ifindex not in self._valid_ifindexes: self._logger.debug("ignoring info for invalid ifindex %s", ifindex) continue interface = self.containers.factory(ifindex, shadows.Interface) interface.trunk = False interface.vlan = vlan if not interface.baseport: interface.baseport = -ifindex def _store_trunk_ports(self, native_vlans, enabled_vlans): """Store the set of enabled vlans for each trunk port.""" for ifindex, vector in enabled_vlans.items(): if ifindex not in self._valid_ifindexes: self._logger.debug("ignoring info for invalid ifindex %s", ifindex) continue interface = self.containers.factory(ifindex, shadows.Interface) interface.trunk = True if ifindex in native_vlans: interface.vlan = native_vlans[ifindex] self._logger.debug("Trunk port %r enabled VLAN count: %s", interface.ifname, len(vector.get_set_bits())) allowed = self.containers.factory(ifindex, shadows.SwPortAllowedVlan) allowed.interface = interface allowed.hex_string = vector.to_hex() def _store_vlan_ifc_relationships(self, routed_vlans): for route in routed_vlans: ifc = self.containers.factory(route.virtual, shadows.Interface) ifc.vlan = route.vlan vlan = self.containers.factory(route.virtual, shadows.Vlan) vlan.vlan = route.vlan if route.physical: phys_ifc = self.containers.factory(route.physical, shadows.Interface) phys_ifc.trunk = True
gpl-2.0
digama0/mmj2
src/mmj/transforms/ReplaceInfo.java
11473
//*****************************************************************************/ //* Copyright (C) 2014 */ //* ALEXEY MERKULOV steelart (dot) alex (at) gmail (dot) com */ //* License terms: GNU General Public License Version 2 */ //* or any later version */ //*****************************************************************************/ package mmj.transforms; import java.util.*; import java.util.Map.Entry; import mmj.lang.*; import mmj.pa.ProofStepStmt; public class ReplaceInfo extends DBInfo { /** The information about equivalence rules */ private final EquivalenceInfo eqInfo; private final ImplicationInfo implInfo; /** * The list of rules for variable replacement: * "B = B' => f(A,B,C) = f(A,B',C)" */ private final Map<Stmt, Assrt[]> replaceOp = new HashMap<>(); /** * The list of rules for variable replacement (implication form): * "B = B' -> f(A,B,C) = f(A,B',C)" */ private final Map<Stmt, Assrt[]> implReplaceOp = new HashMap<>(); // ------------------------------------------------------------------------ // ------------------------Initialization---------------------------------- // ------------------------------------------------------------------------ public ReplaceInfo(final EquivalenceInfo eqInfo, final ImplicationInfo implInfo, final List<Assrt> assrtList, final TrOutput output, final boolean dbg) { super(output, dbg); this.eqInfo = eqInfo; this.implInfo = implInfo; for (final Assrt assrt : assrtList) { findReplaceRules(assrt); findImplReplaceRules(assrt); } if (dbg) { dbgCompare(replaceOp, implReplaceOp, "replaceOp"); dbgCompare(implReplaceOp, replaceOp, "implReplaceOp"); } } private void dbgCompare(final Map<Stmt, Assrt[]> resMap1, final Map<Stmt, Assrt[]> resMap2, final String mapName1) { for (final Entry<Stmt, Assrt[]> elem : resMap1.entrySet()) { final Assrt[] assrts = elem.getValue(); final Stmt stmt = elem.getKey(); final Assrt[] otherAssrts = resMap2.get(stmt); if (otherAssrts == null) { output.dbgMessage(dbg, TrConstants.ERRMSG_REPL_UNIQUE_COLLECTION, mapName1, stmt.toString()); continue; } assert assrts.length == otherAssrts.length; for (int i = 0; i < assrts.length; i++) if (assrts[i] != null && otherAssrts[i] == null) output.dbgMessage(dbg, TrConstants.ERRMSG_REPL_UNIQUE_ASSRT, mapName1, stmt.toString(), i); } } /** * Filters replace rules, like A = B => g(A) = g(B) * * @param assrt the candidate */ private void findReplaceRules(final Assrt assrt) { final LogHyp[] logHyps = assrt.getLogHypArray(); final ParseTree assrtTree = assrt.getExprParseTree(); if (logHyps.length != 1) return; // Maybe depth restriction could be weaken if (assrtTree.getMaxDepth() != 3) return; final ParseNode replRoot = assrtTree.getRoot(); final ParseNode hypNode = logHyps[0].getExprParseTree().getRoot(); coreCheck(assrt, replRoot, hypNode, replaceOp); } /** * Filters replace rules in implication form, like A = B -> g(A) = g(B) * * @param assrt the candidate */ private void findImplReplaceRules(final Assrt assrt) { final LogHyp[] logHyps = assrt.getLogHypArray(); final ParseTree assrtTree = assrt.getExprParseTree(); if (logHyps.length != 0) return; // Maybe depth restriction could be weaken if (assrtTree.getMaxDepth() != 4) return; final ParseNode root = assrtTree.getRoot(); if (!implInfo.isImplOperator(root.stmt)) return; final ParseNode replRoot = root.child[1]; final ParseNode hypNode = root.child[0]; coreCheck(assrt, replRoot, hypNode, implReplaceOp); } // the main search algorithm private void coreCheck(final Assrt assrt, final ParseNode replRoot, final ParseNode hypNode, final Map<Stmt, Assrt[]> resMap) { if (!eqInfo.isEquivalence(replRoot.stmt)) return; if (!eqInfo.isEquivalence(hypNode.stmt)) return; final ParseNode[] hypSubTrees = hypNode.child; assert hypSubTrees.length == 2 : "It should be the equivalence rule!"; if (!TrUtil.isVarNode(hypSubTrees[0]) || !TrUtil.isVarNode(hypSubTrees[1])) return; final ParseNode[] subTrees = replRoot.child; assert subTrees.length == 2 : "It should be the equivalence rule!"; if (subTrees[0].stmt != subTrees[1].stmt) return; final Stmt stmt = subTrees[0].stmt; final ParseNode[] leftChild = subTrees[0].child; final ParseNode[] rightChild = subTrees[1].child; // Fast compare, change if the depth of this assrt statement tree // could be more then 3 int replPos = -1; replaceCheck: for (int i = 0; i < leftChild.length; i++) if (leftChild[i].stmt != rightChild[i].stmt) { // Another place for replace? It is strange! if (replPos != -1) return; // We found the replace replPos = i; // Check that it is actually the swap of two variables for (int k = 0; k < 2; k++) { final int m = (k + 1) % 2; // the other index if (leftChild[i].stmt == hypSubTrees[k].stmt && rightChild[i].stmt == hypSubTrees[m].stmt) continue replaceCheck; } return; } Assrt[] repl = resMap.get(stmt); if (repl == null) { repl = new Assrt[subTrees[0].child.length]; resMap.put(stmt, repl); } // it is the first such assrt; if (repl[replPos] != null) return; repl[replPos] = assrt; output.dbgMessage(dbg, TrConstants.ERRMSG_REPL_ASSRTS, stmt, replPos, assrt, assrt.getFormula()); } /** * @param stmt the statement * @return true if all children in the statement could be replaced with * equal children. */ public boolean isFullReplaceStatement(final Stmt stmt) { final Assrt[] replAssrts = replaceOp.get(stmt); if (replAssrts == null) return false; for (final Assrt assrt : replAssrts) if (assrt == null) return false; return true; } // ------------------------------------------------------------------------ // ------------------------Transformations--------------------------------- // ------------------------------------------------------------------------ private ProofStepStmt createReplaceStepSimple(final WorksheetInfo info, final ParseNode prevVersion, final int i, final ParseNode newSubTree, final ProofStepStmt childTrStmt, final Assrt[] replAsserts) { assert replAsserts[i] != null; final Stmt equalStmt = replAsserts[i].getExprParseTree().getRoot().stmt; final ParseNode resNode = prevVersion.shallowClone(); // Fill the next child // So the new node has form g(A, B', C) resNode.child[i] = newSubTree; // Create node g(A, B, C) = g(A, B', C) final ParseNode stepNode = TrUtil.createBinaryNode(equalStmt, prevVersion, resNode); // Create statement d:childTrStmt:replAssert // |- g(A, B, C) = g(A, B', C) final ProofStepStmt stepTr = info.getOrCreateProofStepStmt(stepNode, new ProofStepStmt[]{childTrStmt}, replAsserts[i]); return stepTr; } private GenProofStepStmt createReplaceStepImpl(final WorksheetInfo info, final ParseNode prevVersion, final int i, final ParseNode newSubTree, final GenProofStepStmt childTrStmt, final Assrt[] replAsserts) { assert replAsserts[i] != null; final ParseNode root = replAsserts[i].getExprParseTree().getRoot(); final Stmt equalStmt = root.child[1].stmt; final ParseNode resNode = prevVersion.shallowClone(); // Fill the next child // So the new node has form g(A, B', C) resNode.child[i] = newSubTree; // Create node g(A, B, C) = g(A, B', C) final ParseNode eqNode = TrUtil.createBinaryNode(equalStmt, prevVersion, resNode); return implInfo.applyHyp(info, childTrStmt, eqNode, replAsserts[i]); } /** * Creates replace step (e.g. g(A, B, C) <-> g(A, B', C)). Note: the * equivalence operators for 'g' and for 'B' could differ! * * @param info the work sheet info * @param prevVersion the source node (e.g. g(A, B, C) ) * @param i the position for replace (e.g. 1 (second)) * @param newSubTree the new child (e.g. B') * @param childTrStmt the equivalence of children (e.g. B = B' ) * @return the replace step */ public GenProofStepStmt createReplaceStep(final WorksheetInfo info, final ParseNode prevVersion, final int i, final ParseNode newSubTree, final GenProofStepStmt childTrStmt) { if (!childTrStmt.hasPrefix()) { final Assrt[] replAsserts = replaceOp.get(prevVersion.stmt); if (replAsserts != null && replAsserts[i] != null) return new GenProofStepStmt( createReplaceStepSimple(info, prevVersion, i, newSubTree, childTrStmt.getSimpleStep(), replAsserts), null); } final Assrt[] replAsserts = implReplaceOp.get(prevVersion.stmt); assert replAsserts != null; assert replAsserts[i] != null; return createReplaceStepImpl(info, prevVersion, i, newSubTree, childTrStmt, replAsserts); } // ------------------------------------------------------------------------ // ------------------------------Getters----------------------------------- // ------------------------------------------------------------------------ public boolean[] getPossibleReplaces(final Stmt stmt, final WorksheetInfo info) { final Assrt[][] assrts; final Assrt[] simple = replaceOp.get(stmt); final Assrt[] implForm = replaceOp.get(stmt); if (!info.hasImplPrefix()) { assrts = new Assrt[][]{simple, implForm}; if (simple != null && implForm != null) assert simple.length == implForm.length; } else assrts = new Assrt[][]{implForm}; boolean[] res = null; for (final Assrt[] assrt : assrts) if (assrt != null) { if (res == null) res = new boolean[assrt.length]; for (int i = 0; i < assrt.length; i++) if (assrt[i] != null) res[i] = true; } return res; } }
gpl-2.0
lewurm/graal
graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/MathSubstitutionsX86.java
5465
/* * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.replacements; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.graph.Node.ConstantNodeParameter; import com.oracle.graal.graph.Node.NodeIntrinsic; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.replacements.nodes.*; import com.oracle.graal.replacements.nodes.MathIntrinsicNode.Operation; /** * Substitutions for {@link java.lang.Math} methods. */ @ClassSubstitution(value = java.lang.Math.class) public class MathSubstitutionsX86 { private static final double PI_4 = Math.PI / 4; @MethodSubstitution public static double abs(double x) { return MathIntrinsicNode.compute(x, Operation.ABS); } @MethodSubstitution public static double sqrt(double x) { return MathIntrinsicNode.compute(x, Operation.SQRT); } @MethodSubstitution(guard = UnsafeSubstitutions.GetAndSetGuard.class) public static double log(double x) { return MathIntrinsicNode.compute(x, Operation.LOG); } @MethodSubstitution(guard = UnsafeSubstitutions.GetAndSetGuard.class) public static double log10(double x) { return MathIntrinsicNode.compute(x, Operation.LOG10); } /** * Special cases from {@link Math#pow} and __ieee754_pow (in sharedRuntimeTrans.cpp). */ @MethodSubstitution(guard = UnsafeSubstitutions.GetAndSetGuard.class) public static double pow(double x, double y) { // If the second argument is positive or negative zero, then the result is 1.0. if (y == 0) { return 1; } // If the second argument is 1.0, then the result is the same as the first argument. if (y == 1) { return x; } // If the second argument is NaN, then the result is NaN. if (Double.isNaN(y)) { return Double.NaN; } // If the first argument is NaN and the second argument is nonzero, then the result is NaN. if (Double.isNaN(x) && y != 0) { return Double.NaN; } // x**-1 = 1/x if (y == -1) { return 1 / x; } // x**2 = x*x if (y == 2) { return x * x; } // x**0.5 = sqrt(x) if (y == 0.5 && x >= 0) { return sqrt(x); } return pow(x, y); } // NOTE on snippets below: // Math.sin(), .cos() and .tan() guarantee a value within 1 ULP of the // exact result, but x87 trigonometric FPU instructions are only that // accurate within [-pi/4, pi/4]. Examine the passed value and provide // a slow path for inputs outside of that interval. @MethodSubstitution(guard = UnsafeSubstitutions.GetAndSetGuard.class) public static double sin(double x) { if (abs(x) < PI_4) { return MathIntrinsicNode.compute(x, Operation.SIN); } else { return callDouble(ARITHMETIC_SIN, x); } } @MethodSubstitution(guard = UnsafeSubstitutions.GetAndSetGuard.class) public static double cos(double x) { if (abs(x) < PI_4) { return MathIntrinsicNode.compute(x, Operation.COS); } else { return callDouble(ARITHMETIC_COS, x); } } @MethodSubstitution(guard = UnsafeSubstitutions.GetAndSetGuard.class) public static double tan(double x) { if (abs(x) < PI_4) { return MathIntrinsicNode.compute(x, Operation.TAN); } else { return callDouble(ARITHMETIC_TAN, x); } } public static final ForeignCallDescriptor ARITHMETIC_SIN = new ForeignCallDescriptor("arithmeticSin", double.class, double.class); public static final ForeignCallDescriptor ARITHMETIC_COS = new ForeignCallDescriptor("arithmeticCos", double.class, double.class); public static final ForeignCallDescriptor ARITHMETIC_TAN = new ForeignCallDescriptor("arithmeticTan", double.class, double.class); @NodeIntrinsic(value = ForeignCallNode.class, setStampFromReturnType = true) public static double callDouble(@ConstantNodeParameter ForeignCallDescriptor descriptor, double value) { if (descriptor == ARITHMETIC_SIN) { return Math.sin(value); } if (descriptor == ARITHMETIC_COS) { return Math.cos(value); } assert descriptor == ARITHMETIC_TAN; return Math.tan(value); } }
gpl-2.0
hglukhova/site
templates/yoo_expo/warp/systems/joomla/elements/verify.php
2378
<?php /** * @package Warp Theme Framework * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) YOOtheme GmbH * @license YOOtheme Proprietary Use License (http://www.yootheme.com/license) */ jimport('joomla.html.html'); jimport('joomla.form.formfield'); class JFormFieldVerify extends JFormField { protected $type = 'Verify'; protected function getInput() { // load config require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/config.php'); // get warp and helpers $warp =& Warp::getInstance(); $path =& $warp->getHelper('path'); $check =& $warp->getHelper('checksum'); // verify theme files $content = array('<div style="margin: 5px 0px;float: left;">'); if (($checksums = $path->path('template:checksums')) && filesize($checksums)) { $check->verify($path->path('template:'), $log); if (count($log)) { $content[] = 'Some template files have been modified. <a href="#" class="verify-link">Click to show files.</a>'; $content[] = '<ul class="verify">'; foreach (array('modified', 'missing') as $type) { if (isset($log[$type])) { foreach ($log[$type] as $file) { $content[] = '<li class="'.$type.'">'.$file.($type == 'missing' ? ' (missing)' : null).'</li>'; } } } $content[] = '</ul>'; } else { $content[] = 'Verification successful, no file modifications detected.'; } } else { $content[] = 'Checksum file is missing! Your template is maybe compromised.'; } $content[] = '</div>'; ob_start(); ?> <style type="text/css"> ul.verify { margin: 5px 0px 0px 0px; padding: 5px; background: #EEE; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; } ul.verify li { margin: 5px; padding: 0px; } ul.verify li.missing { color: red; } </style> <script type="text/javascript"> window.addEvent('domready', function(){ var ul = document.getElement("ul.verify"); if (ul) { ul.setStyle('display', 'none'); document.getElement("a.verify-link").addEvent("click", function(event){ var event = new Event(event).stop(); ul.setStyle('display', ul.getStyle('display') == 'none' ? 'block' : 'none'); }); } }); </script> <?php return implode("\n", $content).ob_get_clean(); } }
gpl-2.0
rickbutton/JarvisSharp
Jarvis/Plugins/Music/Player.cs
4337
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; using NAudio.Wave; using Torshify; namespace Jarvis.Plugins.Music { public class Player { private WaveFormat _format; private BufferedWaveProvider _provider; private WaveOut _out; private bool _playing; private IPlayerQueue _queue; private ISession _session; private int _trackIndex = 0; public Player(ISession session) { _session = session; _session.MusicDeliver += HandleAudio; _session.EndOfTrack += HandleEndOfTrack; } private void LoadTrack(int index) { if (_playing) { _session.PlayerUnload(); } var track = _queue[index]; _session.PlayerLoad(track); _trackIndex = index; } private void HandleEndOfTrack(object sender, SessionEventArgs e) { if (_trackIndex < _queue.Count - 1) // there are more tracks { LoadTrack(_trackIndex + 1); // load next track Play(true); } else { Stop(); // out of tracks _trackIndex = 0; } } public void LoadSong(ISearch search) { _queue = new SearchQueue(_session, search, 1); LoadTrack(0); } public void LoadSearch(ISearch search) { _queue = new SearchQueue(_session, search); LoadTrack(0); } public void LoadPlaylist(IPlaylist playlist) { _queue = new PlaylistQueue(playlist); LoadTrack(0); } public void LoadArtist(IArtist artist) { _queue = new ArtistQueue(artist); LoadTrack(0); } public void Reset() { Stop(); ClearQueue(); } public void ClearQueue() { _queue = null; } public void Stop() { Pause(); if (_provider != null) _provider.ClearBuffer(); } public void Next() { _provider.ClearBuffer(); if (_trackIndex < _queue.Count - 1) { LoadTrack(_trackIndex + 1); } else { LoadTrack(0); } Play(true); } public void Previous() { _provider.ClearBuffer(); if (_trackIndex > 0) { LoadTrack(_trackIndex - 1); } else { LoadTrack(_queue.Count - 1); } Play(true); } public void HandleAudio(object sender, MusicDeliveryEventArgs e) { if (_format == null) { _format = new WaveFormat(e.Rate, e.Channels); } if (_provider == null) { _provider = new BufferedWaveProvider(_format); } var consumed = 0; if (_playing && (_provider.BufferLength - _provider.BufferedBytes) > e.Samples.Length) { _provider.AddSamples(e.Samples, 0, e.Samples.Length); consumed = e.Frames; } e.ConsumedFrames = consumed; if (_out == null) { _out = new WaveOut(); _out.Init(_provider); if (_playing) _out.Play(); else _out.Pause(); } } public void Play(bool forcePlay = false) { if (!_playing || forcePlay) { _session.PlayerPlay(); if (_out != null) _out.Play(); } _playing = true; } public void Pause() { if (_playing) { _session.PlayerPause(); if (_out != null) _out.Pause(); } _playing = false; } } }
gpl-2.0
bloxtheme/BloxTheme
bloxtheme/library/visual-editor/scripts-src/util.saving.js
6998
define(['jquery', 'util.loader', 'knockout', 'deps/json2'], function($, loader, ko) { save = function() { /* If saving isn't allowed, don't try to save. */ if ( typeof isSavingAllowed === 'undefined' || isSavingAllowed === false ) { return false; } /* If currently saving, do not do it again. */ if ( typeof currentlySaving !== 'undefined' && currentlySaving === true ) { return false; } currentlySaving = true; savedTitle = $('title').text(); saveButton = $('span#save-button'); saveButton .text('Saving...') .addClass('active') .css('cursor', 'wait'); /* Change the title */ changeTitle('Visual Editor: Saving'); startTitleActivityIndicator(); /* Do the stuff */ $.post(Blox.ajaxURL, { security: Blox.security, action: 'blox_visual_editor', method: 'save_options', options: JSON.stringify(GLOBALunsavedValues), layout: Blox.viewModels.layoutSelector.currentLayout(), mode: Blox.mode }, function(response) { delete currentlySaving; /* If the AJAX response is '0' then show a log in alert */ if ( response === '0' ) { saveButton.stop(true); saveButton.text('Save'); saveButton.removeClass('active'); saveButton.css('cursor', 'pointer'); return showErrorNotification({ id: 'error-wordpress-authentication', message: '<strong>Notice!</strong><br /><br />Your WordPress authentication has expired and you must log in before you can save.<br /><br /><a href="' + Blox.adminURL + '" target="_blank">Click Here to log in</a>, then switch back to the window/tab the Visual Editor is in.', closeTimer: false, closable: true }); /* If it's not a successful save, revert the save button to normal and display an alert. */ } else if ( typeof response.errors !== 'undefined' || (typeof response != 'object' && response != 'success') ) { saveButton.stop(true); saveButton.text('Save'); saveButton.removeClass('active'); saveButton.css('cursor', 'pointer'); var errorMessage = 'There was an error while saving. Please try again'; if ( typeof response.errors != 'undefined' ) { errorMessage += '<br /><ul>'; $.each(response.errors, function(errorIndex, errorValue) { errorMessage += '<li>' + errorValue + '</li>'; }); errorMessage += '</ul>'; } return showErrorNotification({ id: 'error-invalid-save-response', message: errorMessage, closeTimer: false, closable: true }); /* Successful Save */ } else { /* Hide any previous save errors */ hideNotification('error-wordpress-authentication'); hideNotification('error-invalid-save-response'); saveButton.animate({boxShadow: '0 0 0 #7dd1e2'}, 350); setTimeout(function() { saveButton.css('boxShadow', ''); saveButton.stop(true); saveButton.text('Save'); saveButton.removeClass('active'); saveButton.css('cursor', 'pointer'); /* Replace temporary IDs on new blocks with the new ID */ if ( typeof response['block-id-mapping'] !== 'undefined' ) { $.each(response['block-id-mapping'], function(tempID, id) { var block = $i('.block[data-temp-id="' + tempID + '"]'); block.attr('id', 'block-' + id) .data('id', id) .attr('data-id', id) .removeAttr('data-temp-id') .removeAttr('data-desired-id') .removeData('duplicateOf') .removeData('temp-id') .removeData('desired-id'); updateBlockContentCover(block); /* Reload options with proper ID */ if ( $('#block-' + tempID + '-tab').length ) { var currentSubTab = $('#block-' + tempID + '-tab').find('.sub-tabs .ui-tabs-active').attr('aria-controls'); removePanelTab('block-' + tempID); openBlockOptions(block, currentSubTab) } }); } /* Replace temporary IDs on new wrapper with the new ID */ if ( typeof response['wrapper-id-mapping'] !== 'undefined' ) { $.each(response['wrapper-id-mapping'], function(tempID, id) { var wrapper = $i('.wrapper[data-temp-id="' + tempID + '"]'); wrapper.attr('id', 'wrapper-' + id) .data('id', id) .attr('data-id', id) .removeData('temp-id') .removeData('desired-id'); /* Reload options with proper ID */ if ( $('#wrapper-' + tempID + '-tab').length ) { removePanelTab('wrapper-' + tempID); openWrapperOptions(id); } }); } /* Clear out hidden inputs */ clearUnsavedValues(); /* Output information about snapshot */ if ( typeof response['snapshot'] !== 'undefined' && typeof response['snapshot'].timestamp !== 'undefined' ) { showNotification({ id: 'snapshot-saved', message: 'Snapshot automatically saved.', success: true }); Blox.viewModels.snapshots.snapshots.unshift({ id: response['snapshot'].id, timestamp: response['snapshot'].timestamp, comments: response['snapshot'].comments }); } /* Set the current layout to customized after save */ if ( $('li.layout-selected').length ) { ko.dataFor($('li.layout-selected').get(0)).customized(true); } /* Fade back to inactive save button. */ disallowSaving(); /* Reset the title and show the saving complete notification */ setTimeout(function() { stopTitleActivityIndicator(); changeTitle(savedTitle); showNotification({ id: 'saving-complete', message: 'Saving Complete!', closeTimer: 3500, success: true }); }, 150); }, 350); allowVEClose(); //Do this here in case we have some speedy folks who want to close VE ultra-early after a save. } }); } clearUnsavedValues = function() { delete GLOBALunsavedValues; } allowSaving = function() { /* If it's the layout mode and there no blocks on the page, then do not allow saving. Also do not allow saving if there are overlapping blocks */ if ( (Blox.mode == 'grid' && $i('.block').length === 0) || (typeof Blox.overlappingBlocks != 'undefined' && Blox.overlappingBlocks) ) return disallowSaving(); /* If saving is already allowed, don't do anything else */ if ( typeof isSavingAllowed !== 'undefined' && isSavingAllowed === true ) return; $('body').addClass('allow-saving'); isSavingAllowed = true; /* Set reminder when trying to leave that there are changes. */ prohibitVEClose(); return true; } disallowSaving = function() { isSavingAllowed = false; $('body').removeClass('allow-saving'); /* User can safely leave VE now--changes are saved. As long as there are no overlapping blocks */ if ( typeof Blox.overlappingBlocks == 'undefined' || !Blox.overlappingBlocks ) allowVEClose(); return true; } });
gpl-2.0
stonebuzz/glpi
install/migrations/update_9.5.x_to_10.0.0/domains.php
4649
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2021 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GLPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /** * @var DB $DB * @var Migration $migration */ /** Domains improvements */ /** Add templates to domains */ $migration->addField('glpi_domains', 'is_template', 'bool', [ 'after' => 'comment' ]); $migration->addField('glpi_domains', 'template_name', 'string', [ 'after' => 'is_template' ]); $migration->addKey('glpi_domains', 'is_template'); /** /Add templates to domains */ /** Active domains */ $migration->addField('glpi_domains', 'is_active', 'bool', ['after' => 'template_name']); $migration->addKey('glpi_domains', 'is_active'); $migration->addPostQuery( $DB->buildUpdate( 'glpi_domains', ['is_active' => 1], [true] ) ); /** /Active domains */ //remove "useless "other" field $migration->dropField('glpi_domains', 'others'); // Add fields descriptor field if (!$DB->fieldExists('glpi_domainrecordtypes', 'fields')) { $migration->addField( 'glpi_domainrecordtypes', 'fields', 'text', [ 'after' => 'name' ] ); foreach (DomainRecordType::getDefaults() as $type) { if (countElementsInTable('glpi_domainrecordtypes', ['name' => $type['name']]) === 0) { continue; } $migration->addPostQuery( $DB->buildUpdate( 'glpi_domainrecordtypes', ['fields' => $type['fields']], ['name' => $type['name']] ) ); } } else { // "fields" descriptor already exists, but may correspond to an outdated version //add is_fqdn on some domain records types $fields = [ 'CNAME' => ['target'], 'MX' => ['server'], 'SOA' => ['primary_name_server', 'primary_contact'], 'SRV' => ['target'] ]; $fields_it = $DB->request([ 'FROM' => 'glpi_domainrecordtypes', 'WHERE' => ['name' => array_keys($fields)] ]); while ($field = $fields_it->next()) { if (empty($field['fields']) || $field['fields'] === '[]') { if ($field['name'] === 'CNAME') { //cname field definition has been added $field['fields'] = json_encode([[ 'key' => 'target', 'label' => 'Target', 'placeholder' => 'sip.example.com.', 'is_fqdn' => true ]]); } else { continue; } } $type_fields = DomainRecordType::decodeFields($field['fields']); $updated = false; foreach ($type_fields as &$conf) { if (in_array($conf['key'], $fields[$field['name']])) { $conf['is_fqdn'] = true; $updated = true; } } if ($updated) { $migration->addPostQuery( $DB->buildUpdate( 'glpi_domainrecordtypes', ['fields' => json_encode($type_fields)], ['name' => $field['name']] ) ); } } } // Create new CAA default if (countElementsInTable('glpi_domainrecordtypes', ['name' => 'CAA']) === 0) { foreach (DomainRecordType::getDefaults() as $type) { if ($type['name'] === 'CAA') { unset($type['id']); $migration->addPostQuery( $DB->buildInsert( 'glpi_domainrecordtypes', $type ) ); break; } } } // Add a field to store record data as an object if user inputs data using helper form $migration->addField( 'glpi_domainrecords', 'data_obj', 'text', [ 'after' => 'data' ] );
gpl-2.0
dolly22/openttd-sai
src/saiext/sqlite3/api/sqlite_reader.cpp
2657
/** @file sqlite_reader.cpp Implementation of SqliteReader. */ #include "sqlite_reader.hpp" #include "../../../string_func.h" SqliteReader::SqliteReader(SqliteCommand *cmd) : cmd(cmd) { ++cmd->refs; } SqliteReader::~SqliteReader() { this->Close(); } bool SqliteReader::Read() { requireOpened(); switch(sqlite3_step(this->cmd->getStatement())) { case SQLITE_ROW: return true; case SQLITE_DONE: return false; case SQLITE_ERROR: ReportError(sqlite3_errmsg(this->cmd->conn->db)); default: ReportError("Error occured while reading from SqliteReader."); } return false; } void SqliteReader::Close() { if (this->cmd) { if(--this->cmd->refs==0) this->cmd->Reset(); this->cmd = NULL; } } int SqliteReader::GetInt(int colIdx) { requireOpened(); return sqlite3_column_int(this->cmd->getStatement(), colIdx); } int SqliteReader::GetIntName(const char* colName) { return GetInt(GetIndex(colName)); } double SqliteReader::GetDouble(int colIdx) { requireOpened(); return sqlite3_column_double(this->cmd->getStatement(), colIdx); } double SqliteReader::GetDoubleName(const char* colName) { return GetDouble(GetIndex(colName)); } const char* SqliteReader::GetString(int colIdx) { requireOpened(); return (const char *)sqlite3_column_text(this->cmd->getStatement(), colIdx); } const char* SqliteReader::GetStringName(const char* colName) { return GetString(GetIndex(colName)); } SQInteger SqliteReader::_get(HSQUIRRELVM vm) { if (sq_gettype(vm, 2) != OT_STRING) return SQ_ERROR; const SQChar* colName; sq_getstring(vm, 2, &colName); try { // advanced method does not wait for exception... int colIndex = GetIndex(FS2OTTD(colName)); const char* value = (const char*)sqlite3_column_text(this->cmd->getStatement(), colIndex); sq_pushstring(vm, OTTD2FS(value), -1); } catch (SQInteger e) { return e; } return 1; } int SqliteReader::GetIndex(const char* colName) { // lookups and stuff... if (nameLookup.empty()) initNameLookup(); NameLookup::iterator iter = this->nameLookup.find(colName); if (iter == this->nameLookup.end()) { // column was not found char msg[1024]; seprintf(msg, lastof(msg), "Column '%s' was not found in datareader.", colName); ReportError(msg); } else { // found... return (*iter).second; } return -1; } void SqliteReader::requireOpened() { if (!this->cmd) ReportError("SqliteReader is closed."); } void SqliteReader::initNameLookup() { sqlite3_stmt* stmt = this->cmd->getStatement(); for(int i=0; i < cmd->argc; i++) { const char* colName = sqlite3_column_name(stmt, i); if (colName != '\0') { nameLookup[colName] = i; } } }
gpl-2.0