repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
metaborg/spoofax
org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/stratego/primitive/LocalPathPrimitive.java
1487
package org.metaborg.spoofax.core.stratego.primitive; import java.io.File; import org.apache.commons.vfs2.FileObject; import org.metaborg.core.resource.IResourceService; import org.metaborg.spoofax.core.stratego.primitive.generic.ASpoofaxPrimitive; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import com.google.inject.Inject; import org.spoofax.terms.util.TermUtils; public class LocalPathPrimitive extends ASpoofaxPrimitive { private final IResourceService resourceService; @Inject public LocalPathPrimitive(IResourceService resourceService) { super("local_path", 0, 0); this.resourceService = resourceService; } @Override protected IStrategoTerm call(IStrategoTerm current, Strategy[] svars, IStrategoTerm[] tvars, ITermFactory factory, IContext context) { if(!(TermUtils.isString(current))) { return null; } final IStrategoString currentStr = (IStrategoString) current; final String path = currentStr.stringValue(); final FileObject resource = resourceService.resolve(path); final File localPath = resourceService.localPath(resource); if(localPath == null) { return null; } return factory.makeString(localPath.getPath()); } }
apache-2.0
wapalxj/Android_C3_4_Thread_AsyncTask
C3_4_Thread_AsyncTask/c4_hm_16_asyncTask/src/androidTest/java/vero/com/myapplication/ApplicationTest.java
353
package vero.com.myapplication; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
fwassmer/aries
cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/util/Conversions.java
1657
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.cdi.container.internal.util; import java.util.Arrays; import org.osgi.util.converter.Converter; import org.osgi.util.converter.ConverterBuilder; import org.osgi.util.converter.StandardConverter; import org.osgi.util.converter.TypeRule; public class Conversions { public static String toString(Object object) { return INSTANCE._converter.convert(object).defaultValue("").to(String.class); } public static Converter c() { return INSTANCE._converter; } private Conversions() { ConverterBuilder builder = new StandardConverter().newConverterBuilder(); builder .rule(new TypeRule<>(String[].class, String.class, i -> Arrays.toString((String[])i))) .rule(new TypeRule<>(double[].class, String.class, i -> Arrays.toString((double[])i))) .rule(new TypeRule<>(int[].class, String.class, i -> Arrays.toString((int[])i))) .rule(new TypeRule<>(long[].class, String.class, i -> Arrays.toString((long[])i))); _converter = builder.build(); } public static final Conversions INSTANCE = new Conversions(); private final Converter _converter; }
apache-2.0
rosslamont/jxvc
jxvc/src/test/java/com/componentcorp/xml/validation/SubordinateFeaturesAndPropertyTest.java
8545
/* * Copyright 2017 rlamont. * * 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.componentcorp.xml.validation; import com.componentcorp.xml.validation.base.FeaturePropertyProvider; import com.componentcorp.xml.validation.test.helpers.BaseXMLValidationTest; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.parsers.SAXParser; import javax.xml.validation.Validator; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; /** * * @author rlamont */ public class SubordinateFeaturesAndPropertyTest extends BaseXMLValidationTest { public static final String SIMPLE_ROOT_SYSTEM_ID="http://componentcorp.com/schema/jxvc/test/simpleRootSchema.xsd"; public static final String SIMPLE_ROOT_LOCATION="/schema/simpleRootSchema.xsd"; private static final Map<String,String> RESOURCE_LOCATIONS=new HashMap<String, String>(); static{ RESOURCE_LOCATIONS.put(SIMPLE_ROOT_SYSTEM_ID, SIMPLE_ROOT_LOCATION); } private Map<String,Boolean> setFeatureMap; private Map<String,Object> setPropertyMap; private String languageOrSchema; @Before public void setup(){ languageOrSchema=null; setFeatureMap=null; setPropertyMap=null; } public SubordinateFeaturesAndPropertyTest() { } @Test public void testSettingValidSubordinateFeatureForXSDLanguage(){ try{ languageOrSchema = XMLConstants.W3C_XML_SCHEMA_NS_URI; setFeatureMap = new HashMap<String, Boolean>(); setFeatureMap.put(XMLConstants.FEATURE_SECURE_PROCESSING,false); Collection<SAXParseException> faults=performSAXValidatorHandlerTest("/xml-model/simpleRoot.xml"); assertEquals("Should have been no validation errors",0,faults.size()); } catch (SAXException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } } @Test public void testSettingInvalidSubordinatePropertyForXSDLanguage(){ try{ languageOrSchema = XMLConstants.W3C_XML_SCHEMA_NS_URI; setPropertyMap = new HashMap<String, Object>(); setPropertyMap.put(ValidationConstants.SUBORDINATE_PROPERTY_PHASE_PROPERTY_NAME, "phase"); Collection<SAXParseException> faults=performSAXValidatorHandlerTest("/xml-model/simpleRoot.xml", new SAXCallback()); assertEquals("Should have been no validation errors",0,faults.size()); } catch (SAXNotSupportedException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } catch (SAXNotRecognizedException ex) { //should throw this exception } catch(SAXException ex){ ex.printStackTrace(); fail("Should not have thrown an exception"); } } @Test public void testSettingValidSubordinateFeatureForSchema(){ try{ languageOrSchema=SIMPLE_ROOT_SYSTEM_ID; setFeatureMap = new HashMap<String, Boolean>(); setFeatureMap.put(XMLConstants.FEATURE_SECURE_PROCESSING,false); Collection<SAXParseException> faults=performSAXValidatorHandlerTest("/xml-model/simpleRoot.xml", new SAXCallback()); assertEquals("Should have been no validation errors",0,faults.size()); } catch (SAXException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } } @Test public void testSettingInvalidSubordinatePropertyForSchema(){ try{ languageOrSchema=SIMPLE_ROOT_SYSTEM_ID; setPropertyMap = new HashMap<String, Object>(); setPropertyMap.put(ValidationConstants.SUBORDINATE_PROPERTY_PHASE_PROPERTY_NAME, "phase"); Collection<SAXParseException> faults=performSAXValidatorHandlerTest("/xml-model/simpleRoot.xml", new SAXCallback()); assertEquals("Should have been no validation errors",0,faults.size()); } catch (SAXNotSupportedException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } catch (SAXNotRecognizedException ex) { //should throw this exception } catch(SAXException ex){ ex.printStackTrace(); fail("Should not have thrown an exception"); } } @Test public void testSettingValidSubordinateFeatureUsingValidator(){ try{ languageOrSchema=XMLConstants.W3C_XML_SCHEMA_NS_URI; setFeatureMap = new HashMap<String, Boolean>(); setFeatureMap.put(XMLConstants.FEATURE_SECURE_PROCESSING,false); Collection<SAXParseException> faults=performSAXValidatorTest("/xml-model/simpleRoot.xml",new ValidatorCallback()); assertEquals("Should have been no validation errors",0,faults.size()); } catch (SAXException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } } @Test public void testSettingInvalidSubordinateUsingValidator(){ try{ languageOrSchema=XMLConstants.W3C_XML_SCHEMA_NS_URI; setPropertyMap = new HashMap<String, Object>(); setPropertyMap.put(ValidationConstants.SUBORDINATE_PROPERTY_PHASE_PROPERTY_NAME, "phase"); Collection<SAXParseException> faults=performSAXValidatorTest("/xml-model/simpleRoot.xml",new ValidatorCallback()); assertEquals("Should have been no validation errors",0,faults.size()); } catch (SAXNotSupportedException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } catch (SAXNotRecognizedException ex) { //should throw this exception } catch(SAXException ex){ ex.printStackTrace(); fail("Should not have thrown an exception"); } } @Override protected Map<String, String> getResourceMap() { return RESOURCE_LOCATIONS; } protected void featureSetupCallback(FeaturePropertyProvider featuresAndProperties) { try { Map<String,FeaturePropertyProvider> subordinateFeaturesMap = (Map<String,FeaturePropertyProvider>) featuresAndProperties.getProperty(ValidationConstants.PROPERTY_SUBORDINATE_FEATURES_AND_PROPERTIES); FeaturePropertyProvider xsdHandler = subordinateFeaturesMap.get(languageOrSchema); if (setFeatureMap!=null){ for (Map.Entry<String,Boolean> featureEntry:setFeatureMap.entrySet()){ xsdHandler.setFeature(featureEntry.getKey(), featureEntry.getValue()); } } if (setPropertyMap!=null){ for(Map.Entry<String,Object> propertyEntry: setPropertyMap.entrySet()){ xsdHandler.setProperty(propertyEntry.getKey(), propertyEntry.getValue()); } } } catch (SAXNotRecognizedException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } catch (SAXNotSupportedException ex) { ex.printStackTrace(); fail("Should not have thrown an exception"); } } private class SAXCallback implements SAXValidatorHandlerPreExecutionCallback{ @Override public void preExecute(SAXParser parser, FeaturePropertyProvider validatorHandlerFAndP) { featureSetupCallback(validatorHandlerFAndP); } } private class ValidatorCallback implements ValidatorPreExecutionCallback{ @Override public void preExecute(Validator validator,FeaturePropertyProvider fAndP) { featureSetupCallback(fAndP); } } }
apache-2.0
zhihaoSong/mybatis-test
src/main/java/com/szh/po/Sex.java
965
package com.szh.po; /** * Created by zhihaosong on 17-1-11. */ public enum Sex { MALE(1, "男"), FEMALE(2, "女"); private int id; private String name; Sex(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static Sex getSex(int id) { switch (id) { case 1: return MALE; case 2: return FEMALE; } return null; } @Override public String toString() { return "Sex{" + "id=" + id + ", name='" + name + '\'' + '}'; } public static void main(String[] args) { System.out.println(Sex.getSex(3)); } }
apache-2.0
consulo/consulo-dotnet
dotnet-impl/src/main/java/consulo/dotnet/module/DotNetContentFolderSupportPatcher.java
1432
/* * Copyright 2013-2014 must-be.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.dotnet.module; import java.util.Set; import javax.annotation.Nonnull; import consulo.dotnet.module.extension.DotNetModuleExtension; import com.intellij.openapi.roots.ModifiableRootModel; import consulo.roots.ContentFolderSupportPatcher; import consulo.roots.ContentFolderTypeProvider; import consulo.roots.impl.ProductionContentFolderTypeProvider; /** * @author VISTALL * @since 31.03.14 */ public class DotNetContentFolderSupportPatcher implements ContentFolderSupportPatcher { @Override public void patch(@Nonnull ModifiableRootModel model, @Nonnull Set<ContentFolderTypeProvider> set) { DotNetModuleExtension extension = model.getExtension(DotNetModuleExtension.class); if(extension != null && extension.isAllowSourceRoots()) { set.add(ProductionContentFolderTypeProvider.getInstance()); } } }
apache-2.0
postamar/anoa
library/core/src/main/java/com/adgear/anoa/read/RecordWrapper.java
142
package com.adgear.anoa.read; interface RecordWrapper<R, W extends FieldWrapper> { R get(); void put(W fieldWrapper, Object value); }
apache-2.0
sabi0/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
104620
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.navigation.NavigationUtil; import com.intellij.execution.Executor; import com.intellij.execution.ExecutorRegistry; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.RunnerRegistry; import com.intellij.execution.actions.ChooseRunConfigurationPopup; import com.intellij.execution.actions.ExecutorProvider; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.impl.RunDialog; import com.intellij.execution.runners.ProgramRunner; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.icons.AllIcons; import com.intellij.ide.*; import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManager; import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl; import com.intellij.ide.structureView.StructureView; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.StructureViewTreeElement; import com.intellij.ide.ui.OptionsTopHitProvider; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.laf.darcula.ui.DarculaTextBorder; import com.intellij.ide.ui.laf.darcula.ui.DarculaTextFieldUI; import com.intellij.ide.ui.laf.intellij.MacIntelliJTextBorder; import com.intellij.ide.ui.laf.intellij.MacIntelliJTextFieldUI; import com.intellij.ide.ui.search.BooleanOptionDescription; import com.intellij.ide.ui.search.OptionDescription; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.gotoByName.*; import com.intellij.ide.util.treeView.smartTree.TreeElement; import com.intellij.lang.Language; import com.intellij.lang.LanguagePsiElementExternalizer; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.NavigationItem; import com.intellij.navigation.PsiElementNavigationItem; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actions.TextComponentEditorAction; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.impl.EditorHistoryManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.keymap.MacKeymapUtil; import com.intellij.openapi.keymap.impl.ModifierKeyDoubleClickHandler; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.ComponentPopupBuilder; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFilePathWrapper; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.pom.Navigatable; import com.intellij.psi.*; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBList; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.OnOffButton; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.popup.AbstractPopup; import com.intellij.ui.popup.PopupPositionManager; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.Matcher; import com.intellij.util.text.MatcherHolder; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.StatusText; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import java.util.Vector; import java.util.concurrent.atomic.AtomicBoolean; import static com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts; import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance; /** * @author Konstantin Bulenkov */ @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware, DataProvider, RightAlignedToolbarAction { public static final String SE_HISTORY_KEY = "SearchEverywhereHistoryKey"; public static final int SEARCH_FIELD_COLUMNS = 25; private static final int MAX_CLASSES = 6; private static final int MAX_FILES = 6; private static final int MAX_RUN_CONFIGURATION = 6; private static final int MAX_TOOL_WINDOWS = 4; private static final int MAX_SYMBOLS = 6; private static final int MAX_SETTINGS = 5; private static final int MAX_ACTIONS = 5; private static final int MAX_RECENT_FILES = 10; private static final int DEFAULT_MORE_STEP_COUNT = 15; public static final int MAX_SEARCH_EVERYWHERE_HISTORY = 50; public static final int MAX_TOP_HIT = 15; private static final Logger LOG = Logger.getInstance(SearchEverywhereAction.class); private static final Border RENDERER_BORDER = JBUI.Borders.empty(1, 0); private static final Border RENDERER_TITLE_BORDER = JBUI.Borders.emptyTop(3); private SearchEverywhereAction.MyListRenderer myRenderer; MySearchTextField myPopupField; private volatile GotoClassModel2 myClassModel; private volatile GotoFileModel myFileModel; private volatile GotoActionItemProvider myActionProvider; private volatile GotoSymbolModel2 mySymbolsModel; private Component myFocusComponent; private JBPopup myPopup; private final Map<String, String> myConfigurables = new HashMap<>(); private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, ApplicationManager.getApplication()); private JBList<Object> myList; private JCheckBox myNonProjectCheckBox; private AnActionEvent myActionEvent; private final Set<AnAction> myDisabledActions = new HashSet<>(); private Component myContextComponent; private CalcThread myCalcThread; private static final AtomicBoolean ourShiftIsPressed = new AtomicBoolean(false); private static final AtomicBoolean showAll = new AtomicBoolean(false); private volatile ActionCallback myCurrentWorker = ActionCallback.DONE; private int myCalcThreadRestartRequestId = 0; private final Object myWorkerRestartRequestLock = new Object(); private int myHistoryIndex = 0; boolean mySkipFocusGain = false; public static final Key<JBPopup> SEARCH_EVERYWHERE_POPUP = new Key<>("SearchEverywherePopup"); static { ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_SEARCH_EVERYWHERE, KeyEvent.VK_SHIFT, -1, false); IdeEventQueue.getInstance().addPostprocessor(event -> { if (event instanceof KeyEvent) { final int keyCode = ((KeyEvent)event).getKeyCode(); if (keyCode == KeyEvent.VK_SHIFT) { ourShiftIsPressed.set(event.getID() == KeyEvent.KEY_PRESSED); } } return false; }, null); } private volatile JBPopup myBalloon; private int myPopupActualWidth; private Component myFocusOwner; private ChooseByNamePopup myFileChooseByName; private ChooseByNamePopup myClassChooseByName; private ChooseByNamePopup mySymbolsChooseByName; private StructureViewModel myStructureModel; private Editor myEditor; private FileEditor myFileEditor; private HistoryItem myHistoryItem; @Override public JComponent createCustomComponent(Presentation presentation) { return new ActionButton(this, presentation, ActionPlaces.NAVIGATION_BAR_TOOLBAR, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { @Override protected void updateToolTipText() { String shortcutText = getShortcut(); if (Registry.is("ide.helptooltip.enabled")) { HelpTooltip.dispose(this); new HelpTooltip() .setTitle(myPresentation.getText()) .setShortcut(shortcutText) .setDescription("Searches for:<br/> - Classes<br/> - Files<br/> - Tool Windows<br/> - Actions<br/> - Settings") .setLocation(getTooltipLocation()).installOn(this); } else { setToolTipText("<html><body>Search Everywhere<br/>Press <b>" + shortcutText + "</b> to access<br/> - Classes<br/> - Files<br/> - Tool Windows<br/> - Actions<br/> - Settings</body></html>"); } } }; } private void updateComponents() { myList = new JBList<Object>(new SearchListModel()) { int lastKnownHeight = JBUI.scale(30); @Override public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); if (size.height == -1) { size.height = lastKnownHeight; } else { lastKnownHeight = size.height; } int width = myBalloon != null ? myBalloon.getSize().width : 0; return new Dimension(Math.max(width, Math.min(size.width - 2, getPopupMaxWidth())), myList.isEmpty() ? JBUI.scale(30) : size.height); } @Override public void clearSelection() { //avoid blinking } @Override public Object getSelectedValue() { try { return super.getSelectedValue(); } catch (Exception e) { return null; } } }; myRenderer = new MyListRenderer(myList); myList.setCellRenderer(myRenderer); myList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { e.consume(); final int i = myList.locationToIndex(e.getPoint()); if (i != -1) { mySkipFocusGain = true; getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(getField(), true)); ApplicationManager.getApplication().invokeLater(() -> { myList.setSelectedIndex(i); doNavigate(i); }); } } }); myNonProjectCheckBox = new JCheckBox(); myNonProjectCheckBox.setOpaque(false); myNonProjectCheckBox.setAlignmentX(1.0f); myNonProjectCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (showAll.get() != myNonProjectCheckBox.isSelected()) { showAll.set(!showAll.get()); final JTextField editor = UIUtil.findComponentOfType(myBalloon.getContent(), JTextField.class); if (editor != null) { final String pattern = editor.getText(); myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { if (editor.hasFocus()) { rebuildList(pattern); } }, 30); } } } }); } @Nullable @Override public Object getData(@NonNls String dataId) { return null; } private static String getShortcut() { Shortcut[] shortcuts = getActiveKeymapShortcuts(IdeActions.ACTION_SEARCH_EVERYWHERE).getShortcuts(); if (shortcuts.length == 0) { return "Double" + (SystemInfo.isMac ? FontUtil.thinSpace() + MacKeymapUtil.SHIFT : " Shift"); } return KeymapUtil.getShortcutsText(shortcuts); } private void initSearchField(final MySearchTextField search) { final JTextField editor = search.getTextEditor(); // onFocusLost(); editor.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { final String pattern = editor.getText(); if (editor.hasFocus()) { rebuildList(pattern); } } }); editor.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { if (mySkipFocusGain) { mySkipFocusGain = false; return; } String text = GotoActionBase.getInitialTextForNavigation(myEditor); text = text != null ? text.trim() : ""; search.setText(text); search.getTextEditor().setForeground(UIUtil.getLabelForeground()); search.selectText(); //titleIndex = new TitleIndexes(); editor.setColumns(SEARCH_FIELD_COLUMNS); myFocusComponent = e.getOppositeComponent(); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { final JComponent parent = (JComponent)editor.getParent(); parent.revalidate(); parent.repaint(); }); //if (myPopup != null && myPopup.isVisible()) { // myPopup.cancel(); // myPopup = null; //} rebuildList(text); } @Override public void focusLost(FocusEvent e) { if ( myPopup instanceof AbstractPopup && myPopup.isVisible() && ((myList == e.getOppositeComponent()) || ((AbstractPopup)myPopup).getPopupWindow() == e.getOppositeComponent())) { return; } if (myNonProjectCheckBox == e.getOppositeComponent()) { mySkipFocusGain = true; getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(editor, true)); return; } if (UIUtil.haveCommonOwner(e.getComponent(), e.getOppositeComponent())) { return; } onFocusLost(); } }); } private void jumpNextGroup(boolean forward) { final int index = myList.getSelectedIndex(); final SearchListModel model = getModel(); if (index >= 0) { final int newIndex = forward ? model.next(index) : model.prev(index); myList.setSelectedIndex(newIndex); int more = model.next(newIndex) - 1; if (more < newIndex) { more = myList.getItemsCount() - 1; } ScrollingUtil.ensureIndexIsVisible(myList, more, forward ? 1 : -1); ScrollingUtil.ensureIndexIsVisible(myList, newIndex, forward ? 1 : -1); } } private SearchListModel getModel() { return (SearchListModel)myList.getModel(); } private ActionCallback onFocusLost() { final ActionCallback result = new ActionCallback(); //noinspection SSBasedInspection UIUtil.invokeLaterIfNeeded(() -> { try { if (myCalcThread != null) { myCalcThread.cancel(); //myCalcThread = null; } myAlarm.cancelAllRequests(); if (myBalloon != null && !myBalloon.isDisposed() && myPopup != null && !myPopup.isDisposed()) { myBalloon.cancel(); myPopup.cancel(); } //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> ActionToolbarImpl.updateAllToolbarsImmediately()); } finally { result.setDone(); } }); return result; } private SearchTextField getField() { return myPopupField; } private void doNavigate(final int index) { final DataManager dataManager = DataManager.getInstance(); if (dataManager == null) return; final Project project = CommonDataKeys.PROJECT.getData(dataManager.getDataContext(getField().getTextEditor())); assert project != null; final SearchListModel model = getModel(); if (isMoreItem(index)) { final String pattern = myPopupField.getText(); WidgetID wid = null; if (index == model.moreIndex.classes) wid = WidgetID.CLASSES; else if (index == model.moreIndex.files) wid = WidgetID.FILES; else if (index == model.moreIndex.settings) wid = WidgetID.SETTINGS; else if (index == model.moreIndex.actions) wid = WidgetID.ACTIONS; else if (index == model.moreIndex.symbols) wid = WidgetID.SYMBOLS; else if (index == model.moreIndex.runConfigurations) wid = WidgetID.RUN_CONFIGURATIONS; if (wid != null) { final WidgetID widgetID = wid; synchronized (myWorkerRestartRequestLock) { // this lock together with RestartRequestId should be enough to prevent two CalcThreads running at the same time final int currentRestartRequest = ++myCalcThreadRestartRequestId; myCurrentWorker.doWhenProcessed(() -> { synchronized (myWorkerRestartRequestLock) { if (currentRestartRequest != myCalcThreadRestartRequestId) { return; } myCalcThread = new CalcThread(project, pattern, true); myPopupActualWidth = 0; myCurrentWorker = myCalcThread.insert(index, widgetID); } }); } return; } } final String pattern = getField().getText(); final Object value = myList.getSelectedValue(); saveHistory(project, pattern, value); IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(getField().getTextEditor()); if (myPopup != null && myPopup.isVisible()) { myPopup.cancel(); } if (value instanceof BooleanOptionDescription) { final BooleanOptionDescription option = (BooleanOptionDescription)value; option.setOptionState(!option.isOptionEnabled()); myList.revalidate(); myList.repaint(); getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(getField(), true)); return; } if (value instanceof OptionsTopHitProvider) { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> getField().setText("#" + ((OptionsTopHitProvider)value).getId() + " ")); return; } Runnable onDone = ReadAction.compute(() -> { if (value instanceof PsiElement) { return () -> NavigationUtil.activateFileWithPsiElement((PsiElement)value, true); } else if (isVirtualFile(value)) { return () -> OpenSourceUtil.navigate(true, new OpenFileDescriptor(project, (VirtualFile)value)); } else if (isActionValue(value) || isSetting(value) || isRunConfiguration(value)) { focusManager.requestDefaultFocus(true); final Component comp = myContextComponent; IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> { Component c = comp; if (c == null) { c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); } if (isRunConfiguration(value)) { ChooseRunConfigurationPopup.ItemWrapper itemWrapper = (ChooseRunConfigurationPopup.ItemWrapper)value; RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(itemWrapper.getValue(), RunnerAndConfigurationSettings.class); if (settings != null) { Executor executor = findExecutor(settings); if (executor != null) { itemWrapper.perform(project, executor, dataManager.getDataContext(c)); } } } else { GotoActionAction.openOptionOrPerformAction(value, pattern, project, c); } }); return ()->{}; } else if (value instanceof Navigatable) { return () -> OpenSourceUtil.navigate(true, (Navigatable)value); } return null; }); final ActionCallback callback = onFocusLost(); if (onDone != null) { callback.doWhenDone(onDone); return; } focusManager.requestDefaultFocus(true); } private boolean isMoreItem(int index) { final SearchListModel model = getModel(); return index == model.moreIndex.classes || index == model.moreIndex.files || index == model.moreIndex.settings || index == model.moreIndex.actions || index == model.moreIndex.symbols || index == model.moreIndex.runConfigurations; } private void rebuildList(final String pattern) { assert EventQueue.isDispatchThread() : "Must be EDT"; if (myCalcThread != null && !myCurrentWorker.isProcessed()) { myCurrentWorker = myCalcThread.cancel(); } if (myCalcThread != null && !myCalcThread.isCanceled()) { myCalcThread.cancel(); } final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(getField().getTextEditor())); assert project != null; myRenderer.myProject = project; synchronized (myWorkerRestartRequestLock) { // this lock together with RestartRequestId should be enough to prevent two CalcThreads running at the same time final int currentRestartRequest = ++myCalcThreadRestartRequestId; myCurrentWorker.doWhenProcessed(() -> { synchronized (myWorkerRestartRequestLock) { if (currentRestartRequest != myCalcThreadRestartRequestId) { return; } myCalcThread = new CalcThread(project, pattern, false); myPopupActualWidth = 0; myCurrentWorker = myCalcThread.start(); } }); } } @Override public void actionPerformed(AnActionEvent e) { if (Registry.is("ide.suppress.double.click.handler") && e.getInputEvent() instanceof KeyEvent) { if (((KeyEvent)e.getInputEvent()).getKeyCode() == KeyEvent.VK_SHIFT) { return; } } actionPerformed(e, null); } public void actionPerformed(AnActionEvent e, MouseEvent me) { if (Registry.is("new.search.everywhere") && e.getProject() != null) { //todo[mikhail.sokolov] show new UI String searchProviderID = SearchEverywhereManagerImpl.ALL_CONTRIBUTORS_GROUP_ID; FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE); FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE + "." + searchProviderID); SearchEverywhereManager seManager = SearchEverywhereManager.getInstance(e.getProject()); if (seManager.isShown()) { if (searchProviderID.equals(seManager.getShownContributorID())) { seManager.setShowNonProjectItems(!seManager.isShowNonProjectItems()); } else { seManager.setShownContributor(searchProviderID); } return; } IdeEventQueue.getInstance().getPopupManager().closeAllPopups(false); String text = GotoActionBase.getInitialTextForNavigation(e.getData(CommonDataKeys.EDITOR)); seManager.show(searchProviderID, text, e); return; } if (myBalloon != null && myBalloon.isVisible()) { showAll.set(!showAll.get()); myNonProjectCheckBox.setSelected(showAll.get()); // myPopupField.getTextEditor().setBackground(showAll.get() ? new JBColor(new Color(0xffffe4), new Color(0x494539)) : UIUtil.getTextFieldBackground()); rebuildList(myPopupField.getText()); return; } myCurrentWorker = ActionCallback.DONE; if (e != null) { myEditor = e.getData(CommonDataKeys.EDITOR); myFileEditor = e.getData(PlatformDataKeys.FILE_EDITOR); } if (e == null && myFocusOwner != null) { e = AnActionEvent.createFromAnAction(this, me, ActionPlaces.UNKNOWN, DataManager.getInstance().getDataContext(myFocusOwner)); } if (e == null) return; final Project project = e.getProject(); if (project == null) return; //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> LookupManager.getInstance(project).hideActiveLookup()); updateComponents(); myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext()); Window wnd = myContextComponent != null ? SwingUtilities.windowForComponent(myContextComponent) : KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); if (wnd == null && myContextComponent instanceof Window) { wnd = (Window)myContextComponent; } if (wnd == null || wnd.getParent() != null) return; myActionEvent = e; if (myPopupField != null) { Disposer.dispose(myPopupField); } myPopupField = new MySearchTextField(); //UIUtil.typeAheadUntilFocused(e.getInputEvent(), myPopupField.getTextEditor()); myPopupField.getTextEditor().addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { myHistoryIndex = 0; myHistoryItem = null; } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT) { myList.repaint(); } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT) { myList.repaint(); } } }); initSearchField(myPopupField); myPopupField.setOpaque(false); JTextField editor = myPopupField.getTextEditor(); editor.setColumns(SEARCH_FIELD_COLUMNS); JPanel panel = UIUtil.isUnderWin10LookAndFeel() ? new JPanel(new BorderLayout()) { @Override protected void paintComponent(Graphics g) { g.setColor(UIManager.getColor("SearchEverywhere.background")); g.fillRect(0, 0, getWidth(), getHeight()); } } : new JPanel(new BorderLayout()) { @Override protected void paintComponent(Graphics g) { Gradient gradient = new Gradient(new JBColor(0x6593f2, 0x40505e), new JBColor(0x2e6fcd, 0x354157)); ((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor())); g.fillRect(0, 0, getWidth(), getHeight()); } }; JLabel title = new JLabel(" Search Everywhere: "); JPanel topPanel = new NonOpaquePanel(new BorderLayout()); Color foregroundColor = UIUtil.isUnderWin10LookAndFeel() ? UIManager.getColor("SearchEverywhere.foreground") : new JBColor(Gray._240, Gray._200); title.setForeground(foregroundColor); if (SystemInfo.isMac) { title.setFont(title.getFont().deriveFont(Font.BOLD, title.getFont().getSize() - 1f)); } else { title.setFont(title.getFont().deriveFont(Font.BOLD)); } topPanel.add(title, BorderLayout.WEST); JPanel controls = new JPanel(new BorderLayout()); controls.setOpaque(false); JLabel settings = new JLabel(AllIcons.General.SearchEverywhereGear); new ClickListener(){ @Override public boolean onClick(@NotNull MouseEvent event, int clickCount) { showSettings(); return true; } }.installOn(settings); settings.setBorder(UIUtil.isUnderWin10LookAndFeel() ? JBUI.Borders.emptyLeft(6) : JBUI.Borders.empty()); controls.add(settings, BorderLayout.EAST); if (!NonProjectScopeDisablerEP.isSearchInNonProjectDisabled()) { myNonProjectCheckBox.setForeground(foregroundColor); Color shortcutColor = UIUtil.isUnderWin10LookAndFeel() ? UIManager.getColor("SearchEverywhere.shortcutForeground") : foregroundColor; StringBuilder cbText = new StringBuilder("<html>"); cbText.append(IdeBundle.message("checkbox.include.non.project.items", IdeUICustomization.getInstance().getProjectConceptName())); cbText.append(" "); if (!UIUtil.isUnderWin10LookAndFeel()) cbText.append("<b>"); cbText.append("<font color=#").append(ColorUtil.toHex(shortcutColor)).append(">").append(getShortcut()).append("</font>"); if (!UIUtil.isUnderWin10LookAndFeel()) cbText.append("</b>"); cbText.append("</html>"); myNonProjectCheckBox.setText(cbText.toString()); controls.add(myNonProjectCheckBox, BorderLayout.WEST); } controls.setBorder(UIUtil.isUnderWin10LookAndFeel() ? JBUI.Borders.emptyTop(1) : JBUI.Borders.empty()); topPanel.add(controls, BorderLayout.EAST); panel.add(myPopupField, BorderLayout.CENTER); panel.add(topPanel, BorderLayout.NORTH); panel.setBorder(JBUI.Borders.empty(3, 5, 4, 5)); DataManager.registerDataProvider(panel, this); final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor); myBalloon = builder .setCancelOnClickOutside(true) .setModalContext(false) .setRequestFocus(true) .createPopup(); myBalloon.getContent().setBorder(JBUI.Borders.empty()); project.getMessageBus().connect(myBalloon).subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() { @Override public void exitDumbMode() { ApplicationManager.getApplication().invokeLater(() -> rebuildList(myPopupField.getText())); } }); registerDataProvider(panel, project); final RelativePoint showPoint = calculateShowingPoint(e, panel); myList.setFont(UIUtil.getListFont()); myBalloon.show(showPoint); initSearchActions(myBalloon, myPopupField); IdeFocusManager focusManager = IdeFocusManager.getInstance(project); focusManager.requestFocus(editor, true); FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE); } @NotNull private static RelativePoint calculateShowingPoint(AnActionEvent e, JComponent showingContent) { Project project = e.getProject(); final Window window = project != null ? WindowManager.getInstance().suggestParentWindow(project) : KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); Component parent = UIUtil.findUltimateParent(window); final RelativePoint showPoint; if (parent != null) { int height = UISettings.getInstance().getShowMainToolbar() ? 135 : 115; if (parent instanceof IdeFrameImpl && ((IdeFrameImpl)parent).isInFullScreen()) { height -= 20; } showPoint = new RelativePoint(parent, new Point((parent.getSize().width - showingContent.getPreferredSize().width) / 2, height)); } else { showPoint = JBPopupFactory.getInstance().guessBestPopupLocation(e.getDataContext()); } return showPoint; } private void showSettings() { myPopupField.setText(""); final SearchListModel model = new SearchListModel(); //model.addElement(new SEOption("Show current file structure elements", "search.everywhere.structure")); model.addElement(new SEOption("Show files", "search.everywhere.files")); model.addElement(new SEOption("Show symbols", "search.everywhere.symbols")); model.addElement(new SEOption("Show tool windows", "search.everywhere.toolwindows")); model.addElement(new SEOption("Show run configurations", "search.everywhere.configurations")); model.addElement(new SEOption("Show actions", "search.everywhere.actions")); model.addElement(new SEOption("Show IDE settings", "search.everywhere.settings")); if (myCalcThread != null && !myCurrentWorker.isProcessed()) { myCurrentWorker = myCalcThread.cancel(); } if (myCalcThread != null && !myCalcThread.isCanceled()) { myCalcThread.cancel(); } myCurrentWorker.doWhenProcessed(() -> { myList.setModel(model); updatePopupBounds(); }); } static class SEOption extends BooleanOptionDescription { private final String myKey; public SEOption(String option, String registryKey) { super(option, null); myKey = registryKey; } @Override public boolean isOptionEnabled() { return Registry.is(myKey); } @Override public void setOptionState(boolean enabled) { Registry.get(myKey).setValue(enabled); } } private static void saveHistory(Project project, String text, Object value) { if (project == null || project.isDisposed() || !project.isInitialized()) { return; } HistoryType type = null; String fqn = null; if (isActionValue(value)) { type = HistoryType.ACTION; AnAction action = (AnAction)(value instanceof GotoActionModel.ActionWrapper ? ((GotoActionModel.ActionWrapper)value).getAction() : value); fqn = ActionManager.getInstance().getId(action); } else if (value instanceof VirtualFile) { type = HistoryType.FILE; fqn = ((VirtualFile)value).getUrl(); } else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) { type = HistoryType.RUN_CONFIGURATION; fqn = ((ChooseRunConfigurationPopup.ItemWrapper)value).getText(); } else if (value instanceof PsiElement) { final PsiElement psiElement = (PsiElement)value; final Language language = psiElement.getLanguage(); final String name = LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).getQualifiedName(psiElement); if (name != null) { type = HistoryType.PSI; fqn = language.getID() + "://" + name; } } final PropertiesComponent storage = PropertiesComponent.getInstance(project); final String[] values = storage.getValues(SE_HISTORY_KEY); List<HistoryItem> history = new ArrayList<>(); if (values != null) { for (String s : values) { final String[] split = s.split("\t"); if (split.length != 3 || text.equals(split[0])) { continue; } if (!StringUtil.isEmpty(split[0])) { history.add(new HistoryItem(split[0], split[1], split[2])); } } } history.add(0, new HistoryItem(text, type == null ? null : type.name(), fqn)); if (history.size() > MAX_SEARCH_EVERYWHERE_HISTORY) { history = history.subList(0, MAX_SEARCH_EVERYWHERE_HISTORY); } final String[] newValues = new String[history.size()]; for (int i = 0; i < newValues.length; i++) { newValues[i] = history.get(i).toString(); } storage.setValues(SE_HISTORY_KEY, newValues); } @Nullable public Executor findExecutor(@NotNull RunnerAndConfigurationSettings settings) { final Executor runExecutor = DefaultRunExecutor.getRunExecutorInstance(); final Executor debugExecutor = ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG); Executor executor = ourShiftIsPressed.get() ? runExecutor : debugExecutor; RunConfiguration runConf = settings.getConfiguration(); if (executor == null) return null; ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), runConf); if (runner == null) { executor = runExecutor == executor ? debugExecutor : runExecutor; } return executor; } private void registerDataProvider(JPanel panel, final Project project) { DataManager.registerDataProvider(panel, new DataProvider() { @Nullable @Override public Object getData(@NonNls String dataId) { final Object value = myList.getSelectedValue(); if (CommonDataKeys.PSI_ELEMENT.is(dataId) && value instanceof PsiElement) { return value; } if (CommonDataKeys.VIRTUAL_FILE.is(dataId) && value instanceof VirtualFile) { return value; } if (CommonDataKeys.NAVIGATABLE.is(dataId)) { if (value instanceof Navigatable) return value; if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) { final Object config = ((ChooseRunConfigurationPopup.ItemWrapper)value).getValue(); if (config instanceof RunnerAndConfigurationSettings) { return new Navigatable() { @Override public void navigate(boolean requestFocus) { Executor executor = findExecutor((RunnerAndConfigurationSettings)config); RunDialog.editConfiguration(project, (RunnerAndConfigurationSettings)config, "Edit Configuration", executor); } @Override public boolean canNavigate() { return true; } @Override public boolean canNavigateToSource() { return true; } }; } } } if (PlatformDataKeys.SEARCH_INPUT_TEXT.is(dataId)) { return myPopupField == null ? null : myPopupField.getText(); } return null; } }); } private void initSearchActions(JBPopup balloon, MySearchTextField searchTextField) { final JTextField editor = searchTextField.getTextEditor(); DumbAwareAction.create(e -> jumpNextGroup(true)) .registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), editor, balloon); DumbAwareAction.create(e -> jumpNextGroup(false)) .registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), editor, balloon); AnAction escape = ActionManager.getInstance().getAction("EditorEscape"); DumbAwareAction.create(e -> { if (myBalloon != null && myBalloon.isVisible()) { myBalloon.cancel(); } if (myPopup != null && myPopup.isVisible()) { myPopup.cancel(); } }).registerCustomShortcutSet(escape == null ? CommonShortcuts.ESCAPE : escape.getShortcutSet(), editor, balloon); DumbAwareAction.create(e -> { int index = myList.getSelectedIndex(); if (index != -1) { doNavigate(index); } }).registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER", "shift ENTER"), editor, balloon); new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final PropertiesComponent storage = PropertiesComponent.getInstance(e.getProject()); final String[] values = storage.getValues(SE_HISTORY_KEY); if (values != null) { if (values.length > myHistoryIndex) { final List<String> data = StringUtil.split(values[myHistoryIndex], "\t"); myHistoryItem = new HistoryItem(data.get(0), data.get(1), data.get(2)); myHistoryIndex++; editor.setText(myHistoryItem.pattern); editor.setCaretPosition(myHistoryItem.pattern.length()); editor.moveCaretPosition(0); } } } @Override public void update(AnActionEvent e) { e.getPresentation().setEnabled(editor.getCaretPosition() == 0); } }.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), editor, balloon); } private static class MySearchTextField extends SearchTextField implements DataProvider, Disposable { public MySearchTextField() { super(false, "SearchEveryWhereHistory"); JTextField editor = getTextEditor(); editor.setOpaque(false); if (UIUtil.isUnderDefaultMacTheme()) { editor.setUI((MacIntelliJTextFieldUI)MacIntelliJTextFieldUI.createUI(editor)); editor.setBorder(new MacIntelliJTextBorder()); } else if (!UIUtil.isUnderWin10LookAndFeel()){ editor.setUI((DarculaTextFieldUI)DarculaTextFieldUI.createUI(editor)); editor.setBorder(new DarculaTextBorder()); } editor.putClientProperty("JTextField.Search.noBorderRing", Boolean.TRUE); if (UIUtil.isUnderDarcula()) { editor.setBackground(Gray._45); editor.setForeground(Gray._240); } } @Override protected boolean isSearchControlUISupported() { return true; } @Override protected boolean hasIconsOutsideOfTextField() { return false; } @Override protected void showPopup() { } @Nullable @Override public Object getData(@NonNls String dataId) { if (PlatformDataKeys.PREDEFINED_TEXT.is(dataId)) { return getTextEditor().getText(); } return null; } @Override public void dispose() { } } private class MyListRenderer extends ColoredListCellRenderer<Object> { ColoredListCellRenderer myLocation = new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) { setPaintFocusBorder(false); append(myLocationString, SimpleTextAttributes.GRAYED_ATTRIBUTES); setIcon(myLocationIcon); } }; SearchEverywherePsiRenderer myFileRenderer = new SearchEverywherePsiRenderer(myList); @SuppressWarnings("unchecked") ListCellRenderer myActionsRenderer = new GotoActionModel.GotoActionListCellRenderer(Function.TO_STRING); private String myLocationString; private Icon myLocationIcon; private Project myProject; private final MyAccessibleComponent myMainPanel = new MyAccessibleComponent(new BorderLayout()); private final JLabel myTitle = new JLabel(); MyListRenderer(@NotNull JBList myList) { assert myList == SearchEverywhereAction.this.myList; } private class MyAccessibleComponent extends JPanel { private Accessible myAccessible; public MyAccessibleComponent(LayoutManager layout) { super(layout); setOpaque(false); } void setAccessible(Accessible comp) { myAccessible = comp; } @Override public AccessibleContext getAccessibleContext() { return accessibleContext = (myAccessible != null ? myAccessible.getAccessibleContext() : super.getAccessibleContext()); } } @Override public void clear() { super.clear(); myLocation.clear(); myLocationString = null; myLocationIcon = null; } public void setLocationString(String locationString) { myLocationString = locationString; } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component cmp; myLocationString = null; String pattern = "*" + myPopupField.getText(); Matcher matcher = NameUtil.buildMatcher(pattern, 0, true, true); if (isMoreItem(index)) { cmp = More.get(isSelected); } else { cmp = SearchEverywhereClassifier.EP_Manager.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } if (cmp == null) { cmp = tryFileRenderer(matcher, list, value, index, isSelected); } if (cmp == null) { if (value instanceof GotoActionModel.ActionWrapper) { cmp = myActionsRenderer.getListCellRendererComponent(list, new GotoActionModel.MatchedValue(((GotoActionModel.ActionWrapper)value), pattern), index, isSelected, isSelected); if (cmp instanceof JComponent) ((JComponent)cmp).setBorder(null); } else { cmp = super.getListCellRendererComponent(list, value, index, isSelected, isSelected); final JPanel p = new JPanel(new BorderLayout()); p.setBackground(UIUtil.getListBackground(isSelected)); p.add(cmp, BorderLayout.CENTER); cmp = p; } } if (myLocationString != null || value instanceof BooleanOptionDescription) { final JPanel panel = new JPanel(new BorderLayout()); panel.setBackground(UIUtil.getListBackground(isSelected)); panel.add(cmp, BorderLayout.CENTER); final Component rightComponent; if (value instanceof BooleanOptionDescription) { final OnOffButton button = new OnOffButton(); button.setSelected(((BooleanOptionDescription)value).isOptionEnabled()); rightComponent = button; } else { rightComponent = myLocation.getListCellRendererComponent(list, value, index, isSelected, isSelected); } panel.add(rightComponent, BorderLayout.EAST); cmp = panel; } Color bg = cmp.getBackground(); if (bg == null) { cmp.setBackground(UIUtil.getListBackground(isSelected)); bg = cmp.getBackground(); } String title = getModel().titleIndex.getTitle(index); myMainPanel.removeAll(); if (title != null) { myTitle.setText(title); myMainPanel.add(createTitle(" " + title), BorderLayout.NORTH); } JPanel wrapped = new JPanel(new BorderLayout()); wrapped.setBackground(bg); wrapped.setBorder(RENDERER_BORDER); wrapped.add(cmp, BorderLayout.CENTER); myMainPanel.add(wrapped, BorderLayout.CENTER); if (cmp instanceof Accessible) { myMainPanel.setAccessible((Accessible)cmp); } final int width = myMainPanel.getPreferredSize().width; if (width > myPopupActualWidth) { myPopupActualWidth = width; //schedulePopupUpdate(); } return myMainPanel; } @Nullable private Component tryFileRenderer(Matcher matcher, JList list, Object value, int index, boolean isSelected) { if (myProject != null && value instanceof VirtualFile) { PsiManager psiManager = PsiManager.getInstance(myProject); VirtualFile virtualFile = (VirtualFile)value; value = !virtualFile.isValid() ? virtualFile : virtualFile.isDirectory() ? psiManager.findDirectory(virtualFile) : psiManager.findFile(virtualFile); } if (value instanceof PsiElement) { MatcherHolder.associateMatcher(list, matcher); try { return myFileRenderer.getListCellRendererComponent(list, value, index, isSelected, isSelected); } finally { MatcherHolder.associateMatcher(list, null); } } return null; } @Override protected void customizeCellRenderer(@NotNull JList list, final Object value, int index, final boolean selected, boolean hasFocus) { setPaintFocusBorder(false); setIcon(EmptyIcon.ICON_16); ApplicationManager.getApplication().runReadAction(() -> { if (value instanceof PsiElement) { String name1 = myClassModel.getElementName(value); assert name1 != null; append(name1); } else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) { final ChooseRunConfigurationPopup.ItemWrapper wrapper = (ChooseRunConfigurationPopup.ItemWrapper)value; append(wrapper.getText()); setIcon(wrapper.getIcon()); RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(wrapper.getValue(), RunnerAndConfigurationSettings.class); if (settings != null) { Executor executor = findExecutor(settings); if (executor != null) { setLocationString(executor.getId()); myLocationIcon = executor.getToolWindowIcon(); } } } else if (isVirtualFile(value)) { final VirtualFile file = (VirtualFile)value; if (file instanceof VirtualFilePathWrapper) { append(((VirtualFilePathWrapper)file).getPresentablePath()); } else { append(file.getName()); } setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); } else if (isActionValue(value)) { final GotoActionModel.ActionWrapper actionWithParentGroup = value instanceof GotoActionModel.ActionWrapper ? (GotoActionModel.ActionWrapper)value : null; final AnAction anAction = actionWithParentGroup == null ? (AnAction)value : actionWithParentGroup.getAction(); final Presentation templatePresentation = anAction.getTemplatePresentation(); Icon icon = templatePresentation.getIcon(); if (anAction instanceof ActivateToolWindowAction) { final String id = ((ActivateToolWindowAction)anAction).getToolWindowId(); ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(id); if (toolWindow != null) { icon = toolWindow.getIcon(); } } append(String.valueOf(templatePresentation.getText())); if (actionWithParentGroup != null) { final String groupName = actionWithParentGroup.getGroupName(); if (!StringUtil.isEmpty(groupName)) { setLocationString(groupName); } } final String groupName = actionWithParentGroup == null ? null : actionWithParentGroup.getGroupName(); if (!StringUtil.isEmpty(groupName)) { setLocationString(groupName); } if (icon != null && icon.getIconWidth() <= 16 && icon.getIconHeight() <= 16) { setIcon(IconUtil.toSize(icon, 16, 16)); } } else if (isSetting(value)) { String text = getSettingText((OptionDescription)value); SimpleTextAttributes attrs = SimpleTextAttributes.REGULAR_ATTRIBUTES; if (value instanceof Changeable && ((Changeable)value).hasChanged()) { if (selected) { attrs = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; } else { SimpleTextAttributes base = SimpleTextAttributes.LINK_BOLD_ATTRIBUTES; attrs = base.derive(SimpleTextAttributes.STYLE_BOLD, base.getFgColor(), null, null); } } append(text, attrs); final String id = ((OptionDescription)value).getConfigurableId(); String location = myConfigurables.get(id); if (location == null) location = ((OptionDescription)value).getValue(); if (location != null) { setLocationString(location); } } else if (value instanceof OptionsTopHitProvider) { append("#" + ((OptionsTopHitProvider)value).getId()); } else { ItemPresentation presentation = null; if (value instanceof ItemPresentation) { presentation = (ItemPresentation)value; } else if (value instanceof NavigationItem) { presentation = ((NavigationItem)value).getPresentation(); } if (presentation != null) { final String text = presentation.getPresentableText(); append(text == null ? value.toString() : text); final String location = presentation.getLocationString(); if (!StringUtil.isEmpty(location)) { setLocationString(location); } Icon icon = presentation.getIcon(false); if (icon != null) setIcon(icon); } } }); } public void recalculateWidth() { ListModel model = myList.getModel(); myTitle.setIcon(EmptyIcon.ICON_16); myTitle.setFont(getTitleFont()); int index = 0; while (index < model.getSize()) { String title = getModel().titleIndex.getTitle(index); if (title != null) { myTitle.setText(title); } index++; } myTitle.setForeground(Gray._122); myTitle.setAlignmentY(BOTTOM_ALIGNMENT); } } private static String getSettingText(OptionDescription value) { String hit = value.getHit(); if (hit == null) { hit = value.getOption(); } hit = StringUtil.unescapeXml(hit); if (hit.length() > 60) { hit = hit.substring(0, 60) + "..."; } hit = hit.replace(" ", " "); //avoid extra spaces from mnemonics and xml conversion String text = hit.trim(); text = StringUtil.trimEnd(text, ":"); return text; } private static boolean isActionValue(Object o) { return o instanceof GotoActionModel.ActionWrapper || o instanceof AnAction; } private static boolean isSetting(Object o) { return o instanceof OptionDescription; } private static boolean isRunConfiguration(Object o) { return o instanceof ChooseRunConfigurationPopup.ItemWrapper; } private static boolean isVirtualFile(Object o) { return o instanceof VirtualFile; } private static Font getTitleFont() { return UIUtil.getLabelFont().deriveFont(UIUtil.getFontSize(UIUtil.FontSize.SMALL)); } enum WidgetID {CLASSES, FILES, ACTIONS, SETTINGS, SYMBOLS, RUN_CONFIGURATIONS} @SuppressWarnings({"SSBasedInspection", "unchecked", "Duplicates"}) private class CalcThread implements Runnable { private final Project project; private final String pattern; private final ProgressIndicator myProgressIndicator = new ProgressIndicatorBase(); private final ActionCallback myDone = new ActionCallback(); private final SearchListModel myListModel; private final ArrayList<VirtualFile> myAlreadyAddedFiles = new ArrayList<>(); private final ArrayList<AnAction> myAlreadyAddedActions = new ArrayList<>(); public CalcThread(Project project, String pattern, boolean reuseModel) { this.project = project; this.pattern = pattern; myListModel = reuseModel ? (SearchListModel)myList.getModel() : new SearchListModel(); } @Override public void run() { try { check(); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { // this line must be called on EDT to avoid context switch at clear().append("text") Don't touch. Ask [kb] myList.getEmptyText().setText("Searching..."); if (myList.getModel() instanceof SearchListModel) { //noinspection unchecked myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { if (!myDone.isRejected()) { myList.setModel(myListModel); updatePopup(); } }, 50); } else { myList.setModel(myListModel); } }); if (pattern.trim().length() == 0) { buildModelFromRecentFiles(); //updatePopup(); return; } checkModelsUpToDate(); check(); buildTopHit(pattern); check(); if (!pattern.startsWith("#")) { buildRecentFiles(pattern); check(); runReadAction(() -> buildStructure(pattern), true); updatePopup(); check(); buildToolWindows(pattern); check(); updatePopup(); check(); checkModelsUpToDate(); runReadAction(() -> buildRunConfigurations(pattern), true); runReadAction(() -> buildClasses(pattern), true); runReadAction(() -> buildFiles(pattern), false); runReadAction(() -> buildSymbols(pattern), true); buildActionsAndSettings(pattern); updatePopup(); } updatePopup(); } catch (ProcessCanceledException ignore) { myDone.setRejected(); } catch (Exception e) { LOG.error(e); myDone.setRejected(); } finally { if (!isCanceled()) { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> myList.getEmptyText().setText(StatusText.DEFAULT_EMPTY_TEXT)); updatePopup(); } if (!myDone.isProcessed()) { myDone.setDone(); } } } private void runReadAction(Runnable action, boolean checkDumb) { if (!checkDumb || !DumbService.getInstance(project).isDumb()) { ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(action, myProgressIndicator); updatePopup(); } } protected void check() { myProgressIndicator.checkCanceled(); if (myDone.isRejected()) throw new ProcessCanceledException(); if (myBalloon == null || myBalloon.isDisposed()) throw new ProcessCanceledException(); assert myCalcThread == this : "There are two CalcThreads running before one of them was cancelled"; } private synchronized void buildToolWindows(String pattern) { if (!Registry.is("search.everywhere.toolwindows")) { return; } final List<ActivateToolWindowAction> actions = new ArrayList<>(); for (ActivateToolWindowAction action : ToolWindowsGroup.getToolWindowActions(project, false)) { String text = action.getTemplatePresentation().getText(); if (text != null && StringUtil.startsWithIgnoreCase(text, pattern)) { actions.add(action); if (actions.size() == MAX_TOOL_WINDOWS) { break; } } } check(); if (actions.isEmpty()) { return; } SwingUtilities.invokeLater(() -> { myListModel.titleIndex.toolWindows = myListModel.size(); for (Object toolWindow : actions) { myListModel.addElement(toolWindow); } }); } private SearchResult getActionsOrSettings(final String pattern, final int max, final boolean actions) { final SearchResult result = new SearchResult(); if ((actions && !Registry.is("search.everywhere.actions")) || (!actions && !Registry.is("search.everywhere.settings"))) { return result; } final MinusculeMatcher matcher = NameUtil.buildMatcher("*" +pattern).build(); if (myActionProvider == null) { myActionProvider = createActionProvider(); } myActionProvider.filterElements(pattern, matched -> { check(); Object object = matched.value; if (myListModel.contains(object)) return true; if (!actions && isSetting(object)) { if (matcher.matches(getSettingText((OptionDescription)object))) { result.add(object); } } else if (actions && !isToolWindowAction(object) && isActionValue(object)) { AnAction action = object instanceof AnAction ? ((AnAction)object) : ((GotoActionModel.ActionWrapper)object).getAction(); Object lock = myCalcThread; if (lock != null) { synchronized (lock) { if (isEnabled(action)) { result.add(object); } } } } return result.size() <= max; }); return result; } private synchronized void buildActionsAndSettings(String pattern) { final SearchResult actions = getActionsOrSettings(pattern, MAX_ACTIONS, true); final SearchResult settings = getActionsOrSettings(pattern, MAX_SETTINGS, false); check(); SwingUtilities.invokeLater(() -> { if (isCanceled()) return; if (actions.size() > 0) { myListModel.titleIndex.actions = myListModel.size(); for (Object action : actions) { myListModel.addElement(action); } } myListModel.moreIndex.actions = actions.size() >= MAX_ACTIONS ? myListModel.size() - 1 : -1; if (settings.size() > 0) { myListModel.titleIndex.settings = myListModel.size(); for (Object setting : settings) { myListModel.addElement(setting); } } myListModel.moreIndex.settings = settings.size() >= MAX_SETTINGS ? myListModel.size() - 1 : -1; }); } private synchronized void buildFiles(final String pattern) { final SearchResult files = getFiles(pattern, showAll.get(), MAX_FILES, myFileChooseByName); check(); if (files.size() > 0) { SwingUtilities.invokeLater(() -> { if (isCanceled()) return; myListModel.titleIndex.files = myListModel.size(); for (Object file : files) { myListModel.addElement(file); } myListModel.moreIndex.files = files.needMore ? myListModel.size() - 1 : -1; }); } } private synchronized void buildStructure(final String pattern) { if (!Registry.is("search.everywhere.structure") || myStructureModel == null) return; final List<StructureViewTreeElement> elements = new ArrayList<>(); final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern).build(); fillStructure(myStructureModel.getRoot(), elements, matcher); if (elements.size() > 0) { SwingUtilities.invokeLater(() -> { if (isCanceled()) return; myListModel.titleIndex.structure = myListModel.size(); for (Object element : elements) { myListModel.addElement(element); } myListModel.moreIndex.files = -1; }); } } private void fillStructure(StructureViewTreeElement element, List<StructureViewTreeElement> elements, Matcher matcher) { final TreeElement[] children = element.getChildren(); check(); for (TreeElement child : children) { check(); if (child instanceof StructureViewTreeElement) { final String text = child.getPresentation().getPresentableText(); if (text != null && matcher.matches(text)) { elements.add((StructureViewTreeElement)child); } fillStructure((StructureViewTreeElement)child, elements, matcher); } } } private synchronized void buildSymbols(final String pattern) { final SearchResult symbols = getSymbols(pattern, MAX_SYMBOLS, showAll.get(), mySymbolsChooseByName); check(); if (symbols.size() > 0) { SwingUtilities.invokeLater(() -> { if (isCanceled()) return; myListModel.titleIndex.symbols = myListModel.size(); for (Object file : symbols) { myListModel.addElement(file); } myListModel.moreIndex.symbols = symbols.needMore ? myListModel.size() - 1 : -1; }); } } @Nullable private ChooseRunConfigurationPopup.ItemWrapper getRunConfigurationByName(String name) { final ChooseRunConfigurationPopup.ItemWrapper[] wrappers = ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() { @Override public Executor getExecutor() { return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG); } }, false); for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) { if (wrapper.getText().equals(name)) { return wrapper; } } return null; } private synchronized void buildRunConfigurations(String pattern) { final SearchResult runConfigurations = getConfigurations(pattern, MAX_RUN_CONFIGURATION); if (runConfigurations.size() > 0) { SwingUtilities.invokeLater(() -> { if (isCanceled()) return; myListModel.titleIndex.runConfigurations = myListModel.size(); for (Object runConfiguration : runConfigurations) { myListModel.addElement(runConfiguration); } myListModel.moreIndex.runConfigurations = runConfigurations.needMore ? myListModel.getSize() - 1 : -1; }); } } private SearchResult getConfigurations(String pattern, int max) { SearchResult configurations = new SearchResult(); if (!Registry.is("search.everywhere.configurations")) { return configurations; } final MinusculeMatcher matcher = NameUtil.buildMatcher(pattern).build(); final ChooseRunConfigurationPopup.ItemWrapper[] wrappers = ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() { @Override public Executor getExecutor() { return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG); } }, false); check(); for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) { if (matcher.matches(wrapper.getText()) && !myListModel.contains(wrapper)) { if (configurations.size() == max) { configurations.needMore = true; break; } configurations.add(wrapper); } check(); } return configurations; } private synchronized void buildClasses(final String pattern) { final SearchResult classes = getClasses(pattern, showAll.get(), MAX_CLASSES, myClassChooseByName); check(); if (classes.size() > 0) { SwingUtilities.invokeLater(() -> { if (isCanceled()) return; myListModel.titleIndex.classes = myListModel.size(); for (Object file : classes) { myListModel.addElement(file); } myListModel.moreIndex.classes = -1; if (classes.needMore) { myListModel.moreIndex.classes = myListModel.size() - 1; } }); } } @NotNull private GlobalSearchScope getProjectScope(@NotNull Project project) { final GlobalSearchScope scope = SearchEverywhereClassifier.EP_Manager.getProjectScope(project); if (scope != null) return scope; return GlobalSearchScope.projectScope(project); } private SearchResult getSymbols(String pattern, final int max, final boolean includeLibs, ChooseByNamePopup chooseByNamePopup) { final SearchResult symbols = new SearchResult(); if (!Registry.is("search.everywhere.symbols") || shouldSkipPattern(pattern)) { return symbols; } final GlobalSearchScope scope = getProjectScope(project); if (chooseByNamePopup == null) return symbols; final ChooseByNameItemProvider provider = chooseByNamePopup.getProvider(); provider.filterElements(chooseByNamePopup, pattern, includeLibs, myProgressIndicator, o -> { if (SearchEverywhereClassifier.EP_Manager.isSymbol(o) && !myListModel.contains(o) && !symbols.contains(o)) { PsiElement element = null; if (o instanceof PsiElement) { element = (PsiElement)o; } else if (o instanceof PsiElementNavigationItem) { element = ((PsiElementNavigationItem)o).getTargetElement(); } VirtualFile virtualFile = SearchEverywhereClassifier.EP_Manager.getVirtualFile(o); //some elements are non-physical like DB columns boolean isElementWithoutFile = element != null && element.getContainingFile() == null; boolean isFileInScope = virtualFile != null && (includeLibs || scope.accept(virtualFile)); boolean isSpecialElement = element == null && virtualFile == null; //all Rider elements don't have any psi elements within if (isElementWithoutFile || isFileInScope || isSpecialElement) { symbols.add(o); } } symbols.needMore = symbols.size() == max; return !symbols.needMore; }); if (!includeLibs && symbols.isEmpty()) { return getSymbols(pattern, max, true, chooseByNamePopup); } return symbols; } private SearchResult getClasses(String pattern, boolean includeLibs, final int max, ChooseByNamePopup chooseByNamePopup) { final SearchResult classes = new SearchResult(); if (chooseByNamePopup == null || shouldSkipPattern(pattern)) { return classes; } chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, includeLibs, myProgressIndicator, o -> { if (SearchEverywhereClassifier.EP_Manager.isClass(o) && !myListModel.contains(o) && !classes.contains(o)) { if (classes.size() == max) { classes.needMore = true; return false; } PsiElement element = null; if (o instanceof PsiElement) { element = (PsiElement)o; } else if (o instanceof PsiElementNavigationItem) { element = ((PsiElementNavigationItem)o).getTargetElement(); } classes.add(o); if (element instanceof PsiNamedElement) { final String name = ((PsiNamedElement)element).getName(); VirtualFile virtualFile = SearchEverywhereClassifier.EP_Manager.getVirtualFile(o); if (virtualFile != null) { if (StringUtil.equals(name, virtualFile.getNameWithoutExtension())) { myAlreadyAddedFiles.add(virtualFile); } } } } return true; }); if (!includeLibs && classes.isEmpty()) { return getClasses(pattern, true, max, chooseByNamePopup); } return classes; } private SearchResult getFiles(final String pattern, final boolean includeLibs, final int max, ChooseByNamePopup chooseByNamePopup) { final SearchResult files = new SearchResult(); if (chooseByNamePopup == null || !Registry.is("search.everywhere.files")) { return files; } final GlobalSearchScope scope = getProjectScope(project); chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, true, myProgressIndicator, o -> { VirtualFile file = null; if (o instanceof VirtualFile) { file = (VirtualFile)o; } else if (o instanceof PsiFile) { file = ((PsiFile)o).getVirtualFile(); } else if (o instanceof PsiDirectory) { file = ((PsiDirectory)o).getVirtualFile(); } if (file != null && !(pattern.indexOf(' ') != -1 && file.getName().indexOf(' ') == -1) && (includeLibs || scope.accept(file) && !myListModel.contains(file) && !myAlreadyAddedFiles.contains(file)) && !files.contains(file)) { if (files.size() == max) { files.needMore = true; return false; } files.add(file); } return true; }); if (!includeLibs && files.isEmpty()) { return getFiles(pattern, true, max, chooseByNamePopup); } return files; } private synchronized void buildRecentFiles(String pattern) { final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern).build(); final ArrayList<VirtualFile> files = new ArrayList<>(); final List<VirtualFile> selected = Arrays.asList(FileEditorManager.getInstance(project).getSelectedFiles()); for (VirtualFile file : ContainerUtil.reverse(EditorHistoryManager.getInstance(project).getFileList())) { if (StringUtil.isEmptyOrSpaces(pattern) || matcher.matches(file.getName())) { if (!files.contains(file) && !selected.contains(file)) { files.add(file); } } if (files.size() > MAX_RECENT_FILES) break; } if (files.size() > 0) { myAlreadyAddedFiles.addAll(files); SwingUtilities.invokeLater(() -> { if (isCanceled()) return; myListModel.titleIndex.recentFiles = myListModel.size(); for (Object file : files) { myListModel.addElement(file); } updatePopup(); }); } } private boolean isCanceled() { return myProgressIndicator.isCanceled() || myDone.isRejected(); } private synchronized void buildTopHit(String pattern) { final List<Object> elements = new ArrayList<>(); final HistoryItem history = myHistoryItem; if (history != null) { final HistoryType type = parseHistoryType(history.type); if (type != null) { switch (type){ case PSI: if (!DumbService.isDumb(project)) { ApplicationManager.getApplication().runReadAction(() -> { final int i = history.fqn.indexOf("://"); if (i != -1) { final String langId = history.fqn.substring(0, i); final Language language = Language.findLanguageByID(langId); final String psiFqn = history.fqn.substring(i + 3); if (language != null) { final PsiElement psi = LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).findByQualifiedName(project, psiFqn); if (psi != null) { elements.add(psi); final PsiFile psiFile = psi.getContainingFile(); if (psiFile != null) { final VirtualFile file = psiFile.getVirtualFile(); if (file != null) { myAlreadyAddedFiles.add(file); } } } } } }); } break; case FILE: final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(history.fqn); if (file != null) { elements.add(file); } break; case SETTING: break; case ACTION: final AnAction action = ActionManager.getInstance().getAction(history.fqn); if (action != null) { elements.add(action); myAlreadyAddedActions.add(action); } break; case RUN_CONFIGURATION: if (!DumbService.isDumb(project)) { ApplicationManager.getApplication().runReadAction(() -> { final ChooseRunConfigurationPopup.ItemWrapper runConfiguration = getRunConfigurationByName(history.fqn); if (runConfiguration != null) { elements.add(runConfiguration); } }); } break; } } } final Consumer<Object> consumer = o -> { if (isSetting(o) || isVirtualFile(o) || isActionValue(o) || o instanceof PsiElement || o instanceof OptionsTopHitProvider) { if (o instanceof AnAction && myAlreadyAddedActions.contains(o)) { return; } elements.add(o); } }; if (pattern.startsWith("#") && !pattern.contains(" ")) { String id = pattern.substring(1); final HashSet<String> ids = new HashSet<>(); for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) { check(); if (provider instanceof OptionsTopHitProvider) { final String providerId = ((OptionsTopHitProvider)provider).getId(); if (!ids.contains(providerId) && StringUtil.startsWithIgnoreCase(providerId, id)) { consumer.consume(provider); ids.add(providerId); } } } } else { final ActionManager actionManager = ActionManager.getInstance(); final List<String> actions = AbbreviationManager.getInstance().findActions(pattern); for (String actionId : actions) { consumer.consume(actionManager.getAction(actionId)); } for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) { check(); if (provider instanceof OptionsTopHitProvider && !((OptionsTopHitProvider)provider).isEnabled(project)) { continue; } provider.consumeTopHits(pattern, consumer, project); } } if (elements.size() > 0) { SwingUtilities.invokeLater(() -> { if (isCanceled()) return; for (Object element : new ArrayList(elements)) { if (element instanceof AnAction) { if (!isEnabled((AnAction)element)) { elements.remove(element); } if (isCanceled()) return; } } if (isCanceled() || elements.isEmpty()) return; myListModel.titleIndex.topHit = myListModel.size(); for (Object element : ContainerUtil.getFirstItems(elements, MAX_TOP_HIT)) { myListModel.addElement(element); } }); } } protected boolean isEnabled(final AnAction action) { AnActionEvent event = myActionEvent; if (myDisabledActions.contains(action) || event == null) return false; final AnActionEvent e = new AnActionEvent(event.getInputEvent(), event.getDataContext(), event.getPlace(), action.getTemplatePresentation().clone(), event.getActionManager(), event.getModifiers()); ApplicationManager.getApplication().invokeAndWait(() -> ActionUtil.performDumbAwareUpdate(action, e, false), ModalityState.NON_MODAL); final Presentation presentation = e.getPresentation(); final boolean enabled = presentation.isEnabled() && presentation.isVisible() && !StringUtil.isEmpty(presentation.getText()); if (!enabled) { myDisabledActions.add(action); } return enabled; } private synchronized void checkModelsUpToDate() { if (myClassModel == null) { myClassModel = new GotoClassModel2(project); myFileModel = new GotoFileModel(project) { @Override public boolean isSlashlessMatchingEnabled() { return false; } }; mySymbolsModel = new GotoSymbolModel2(project); myFileChooseByName = ChooseByNamePopup.createPopup(project, myFileModel, (PsiElement)null); myClassChooseByName = ChooseByNamePopup.createPopup(project, myClassModel, (PsiElement)null); mySymbolsChooseByName = ChooseByNamePopup.createPopup(project, mySymbolsModel, (PsiElement)null); project.putUserData(ChooseByNamePopup.CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY, null); myActionProvider = createActionProvider(); myConfigurables.clear(); fillConfigurablesIds(null, ShowSettingsUtilImpl.getConfigurables(project, true)); } if (myStructureModel == null && myFileEditor != null && Registry.is("search.everywhere.structure")) { runReadAction(() -> { StructureViewBuilder structureViewBuilder = myFileEditor.getStructureViewBuilder(); if (structureViewBuilder == null) return; StructureView structureView = structureViewBuilder.createStructureView(myFileEditor, project); myStructureModel = structureView.getTreeModel(); }, true); } } private void buildModelFromRecentFiles() { buildRecentFiles(""); } private GotoActionItemProvider createActionProvider() { GotoActionModel model = new GotoActionModel(project, myFocusComponent, myEditor) { @Override protected MatchMode actionMatches(@NotNull String pattern, MinusculeMatcher matcher, @NotNull AnAction anAction) { MatchMode mode = super.actionMatches(pattern, matcher, anAction); return mode == MatchMode.NAME ? mode : MatchMode.NONE; } }; return new GotoActionItemProvider(model); } @SuppressWarnings("SSBasedInspection") private void updatePopup() { check(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { myListModel.update(); myList.revalidate(); myList.repaint(); myRenderer.recalculateWidth(); if (myBalloon == null || myBalloon.isDisposed()) { return; } if (myPopup == null || !myPopup.isVisible()) { ScrollingUtil.installActions(myList, getField().getTextEditor()); JBScrollPane content = new JBScrollPane(myList) { { if (UIUtil.isUnderDarcula()) { setBorder(null); } } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); Dimension listSize = myList.getPreferredSize(); if (size.height > listSize.height || myList.getModel().getSize() == 0) { size.height = Math.max(JBUI.scale(30), listSize.height); } if (myBalloon != null && size.width < myBalloon.getSize().width) { size.width = myBalloon.getSize().width; } return size; } }; content.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); content.setMinimumSize(new Dimension(myBalloon.getSize().width, 30)); final ComponentPopupBuilder builder = JBPopupFactory.getInstance() .createComponentPopupBuilder(content, null); myPopup = builder .setRequestFocus(false) .setCancelKeyEnabled(false) .setResizable(true) .setCancelCallback(() -> { final JBPopup balloon = myBalloon; final AWTEvent event = IdeEventQueue.getInstance().getTrueCurrentEvent(); if (event instanceof MouseEvent) { final Component comp = ((MouseEvent)event).getComponent(); if (balloon != null && UIUtil.getWindow(comp) == UIUtil.getWindow(balloon.getContent())) { return false; } } final boolean canClose = balloon == null || balloon.isDisposed() || (!getField().getTextEditor().hasFocus() && !mySkipFocusGain); if (canClose) { PropertiesComponent.getInstance().setValue("search.everywhere.max.popup.width", Math.max(content.getWidth(), JBUI.scale(600)), JBUI.scale(600)); } return canClose; }) .setShowShadow(false) .setShowBorder(false) .createPopup(); project.putUserData(SEARCH_EVERYWHERE_POPUP, myPopup); //myPopup.setMinimumSize(new Dimension(myBalloon.getSize().width, 30)); myPopup.getContent().setBorder(null); Disposer.register(myPopup, new Disposable() { @Override public void dispose() { project.putUserData(SEARCH_EVERYWHERE_POPUP, null); ApplicationManager.getApplication().executeOnPooledThread(() -> { resetFields(); myNonProjectCheckBox.setSelected(false); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> ActionToolbarImpl.updateAllToolbarsImmediately()); if (myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) { final Component component = myActionEvent.getInputEvent().getComponent(); if (component != null) { final JLabel label = UIUtil.getParentOfType(JLabel.class, component); if (label != null) { SwingUtilities.invokeLater(() -> label.setIcon(AllIcons.Actions.Find)); } } } myActionEvent = null; }); } }); updatePopupBounds(); myPopup.show(new RelativePoint(getField().getParent(), new Point(0, getField().getParent().getHeight()))); ActionManager.getInstance().addAnActionListener(new AnActionListener.Adapter() { @Override public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { if (action instanceof TextComponentEditorAction) { return; } if (myPopup!=null) { myPopup.cancel(); } } }, myPopup); } else { myList.revalidate(); myList.repaint(); } ScrollingUtil.ensureSelectionExists(myList); if (myList.getModel().getSize() > 0) { updatePopupBounds(); } } }); } public ActionCallback cancel() { myProgressIndicator.cancel(); //myDone.setRejected(); return myDone; } public ActionCallback insert(final int index, final WidgetID id) { ApplicationManager.getApplication().executeOnPooledThread(() -> { try { runReadAction(() -> { final SearchResult result = id == WidgetID.CLASSES ? getClasses(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myClassChooseByName) : id == WidgetID.FILES ? getFiles(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myFileChooseByName) : id == WidgetID.RUN_CONFIGURATIONS ? getConfigurations(pattern, DEFAULT_MORE_STEP_COUNT) : id == WidgetID.SYMBOLS ? getSymbols(pattern, DEFAULT_MORE_STEP_COUNT, showAll.get(), mySymbolsChooseByName) : id == WidgetID.ACTIONS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, true) : id == WidgetID.SETTINGS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, false) : new SearchResult(); check(); SwingUtilities.invokeLater(() -> { try { int shift = 0; int i = index+1; for (Object o : result) { //noinspection unchecked myListModel.insertElementAt(o, i); shift++; i++; } MoreIndex moreIndex = myListModel.moreIndex; myListModel.titleIndex.shift(index, shift); moreIndex.shift(index, shift); if (!result.needMore) { switch (id) { case CLASSES: moreIndex.classes = -1; break; case FILES: moreIndex.files = -1; break; case ACTIONS: moreIndex.actions = -1; break; case SETTINGS: moreIndex.settings = -1; break; case SYMBOLS: moreIndex.symbols = -1; break; case RUN_CONFIGURATIONS: moreIndex.runConfigurations = -1; break; } } ScrollingUtil.selectItem(myList, index); myDone.setDone(); } catch (Exception e) { myDone.setRejected(); } }); }, true); } catch (Exception e) { myDone.setRejected(); } }); return myDone; } public ActionCallback start() { ApplicationManager.getApplication().executeOnPooledThread(this); return myDone; } } private static boolean shouldSkipPattern(String pattern) { return Registry.is("search.everywhere.pattern.checking") && StringUtil.split(pattern, ".").size() == 2; } protected void resetFields() { if (myBalloon != null) { final JBPopup balloonToBeCanceled = myBalloon; //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> balloonToBeCanceled.cancel()); myBalloon = null; } myCurrentWorker.doWhenProcessed(() -> { myFileModel = null; if (myFileChooseByName != null) { myFileChooseByName.close(false); myFileChooseByName = null; } if (myClassChooseByName != null) { myClassChooseByName.close(false); myClassChooseByName = null; } if (mySymbolsChooseByName != null) { mySymbolsChooseByName.close(false); mySymbolsChooseByName = null; } final Object lock = myCalcThread; if (lock != null) { synchronized (lock) { myClassModel = null; myActionProvider = null; mySymbolsModel = null; myConfigurables.clear(); myFocusComponent = null; myContextComponent = null; myFocusOwner = null; myRenderer.myProject = null; myPopup = null; myHistoryIndex = 0; myPopupActualWidth = 0; showAll.set(false); myCurrentWorker = myCalcThread.cancel(); myCalcThread = null; myEditor = null; myFileEditor = null; myStructureModel = null; myDisabledActions.clear(); } } }); mySkipFocusGain = false; } private void updatePopupBounds() { if (myPopup == null || !myPopup.isVisible()) { return; } final Container parent = getField().getParent(); final Dimension size = myList.getParent().getParent().getPreferredSize(); size.width = myPopupActualWidth - 2; if (size.width + 2 < parent.getWidth()) { size.width = parent.getWidth(); } if (myList.getItemsCount() == 0) { size.height = JBUI.scale(30); } Dimension sz = new Dimension(size.width, myList.getPreferredSize().height); if (!SystemInfo.isMac) { if ((sz.width > getPopupMaxWidth() || sz.height > getPopupMaxWidth())) { final JBScrollPane pane = new JBScrollPane(); final int extraWidth = pane.getVerticalScrollBar().getWidth() + 1; final int extraHeight = pane.getHorizontalScrollBar().getHeight() + 1; sz = new Dimension(Math.min(getPopupMaxWidth(), Math.max(getField().getWidth(), sz.width + extraWidth)), Math.min(getPopupMaxWidth(), sz.height + extraHeight)); sz.width += 20; } else { sz.width += 2; } } sz.height += 2; sz.width = Math.max(sz.width, myPopup.getSize().width); myPopup.setSize(sz); if (myActionEvent != null && myActionEvent.getInputEvent() == null) { final Point p = parent.getLocationOnScreen(); p.y += parent.getHeight(); if (parent.getWidth() < sz.width) { p.x -= sz.width - parent.getWidth(); } myPopup.setLocation(p); } else { try { adjustPopup(); } catch (Exception ignore) {} } } private static int getPopupMaxWidth() { return PropertiesComponent.getInstance().getInt("search.everywhere.max.popup.width", JBUI.scale(600)); } private void adjustPopup() { // new PopupPositionManager.PositionAdjuster(getField().getParent(), 0).adjust(myPopup, PopupPositionManager.Position.BOTTOM); final Dimension d = PopupPositionManager.PositionAdjuster.getPopupSize(myPopup); final JComponent myRelativeTo = myBalloon.getContent(); Point myRelativeOnScreen = myRelativeTo.getLocationOnScreen(); Rectangle screen = ScreenUtil.getScreenRectangle(myRelativeOnScreen); Rectangle popupRect = null; Rectangle r = new Rectangle(myRelativeOnScreen.x, myRelativeOnScreen.y + myRelativeTo.getHeight(), d.width, d.height); if (screen.contains(r)) { popupRect = r; } if (popupRect != null) { Point location = new Point(r.x, r.y); if (!location.equals(myPopup.getLocationOnScreen())) { myPopup.setLocation(location); } } else { if (r.y + d.height > screen.y + screen.height) { r.height = screen.y + screen.height - r.y - 2; } if (r.width > screen.width) { r.width = screen.width - 50; } if (r.x + r.width > screen.x + screen.width) { r.x = screen.x + screen.width - r.width - 2; } myPopup.setSize(r.getSize()); myPopup.setLocation(r.getLocation()); } } private static boolean isToolWindowAction(Object o) { return isActionValue(o) && o instanceof GotoActionModel.ActionWrapper && ((GotoActionModel.ActionWrapper)o).getAction() instanceof ActivateToolWindowAction; } private void fillConfigurablesIds(String pathToParent, Configurable[] configurables) { for (Configurable configurable : configurables) { if (configurable instanceof SearchableConfigurable) { final String id = ((SearchableConfigurable)configurable).getId(); String name = configurable.getDisplayName(); if (pathToParent != null) { name = pathToParent + " -> " + name; } myConfigurables.put(id, name); if (configurable instanceof SearchableConfigurable.Parent) { fillConfigurablesIds(name, ((SearchableConfigurable.Parent)configurable).getConfigurables()); } } } } static class MoreIndex { volatile int classes = -1; volatile int files = -1; volatile int actions = -1; volatile int settings = -1; volatile int symbols = -1; volatile int runConfigurations = -1; volatile int structure = -1; public void shift(int index, int shift) { if (runConfigurations >= index) runConfigurations += shift; if (classes >= index) classes += shift; if (files >= index) files += shift; if (symbols >= index) symbols += shift; if (actions >= index) actions += shift; if (settings >= index) settings += shift; if (structure >= index) structure += shift; } } static class TitleIndex { volatile int topHit = -1; volatile int recentFiles = -1; volatile int runConfigurations = -1; volatile int classes = -1; volatile int structure = -1; volatile int files = -1; volatile int actions = -1; volatile int settings = -1; volatile int toolWindows = -1; volatile int symbols = -1; final String gotoClassTitle; final String gotoFileTitle; final String gotoActionTitle; final String gotoSettingsTitle; final String gotoRecentFilesTitle; final String gotoRunConfigurationsTitle; final String gotoSymbolTitle; final String gotoStructureTitle; static final String toolWindowsTitle = "Tool Windows"; TitleIndex() { String gotoClass = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoClass")); String classesStr = StringUtil.capitalize(StringUtil.join(GotoClassPresentationUpdater.getElementKinds(), s -> StringUtil.pluralize(s), "/")); gotoClassTitle = StringUtil.isEmpty(gotoClass) ? classesStr : classesStr + " (" + gotoClass + ")"; String gotoFile = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoFile")); gotoFileTitle = StringUtil.isEmpty(gotoFile) ? "Files" : "Files (" + gotoFile + ")"; String gotoAction = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoAction")); gotoActionTitle = StringUtil.isEmpty(gotoAction) ? "Actions" : "Actions (" + gotoAction + ")"; String gotoSettings = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ShowSettings")); gotoSettingsTitle = StringUtil.isEmpty(gotoAction) ? ShowSettingsUtil.getSettingsMenuName() : ShowSettingsUtil.getSettingsMenuName() + " (" + gotoSettings + ")"; String gotoRecentFiles = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("RecentFiles")); gotoRecentFilesTitle = StringUtil.isEmpty(gotoRecentFiles) ? "Recent Files" : "Recent Files (" + gotoRecentFiles + ")"; String gotoSymbol = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoSymbol")); gotoSymbolTitle = StringUtil.isEmpty(gotoSymbol) ? "Symbols" : "Symbols (" + gotoSymbol + ")"; String gotoRunConfiguration = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ChooseDebugConfiguration")); if (StringUtil.isEmpty(gotoRunConfiguration)) { gotoRunConfiguration = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ChooseRunConfiguration")); } gotoRunConfigurationsTitle = StringUtil.isEmpty(gotoRunConfiguration) ? "Run Configurations" : "Run Configurations (" + gotoRunConfiguration + ")"; String gotoStructure = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("FileStructurePopup")); gotoStructureTitle = StringUtil.isEmpty(gotoStructure) ? "File Structure" : "File Structure (" + gotoStructure + ")"; } String getTitle(int index) { if (index == topHit) return index == 0 ? "Top Hit" : "Top Hits"; if (index == recentFiles) return gotoRecentFilesTitle; if (index == structure) return gotoStructureTitle; if (index == runConfigurations) return gotoRunConfigurationsTitle; if (index == classes) return gotoClassTitle; if (index == files) return gotoFileTitle; if (index == toolWindows) return toolWindowsTitle; if (index == actions) return gotoActionTitle; if (index == settings) return gotoSettingsTitle; if (index == symbols) return gotoSymbolTitle; return null; } public void clear() { topHit = -1; runConfigurations = -1; recentFiles = -1; classes = -1; files = -1; structure = -1; actions = -1; settings = -1; toolWindows = -1; } public void shift(int index, int shift) { if (toolWindows != - 1 && toolWindows > index) toolWindows += shift; if (settings != - 1 && settings > index) settings += shift; if (actions != - 1 && actions > index) actions += shift; if (files != - 1 && files > index) files += shift; if (structure != - 1 && structure > index) structure += shift; if (classes != - 1 && classes > index) classes += shift; if (runConfigurations != - 1 && runConfigurations > index) runConfigurations += shift; if (symbols != - 1 && symbols > index) symbols += shift; } } static class SearchResult extends ArrayList<Object> { boolean needMore; } @SuppressWarnings("unchecked") private static class SearchListModel extends DefaultListModel<Object> { @SuppressWarnings("UseOfObsoleteCollectionType") Vector myDelegate; volatile TitleIndex titleIndex = new TitleIndex(); volatile MoreIndex moreIndex = new MoreIndex(); private SearchListModel() { super(); myDelegate = ReflectionUtil.getField(DefaultListModel.class, this, Vector.class, "delegate"); } int next(int index) { int[] all = getAll(); Arrays.sort(all); for (int next : all) { if (next > index) return next; } return 0; } int[] getAll() { return new int[]{ titleIndex.topHit, titleIndex.recentFiles, titleIndex.structure, titleIndex.runConfigurations, titleIndex.classes, titleIndex.files, titleIndex.actions, titleIndex.settings, titleIndex.toolWindows, titleIndex.symbols, moreIndex.classes, moreIndex.actions, moreIndex.files, moreIndex.settings, moreIndex.symbols, moreIndex.runConfigurations, moreIndex.structure }; } int prev(int index) { int[] all = getAll(); Arrays.sort(all); for (int i = all.length-1; i >= 0; i--) { if (all[i] != -1 && all[i] < index) return all[i]; } return all[all.length - 1]; } @Override public void addElement(Object obj) { myDelegate.add(obj); } public void update() { fireContentsChanged(this, 0, getSize() - 1); } } static class More extends JPanel { static final More instance = new More(); final JLabel label = new JLabel(" ... more "); private More() { super(new BorderLayout()); add(label, BorderLayout.CENTER); } static More get(boolean isSelected) { instance.setBackground(UIUtil.getListBackground(isSelected)); instance.label.setForeground(UIUtil.getLabelDisabledForeground()); instance.label.setFont(getTitleFont()); instance.label.setBackground(UIUtil.getListBackground(isSelected)); return instance; } } private static JComponent createTitle(String titleText) { JLabel titleLabel = new JLabel(titleText); titleLabel.setFont(getTitleFont()); titleLabel.setForeground(UIUtil.getLabelDisabledForeground()); SeparatorComponent separatorComponent = new SeparatorComponent(titleLabel.getPreferredSize().height / 2, new JBColor(Gray._220, Gray._80), null); return JBUI.Panels.simplePanel(5, 10) .addToCenter(separatorComponent) .addToLeft(titleLabel) .withBorder(RENDERER_TITLE_BORDER) .withBackground(UIUtil.getListBackground()); } private enum HistoryType {PSI, FILE, SETTING, ACTION, RUN_CONFIGURATION} @Nullable private static HistoryType parseHistoryType(@Nullable String name) { try { return HistoryType.valueOf(name); } catch (Exception e) { return null; } } private static class HistoryItem { final String pattern, type, fqn; private HistoryItem(String pattern, String type, String fqn) { this.pattern = pattern; this.type = type; this.fqn = fqn; } public String toString() { return pattern + "\t" + type + "\t" + fqn; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HistoryItem item = (HistoryItem)o; if (!pattern.equals(item.pattern)) return false; return true; } @Override public int hashCode() { return pattern.hashCode(); } } }
apache-2.0
saulbein/web3j
core/src/main/java/org/web3j/abi/datatypes/generated/Ufixed128x88.java
594
package org.web3j.abi.datatypes.generated; import java.math.BigInteger; import org.web3j.abi.datatypes.Ufixed; /** * <p>Auto generated code.<br> * <strong>Do not modifiy!</strong><br> * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p> */ public class Ufixed128x88 extends Ufixed { public static final Ufixed128x88 DEFAULT = new Ufixed128x88(BigInteger.ZERO); public Ufixed128x88(BigInteger value) { super(128, 88, value); } public Ufixed128x88(int mBitSize, int nBitSize, BigInteger m, BigInteger n) { super(128, 88, m, n); } }
apache-2.0
yuris7/java_ua
sandbox/src/test/java/ua/stqa/pft/sandbox/EquationTests.java
867
package ua.stqa.pft.sandbox; import org.testng.Assert; import org.testng.annotations.Test; public class EquationTests { @Test public void test0() { Equation e = new Equation(1, 1, 1); Assert.assertEquals(e.rootNumber(), 0); } @Test public void test1() { Equation e = new Equation(1, 2, 1); Assert.assertEquals(e.rootNumber(), 1); } @Test public void test2() { Equation e = new Equation(1, 5, 6); Assert.assertEquals(e.rootNumber(), 2); } @Test public void testLinear() { Equation e = new Equation(0, 1, 1); Assert.assertEquals(e.rootNumber(), 1); } @Test public void testConstant() { Equation e = new Equation(0, 0, 1); Assert.assertEquals(e.rootNumber(), 0); } @Test public void testZero() { Equation e = new Equation(0, 0, 0); Assert.assertEquals(e.rootNumber(), -1); } }
apache-2.0
ilya-moskovtsev/imoskovtsev
intern/chapter_001_basic_syntax/src/main/java/ru/job4j/array/RotateArray.java
1349
package ru.job4j.array; /** * 5.2. Создание программы поворота квадратного массива. * * @author imoskovtsev */ public class RotateArray { /** * Метод должен повернуть двумерный массив по часовой стрелке. * Задачу можно решить с использованием дополнительного массива, так и без него. * * @param array - исходный массив. * @return int[][] - массив повернутый по часовой стрелке на 90 градусов. */ public int[][] rotate(int[][] array) { int stop1 = array.length / 2; int stop2 = array.length / 2; if (array.length % 2 != 0) { stop2++; } int temp; for (int i = 0; i < stop1; i++) { for (int j = 0; j < stop2; j++) { temp = array[j][i]; array[j][i] = array[array.length - 1 - i][j]; array[array.length - 1 - i][j] = array[array.length - 1 - j][array.length - 1 - i]; array[array.length - 1 - j][array.length - 1 - i] = array[i][array.length - 1 - j]; array[i][array.length - 1 - j] = temp; } } return array; } }
apache-2.0
quarkusio/quarkus
integration-tests/grpc-proto-v2/src/main/java/io/quarkus/grpc/examples/hello/HelloWorldService.java
710
package io.quarkus.grpc.examples.hello; import java.util.concurrent.atomic.AtomicInteger; import examples.HelloReply; import examples.HelloRequest; import examples.MutinyGreeterGrpc; import io.quarkus.grpc.GrpcService; import io.smallrye.mutiny.Uni; @GrpcService public class HelloWorldService extends MutinyGreeterGrpc.GreeterImplBase { AtomicInteger counter = new AtomicInteger(); @Override public Uni<HelloReply> sayHello(HelloRequest request) { int count = counter.incrementAndGet(); String name = request.getName(); return Uni.createFrom().item("Hello " + name) .map(res -> HelloReply.newBuilder().setMessage(res).setCount(count).build()); } }
apache-2.0
ebi-uniprot/QuickGOBE
annotation-rest/src/test/java/uk/ac/ebi/quickgo/annotation/service/statistics/StatisticsTypeDefaultPropertiesIT.java
2273
package uk.ac.ebi.quickgo.annotation.service.statistics; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static uk.ac.ebi.quickgo.annotation.service.statistics.RequiredStatisticType.DEFAULT_LIMIT; import static uk.ac.ebi.quickgo.annotation.service.statistics.RequiredStatistics.DEFAULT_GO_TERM_LIMIT; /** * Created 14/08/17 * @author Edd */ @ActiveProfiles("stats-no-type-limit-properties-test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = StatisticsTypeDefaultPropertiesIT.FakeApplication.class) public class StatisticsTypeDefaultPropertiesIT { private static final String GO_ID = "goId"; @Autowired private RequiredStatisticsProvider requiredStatisticsProvider; private List<RequiredStatistic> statistics; @Before public void setUp() { statistics = requiredStatisticsProvider.getStandardUsage(); } @Test public void checkLimitsNotReadAndSetDefaultsForCorrectTypes() { for (RequiredStatistic request : statistics) { for (RequiredStatisticType type : request.getTypes()) { switch (type.getName()) { case GO_ID: assertThat(type.getLimit(), is(DEFAULT_GO_TERM_LIMIT)); break; default: assertThat(type.getLimit(), is(DEFAULT_LIMIT)); break; } } } } @Profile("stats-no-type-limit-properties-test") @Configuration @EnableAutoConfiguration @Import(StatisticsServiceConfig.class) public static class FakeApplication {} }
apache-2.0
madanadit/alluxio
core/transport/src/main/java/alluxio/grpc/GetMasterIdPRequest.java
27260
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: grpc/meta_master.proto package alluxio.grpc; /** * Protobuf type {@code alluxio.grpc.meta.GetMasterIdPRequest} */ public final class GetMasterIdPRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:alluxio.grpc.meta.GetMasterIdPRequest) GetMasterIdPRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetMasterIdPRequest.newBuilder() to construct. private GetMasterIdPRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetMasterIdPRequest() { } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private GetMasterIdPRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { alluxio.grpc.NetAddress.Builder subBuilder = null; if (((bitField0_ & 0x00000001) == 0x00000001)) { subBuilder = masterAddress_.toBuilder(); } masterAddress_ = input.readMessage(alluxio.grpc.NetAddress.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(masterAddress_); masterAddress_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 18: { alluxio.grpc.GetMasterIdPOptions.Builder subBuilder = null; if (((bitField0_ & 0x00000002) == 0x00000002)) { subBuilder = options_.toBuilder(); } options_ = input.readMessage(alluxio.grpc.GetMasterIdPOptions.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(options_); options_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000002; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_GetMasterIdPRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_GetMasterIdPRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( alluxio.grpc.GetMasterIdPRequest.class, alluxio.grpc.GetMasterIdPRequest.Builder.class); } private int bitField0_; public static final int MASTERADDRESS_FIELD_NUMBER = 1; private alluxio.grpc.NetAddress masterAddress_; /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public boolean hasMasterAddress() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public alluxio.grpc.NetAddress getMasterAddress() { return masterAddress_ == null ? alluxio.grpc.NetAddress.getDefaultInstance() : masterAddress_; } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public alluxio.grpc.NetAddressOrBuilder getMasterAddressOrBuilder() { return masterAddress_ == null ? alluxio.grpc.NetAddress.getDefaultInstance() : masterAddress_; } public static final int OPTIONS_FIELD_NUMBER = 2; private alluxio.grpc.GetMasterIdPOptions options_; /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public boolean hasOptions() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public alluxio.grpc.GetMasterIdPOptions getOptions() { return options_ == null ? alluxio.grpc.GetMasterIdPOptions.getDefaultInstance() : options_; } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public alluxio.grpc.GetMasterIdPOptionsOrBuilder getOptionsOrBuilder() { return options_ == null ? alluxio.grpc.GetMasterIdPOptions.getDefaultInstance() : options_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, getMasterAddress()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeMessage(2, getOptions()); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getMasterAddress()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getOptions()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof alluxio.grpc.GetMasterIdPRequest)) { return super.equals(obj); } alluxio.grpc.GetMasterIdPRequest other = (alluxio.grpc.GetMasterIdPRequest) obj; boolean result = true; result = result && (hasMasterAddress() == other.hasMasterAddress()); if (hasMasterAddress()) { result = result && getMasterAddress() .equals(other.getMasterAddress()); } result = result && (hasOptions() == other.hasOptions()); if (hasOptions()) { result = result && getOptions() .equals(other.getOptions()); } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasMasterAddress()) { hash = (37 * hash) + MASTERADDRESS_FIELD_NUMBER; hash = (53 * hash) + getMasterAddress().hashCode(); } if (hasOptions()) { hash = (37 * hash) + OPTIONS_FIELD_NUMBER; hash = (53 * hash) + getOptions().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static alluxio.grpc.GetMasterIdPRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static alluxio.grpc.GetMasterIdPRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static alluxio.grpc.GetMasterIdPRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static alluxio.grpc.GetMasterIdPRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static alluxio.grpc.GetMasterIdPRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static alluxio.grpc.GetMasterIdPRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(alluxio.grpc.GetMasterIdPRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code alluxio.grpc.meta.GetMasterIdPRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:alluxio.grpc.meta.GetMasterIdPRequest) alluxio.grpc.GetMasterIdPRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_GetMasterIdPRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_GetMasterIdPRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( alluxio.grpc.GetMasterIdPRequest.class, alluxio.grpc.GetMasterIdPRequest.Builder.class); } // Construct using alluxio.grpc.GetMasterIdPRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getMasterAddressFieldBuilder(); getOptionsFieldBuilder(); } } public Builder clear() { super.clear(); if (masterAddressBuilder_ == null) { masterAddress_ = null; } else { masterAddressBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); if (optionsBuilder_ == null) { options_ = null; } else { optionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_GetMasterIdPRequest_descriptor; } public alluxio.grpc.GetMasterIdPRequest getDefaultInstanceForType() { return alluxio.grpc.GetMasterIdPRequest.getDefaultInstance(); } public alluxio.grpc.GetMasterIdPRequest build() { alluxio.grpc.GetMasterIdPRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public alluxio.grpc.GetMasterIdPRequest buildPartial() { alluxio.grpc.GetMasterIdPRequest result = new alluxio.grpc.GetMasterIdPRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (masterAddressBuilder_ == null) { result.masterAddress_ = masterAddress_; } else { result.masterAddress_ = masterAddressBuilder_.build(); } if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } if (optionsBuilder_ == null) { result.options_ = options_; } else { result.options_ = optionsBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof alluxio.grpc.GetMasterIdPRequest) { return mergeFrom((alluxio.grpc.GetMasterIdPRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(alluxio.grpc.GetMasterIdPRequest other) { if (other == alluxio.grpc.GetMasterIdPRequest.getDefaultInstance()) return this; if (other.hasMasterAddress()) { mergeMasterAddress(other.getMasterAddress()); } if (other.hasOptions()) { mergeOptions(other.getOptions()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { alluxio.grpc.GetMasterIdPRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (alluxio.grpc.GetMasterIdPRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private alluxio.grpc.NetAddress masterAddress_ = null; private com.google.protobuf.SingleFieldBuilderV3< alluxio.grpc.NetAddress, alluxio.grpc.NetAddress.Builder, alluxio.grpc.NetAddressOrBuilder> masterAddressBuilder_; /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public boolean hasMasterAddress() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public alluxio.grpc.NetAddress getMasterAddress() { if (masterAddressBuilder_ == null) { return masterAddress_ == null ? alluxio.grpc.NetAddress.getDefaultInstance() : masterAddress_; } else { return masterAddressBuilder_.getMessage(); } } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public Builder setMasterAddress(alluxio.grpc.NetAddress value) { if (masterAddressBuilder_ == null) { if (value == null) { throw new NullPointerException(); } masterAddress_ = value; onChanged(); } else { masterAddressBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public Builder setMasterAddress( alluxio.grpc.NetAddress.Builder builderForValue) { if (masterAddressBuilder_ == null) { masterAddress_ = builderForValue.build(); onChanged(); } else { masterAddressBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public Builder mergeMasterAddress(alluxio.grpc.NetAddress value) { if (masterAddressBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && masterAddress_ != null && masterAddress_ != alluxio.grpc.NetAddress.getDefaultInstance()) { masterAddress_ = alluxio.grpc.NetAddress.newBuilder(masterAddress_).mergeFrom(value).buildPartial(); } else { masterAddress_ = value; } onChanged(); } else { masterAddressBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public Builder clearMasterAddress() { if (masterAddressBuilder_ == null) { masterAddress_ = null; onChanged(); } else { masterAddressBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public alluxio.grpc.NetAddress.Builder getMasterAddressBuilder() { bitField0_ |= 0x00000001; onChanged(); return getMasterAddressFieldBuilder().getBuilder(); } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ public alluxio.grpc.NetAddressOrBuilder getMasterAddressOrBuilder() { if (masterAddressBuilder_ != null) { return masterAddressBuilder_.getMessageOrBuilder(); } else { return masterAddress_ == null ? alluxio.grpc.NetAddress.getDefaultInstance() : masterAddress_; } } /** * <code>optional .alluxio.grpc.NetAddress masterAddress = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< alluxio.grpc.NetAddress, alluxio.grpc.NetAddress.Builder, alluxio.grpc.NetAddressOrBuilder> getMasterAddressFieldBuilder() { if (masterAddressBuilder_ == null) { masterAddressBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< alluxio.grpc.NetAddress, alluxio.grpc.NetAddress.Builder, alluxio.grpc.NetAddressOrBuilder>( getMasterAddress(), getParentForChildren(), isClean()); masterAddress_ = null; } return masterAddressBuilder_; } private alluxio.grpc.GetMasterIdPOptions options_ = null; private com.google.protobuf.SingleFieldBuilderV3< alluxio.grpc.GetMasterIdPOptions, alluxio.grpc.GetMasterIdPOptions.Builder, alluxio.grpc.GetMasterIdPOptionsOrBuilder> optionsBuilder_; /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public boolean hasOptions() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public alluxio.grpc.GetMasterIdPOptions getOptions() { if (optionsBuilder_ == null) { return options_ == null ? alluxio.grpc.GetMasterIdPOptions.getDefaultInstance() : options_; } else { return optionsBuilder_.getMessage(); } } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public Builder setOptions(alluxio.grpc.GetMasterIdPOptions value) { if (optionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } options_ = value; onChanged(); } else { optionsBuilder_.setMessage(value); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public Builder setOptions( alluxio.grpc.GetMasterIdPOptions.Builder builderForValue) { if (optionsBuilder_ == null) { options_ = builderForValue.build(); onChanged(); } else { optionsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public Builder mergeOptions(alluxio.grpc.GetMasterIdPOptions value) { if (optionsBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002) && options_ != null && options_ != alluxio.grpc.GetMasterIdPOptions.getDefaultInstance()) { options_ = alluxio.grpc.GetMasterIdPOptions.newBuilder(options_).mergeFrom(value).buildPartial(); } else { options_ = value; } onChanged(); } else { optionsBuilder_.mergeFrom(value); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public Builder clearOptions() { if (optionsBuilder_ == null) { options_ = null; onChanged(); } else { optionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public alluxio.grpc.GetMasterIdPOptions.Builder getOptionsBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOptionsFieldBuilder().getBuilder(); } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ public alluxio.grpc.GetMasterIdPOptionsOrBuilder getOptionsOrBuilder() { if (optionsBuilder_ != null) { return optionsBuilder_.getMessageOrBuilder(); } else { return options_ == null ? alluxio.grpc.GetMasterIdPOptions.getDefaultInstance() : options_; } } /** * <code>optional .alluxio.grpc.meta.GetMasterIdPOptions options = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< alluxio.grpc.GetMasterIdPOptions, alluxio.grpc.GetMasterIdPOptions.Builder, alluxio.grpc.GetMasterIdPOptionsOrBuilder> getOptionsFieldBuilder() { if (optionsBuilder_ == null) { optionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< alluxio.grpc.GetMasterIdPOptions, alluxio.grpc.GetMasterIdPOptions.Builder, alluxio.grpc.GetMasterIdPOptionsOrBuilder>( getOptions(), getParentForChildren(), isClean()); options_ = null; } return optionsBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:alluxio.grpc.meta.GetMasterIdPRequest) } // @@protoc_insertion_point(class_scope:alluxio.grpc.meta.GetMasterIdPRequest) private static final alluxio.grpc.GetMasterIdPRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new alluxio.grpc.GetMasterIdPRequest(); } public static alluxio.grpc.GetMasterIdPRequest getDefaultInstance() { return DEFAULT_INSTANCE; } @java.lang.Deprecated public static final com.google.protobuf.Parser<GetMasterIdPRequest> PARSER = new com.google.protobuf.AbstractParser<GetMasterIdPRequest>() { public GetMasterIdPRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new GetMasterIdPRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<GetMasterIdPRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetMasterIdPRequest> getParserForType() { return PARSER; } public alluxio.grpc.GetMasterIdPRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesis/model/DescribeStreamConsumerResult.java
4203
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.kinesis.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/DescribeStreamConsumer" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeStreamConsumerResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * An object that represents the details of the consumer. * </p> */ private ConsumerDescription consumerDescription; /** * <p> * An object that represents the details of the consumer. * </p> * * @param consumerDescription * An object that represents the details of the consumer. */ public void setConsumerDescription(ConsumerDescription consumerDescription) { this.consumerDescription = consumerDescription; } /** * <p> * An object that represents the details of the consumer. * </p> * * @return An object that represents the details of the consumer. */ public ConsumerDescription getConsumerDescription() { return this.consumerDescription; } /** * <p> * An object that represents the details of the consumer. * </p> * * @param consumerDescription * An object that represents the details of the consumer. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeStreamConsumerResult withConsumerDescription(ConsumerDescription consumerDescription) { setConsumerDescription(consumerDescription); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getConsumerDescription() != null) sb.append("ConsumerDescription: ").append(getConsumerDescription()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeStreamConsumerResult == false) return false; DescribeStreamConsumerResult other = (DescribeStreamConsumerResult) obj; if (other.getConsumerDescription() == null ^ this.getConsumerDescription() == null) return false; if (other.getConsumerDescription() != null && other.getConsumerDescription().equals(this.getConsumerDescription()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getConsumerDescription() == null) ? 0 : getConsumerDescription().hashCode()); return hashCode; } @Override public DescribeStreamConsumerResult clone() { try { return (DescribeStreamConsumerResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
PitneyBowes/LocationIntelligenceSDK-Java
src/main/java/pb/locationintelligence/model/DistanceToBorder.java
3092
/** * Location Intelligence APIs * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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 pb.locationintelligence.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * DistanceToBorder */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2020-04-16T15:55:12.092+05:30") public class DistanceToBorder { @SerializedName("unit") private String unit = null; @SerializedName("value") private String value = null; public DistanceToBorder unit(String unit) { this.unit = unit; return this; } /** * Get unit * @return unit **/ @ApiModelProperty(example = "null", value = "") public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public DistanceToBorder value(String value) { this.value = value; return this; } /** * Get value * @return value **/ @ApiModelProperty(example = "null", value = "") public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DistanceToBorder distanceToBorder = (DistanceToBorder) o; return Objects.equals(this.unit, distanceToBorder.unit) && Objects.equals(this.value, distanceToBorder.value); } @Override public int hashCode() { return Objects.hash(unit, value); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DistanceToBorder {\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
xc35/dragontoolkit
src/main/java/edu/drexel/cis/dragon/config/NERConfig.java
2243
/* */ package edu.drexel.cis.dragon.config; /* */ /* */ import edu.drexel.cis.dragon.nlp.tool.Annie; /* */ import edu.drexel.cis.dragon.nlp.tool.NER; /* */ /* */ public class NERConfig extends ConfigUtil /* */ { /* */ public NERConfig() /* */ { /* */ } /* */ /* */ public NERConfig(ConfigureNode root) /* */ { /* 20 */ super(root); /* */ } /* */ /* */ public NERConfig(String configFile) { /* 24 */ super(configFile); /* */ } /* */ /* */ public NER getNER(int taggerID) { /* 28 */ return getNER(this.root, taggerID); /* */ } /* */ /* */ public NER getNER(ConfigureNode node, int nerID) { /* 32 */ return loadNER(node, nerID); /* */ } /* */ /* */ private NER loadNER(ConfigureNode node, int nerID) /* */ { /* 38 */ ConfigureNode nerNode = getConfigureNode(node, "ner", nerID); /* 39 */ if (nerNode == null) { /* 40 */ return null; /* */ } /* 42 */ String nerName = nerNode.getNodeName(); /* 43 */ return loadNER(nerName, nerNode); /* */ } /* */ /* */ protected NER loadNER(String nerName, ConfigureNode nerNode) { /* 47 */ if (nerName.equalsIgnoreCase("Annie")) { /* 48 */ return loadAnnie(nerNode); /* */ } /* 50 */ return (NER)loadResource(nerNode); /* */ } /* */ /* */ private Annie loadAnnie(ConfigureNode curNode) /* */ { /* */ try /* */ { /* 58 */ String gateHome = curNode.getString("gatehome", null); /* 59 */ String annotationTypes = curNode.getString("entitytypes", "Person;Location;Organization"); /* */ Annie ner; /* 61 */ if (gateHome == null) /* 62 */ ner = new Annie(); /* */ else /* 64 */ ner = new Annie(gateHome); /* 65 */ ner.setAnnotationTypes(annotationTypes.split(";")); /* 66 */ return ner; /* */ } /* */ catch (Exception e) { /* 69 */ e.printStackTrace(); /* 70 */ }return null; /* */ } /* */ } /* Location: C:\dragontoolikt\dragontool.jar * Qualified Name: dragon.config.NERConfig * JD-Core Version: 0.6.2 */
apache-2.0
lucastheisen/apache-directory-server
service-builder/src/main/java/org/apache/directory/server/config/builder/ServiceBuilder.java
60662
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.server.config.builder; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.ldif.LdapLdifException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.api.ldap.model.message.AliasDerefMode; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.api.util.Strings; import org.apache.directory.server.config.ConfigSchemaConstants; import org.apache.directory.server.config.ConfigurationException; import org.apache.directory.server.config.beans.AuthenticationInterceptorBean; import org.apache.directory.server.config.beans.AuthenticatorBean; import org.apache.directory.server.config.beans.AuthenticatorImplBean; import org.apache.directory.server.config.beans.ChangeLogBean; import org.apache.directory.server.config.beans.ChangePasswordServerBean; import org.apache.directory.server.config.beans.DelegatingAuthenticatorBean; import org.apache.directory.server.config.beans.DirectoryServiceBean; import org.apache.directory.server.config.beans.ExtendedOpHandlerBean; import org.apache.directory.server.config.beans.HttpServerBean; import org.apache.directory.server.config.beans.HttpWebAppBean; import org.apache.directory.server.config.beans.IndexBean; import org.apache.directory.server.config.beans.InterceptorBean; import org.apache.directory.server.config.beans.JdbmIndexBean; import org.apache.directory.server.config.beans.JdbmPartitionBean; import org.apache.directory.server.config.beans.JournalBean; import org.apache.directory.server.config.beans.KdcServerBean; import org.apache.directory.server.config.beans.LdapServerBean; import org.apache.directory.server.config.beans.MavibotIndexBean; import org.apache.directory.server.config.beans.MavibotPartitionBean; import org.apache.directory.server.config.beans.NtpServerBean; import org.apache.directory.server.config.beans.PartitionBean; import org.apache.directory.server.config.beans.PasswordPolicyBean; import org.apache.directory.server.config.beans.ReplConsumerBean; import org.apache.directory.server.config.beans.SaslMechHandlerBean; import org.apache.directory.server.config.beans.TcpTransportBean; import org.apache.directory.server.config.beans.TransportBean; import org.apache.directory.server.constants.ApacheSchemaConstants; import org.apache.directory.server.core.DefaultDirectoryService; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.api.InstanceLayout; import org.apache.directory.server.core.api.authn.ppolicy.CheckQualityEnum; import org.apache.directory.server.core.api.authn.ppolicy.DefaultPasswordValidator; import org.apache.directory.server.core.api.authn.ppolicy.PasswordPolicyConfiguration; import org.apache.directory.server.core.api.authn.ppolicy.PasswordValidator; import org.apache.directory.server.core.api.changelog.ChangeLog; import org.apache.directory.server.core.api.interceptor.Interceptor; import org.apache.directory.server.core.api.journal.Journal; import org.apache.directory.server.core.api.journal.JournalStore; import org.apache.directory.server.core.api.partition.AbstractPartition; import org.apache.directory.server.core.api.partition.Partition; import org.apache.directory.server.core.authn.AuthenticationInterceptor; import org.apache.directory.server.core.authn.Authenticator; import org.apache.directory.server.core.authn.DelegatingAuthenticator; import org.apache.directory.server.core.authn.ppolicy.PpolicyConfigContainer; import org.apache.directory.server.core.changelog.DefaultChangeLog; import org.apache.directory.server.core.journal.DefaultJournal; import org.apache.directory.server.core.journal.DefaultJournalStore; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmDnIndex; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmRdnIndex; import org.apache.directory.server.core.partition.impl.btree.mavibot.MavibotDnIndex; import org.apache.directory.server.core.partition.impl.btree.mavibot.MavibotIndex; import org.apache.directory.server.core.partition.impl.btree.mavibot.MavibotPartition; import org.apache.directory.server.core.partition.impl.btree.mavibot.MavibotRdnIndex; import org.apache.directory.server.integration.http.HttpServer; import org.apache.directory.server.integration.http.WebApp; import org.apache.directory.server.kerberos.ChangePasswordConfig; import org.apache.directory.server.kerberos.KerberosConfig; import org.apache.directory.server.kerberos.changepwd.ChangePasswordServer; import org.apache.directory.server.kerberos.kdc.KdcServer; import org.apache.directory.server.ldap.ExtendedOperationHandler; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.ldap.handlers.sasl.MechanismHandler; import org.apache.directory.server.ldap.handlers.sasl.ntlm.NtlmMechanismHandler; import org.apache.directory.server.ldap.replication.SyncReplConfiguration; import org.apache.directory.server.ldap.replication.consumer.ReplicationConsumer; import org.apache.directory.server.ldap.replication.consumer.ReplicationConsumerImpl; import org.apache.directory.server.ldap.replication.provider.ReplicationRequestHandler; import org.apache.directory.server.ldap.replication.provider.SyncReplRequestHandler; import org.apache.directory.server.ntp.NtpServer; import org.apache.directory.server.protocol.shared.transport.TcpTransport; import org.apache.directory.server.protocol.shared.transport.Transport; import org.apache.directory.server.protocol.shared.transport.UdpTransport; import org.apache.directory.server.xdbm.Index; import org.apache.directory.shared.kerberos.codec.types.EncryptionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A class used for reading the configuration present in a Partition * and instantiate the necessary objects like DirectoryService, Interceptors etc. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ServiceBuilder { /** The logger for this class */ private static final Logger LOG = LoggerFactory.getLogger( ServiceBuilder.class ); /** LDIF file filter */ private static FilenameFilter ldifFilter = new FilenameFilter() { public boolean accept( File file, String name ) { if ( file.isDirectory() ) { return true; } return Strings.toLowerCase( file.getName() ).endsWith( ".ldif" ); } }; /** * Creates the Interceptor instances from the configuration * * @param dirServiceDN the Dn under which interceptors are configured * @return a list of instantiated Interceptor objects * @throws Exception If the instanciation failed */ public static List<Interceptor> createInterceptors( List<InterceptorBean> interceptorBeans ) throws LdapException { List<Interceptor> interceptors = new ArrayList<Interceptor>( interceptorBeans.size() ); // First order the interceptorBeans Set<InterceptorBean> orderedInterceptorBeans = new TreeSet<InterceptorBean>(); for ( InterceptorBean interceptorBean : interceptorBeans ) { if ( interceptorBean.isEnabled() ) { orderedInterceptorBeans.add( interceptorBean ); } } // Instantiate the interceptors now for ( InterceptorBean interceptorBean : orderedInterceptorBeans ) { try { LOG.debug( "loading the interceptor class {} and instantiating", interceptorBean.getInterceptorClassName() ); Interceptor interceptor = ( Interceptor ) Class.forName( interceptorBean.getInterceptorClassName() ) .newInstance(); if ( interceptorBean instanceof AuthenticationInterceptorBean ) { // Transports Authenticator[] authenticators = createAuthenticators( ( ( AuthenticationInterceptorBean ) interceptorBean ) .getAuthenticators() ); ( ( AuthenticationInterceptor ) interceptor ).setAuthenticators( authenticators ); // password policies List<PasswordPolicyBean> ppolicyBeans = ( ( AuthenticationInterceptorBean ) interceptorBean ) .getPasswordPolicies(); PpolicyConfigContainer ppolicyContainer = new PpolicyConfigContainer(); for ( PasswordPolicyBean ppolicyBean : ppolicyBeans ) { PasswordPolicyConfiguration ppolicyConfig = createPwdPolicyConfig( ppolicyBean ); if ( ppolicyConfig != null ) { // the name should be strictly 'default', the default policy can't be enforced by defining a new AT if ( ppolicyBean.getPwdId().equalsIgnoreCase( "default" ) ) { ppolicyContainer.setDefaultPolicy( ppolicyConfig ); } else { ppolicyContainer.addPolicy( ppolicyBean.getDn(), ppolicyConfig ); } } } ( ( AuthenticationInterceptor ) interceptor ).setPwdPolicies( ppolicyContainer ); } interceptors.add( interceptor ); } catch ( Exception e ) { e.printStackTrace(); String message = "Cannot initialize the " + interceptorBean.getInterceptorClassName() + ", error : " + e; LOG.error( message ); throw new ConfigurationException( message ); } } return interceptors; } /** * creates the PassworddPolicyConfiguration object after reading the config entry containing pwdpolicy OC * * @param PasswordPolicyBean The Bean containing the PasswordPolicy configuration * @return the {@link PasswordPolicyConfiguration} object, null if the pwdpolicy entry is not present or disabled */ public static PasswordPolicyConfiguration createPwdPolicyConfig( PasswordPolicyBean passwordPolicyBean ) { if ( ( passwordPolicyBean == null ) || passwordPolicyBean.isDisabled() ) { return null; } PasswordPolicyConfiguration passwordPolicy = new PasswordPolicyConfiguration(); passwordPolicy.setPwdAllowUserChange( passwordPolicyBean.isPwdAllowUserChange() ); passwordPolicy.setPwdAttribute( passwordPolicyBean.getPwdAttribute() ); passwordPolicy.setPwdCheckQuality( CheckQualityEnum.getCheckQuality( passwordPolicyBean.getPwdCheckQuality() ) ); passwordPolicy.setPwdExpireWarning( passwordPolicyBean.getPwdExpireWarning() ); passwordPolicy.setPwdFailureCountInterval( passwordPolicyBean.getPwdFailureCountInterval() ); passwordPolicy.setPwdGraceAuthNLimit( passwordPolicyBean.getPwdGraceAuthNLimit() ); passwordPolicy.setPwdGraceExpire( passwordPolicyBean.getPwdGraceExpire() ); passwordPolicy.setPwdInHistory( passwordPolicyBean.getPwdInHistory() ); passwordPolicy.setPwdLockout( passwordPolicyBean.isPwdLockout() ); passwordPolicy.setPwdLockoutDuration( passwordPolicyBean.getPwdLockoutDuration() ); passwordPolicy.setPwdMaxAge( passwordPolicyBean.getPwdMaxAge() ); passwordPolicy.setPwdMaxDelay( passwordPolicyBean.getPwdMaxDelay() ); passwordPolicy.setPwdMaxFailure( passwordPolicyBean.getPwdMaxFailure() ); passwordPolicy.setPwdMaxIdle( passwordPolicyBean.getPwdMaxIdle() ); passwordPolicy.setPwdMaxLength( passwordPolicyBean.getPwdMaxLength() ); passwordPolicy.setPwdMinAge( passwordPolicyBean.getPwdMinAge() ); passwordPolicy.setPwdMinDelay( passwordPolicyBean.getPwdMinDelay() ); passwordPolicy.setPwdMinLength( passwordPolicyBean.getPwdMinLength() ); passwordPolicy.setPwdMustChange( passwordPolicyBean.isPwdMustChange() ); passwordPolicy.setPwdSafeModify( passwordPolicyBean.isPwdSafeModify() ); PasswordValidator validator = null; try { String className = passwordPolicyBean.getPwdValidator(); if ( className != null ) { Class<?> cls = Class.forName( className ); validator = ( PasswordValidator ) cls.newInstance(); } } catch ( Exception e ) { LOG.warn( "Failed to load and instantiate the custom password validator for password policy config {}, using the default validator", passwordPolicyBean.getDn(), e ); } if ( validator == null ) { validator = new DefaultPasswordValidator(); } passwordPolicy.setPwdValidator( validator ); return passwordPolicy; } /** * Read the configuration for the ChangeLog system * * @param changelogBean The Bean containing the ChangeLog configuration * @return The instantiated ChangeLog element */ public static ChangeLog createChangeLog( ChangeLogBean changeLogBean ) { if ( ( changeLogBean == null ) || changeLogBean.isDisabled() ) { return null; } ChangeLog changeLog = new DefaultChangeLog(); changeLog.setEnabled( changeLogBean.isEnabled() ); changeLog.setExposed( changeLogBean.isChangeLogExposed() ); return changeLog; } /** * Instantiate the Journal object from the stored configuration * * @param changelogBean The Bean containing the ChangeLog configuration * @return An instance of Journal */ public static Journal createJournal( JournalBean journalBean ) { if ( ( journalBean == null ) || journalBean.isDisabled() ) { return null; } Journal journal = new DefaultJournal(); journal.setRotation( journalBean.getJournalRotation() ); journal.setEnabled( journalBean.isEnabled() ); JournalStore store = new DefaultJournalStore(); store.setFileName( journalBean.getJournalFileName() ); store.setWorkingDirectory( journalBean.getJournalWorkingDir() ); journal.setJournalStore( store ); return journal; } /** * Load the Test entries * * @param entryFilePath The place on disk where the test entries are stored * @return A list of LdifEntry elements * @throws ConfigurationException If we weren't able to read the entries */ public static List<LdifEntry> readTestEntries( String entryFilePath ) throws ConfigurationException { List<LdifEntry> entries = new ArrayList<LdifEntry>(); File file = new File( entryFilePath ); if ( !file.exists() ) { LOG.warn( "LDIF test entry file path doesn't exist {}", entryFilePath ); } else { LOG.debug( "parsing the LDIF file(s) present at the path {}", entryFilePath ); try { loadEntries( file, entries ); } catch ( LdapLdifException e ) { String message = "Error while parsing a LdifEntry : " + e.getMessage(); LOG.error( message ); throw new ConfigurationException( message ); } catch ( IOException e ) { String message = "cannot read the Ldif entries from the " + entryFilePath + " location"; LOG.error( message ); throw new ConfigurationException( message ); } } return entries; } /** * Load the entries from a Ldif file recursively * @throws LdapLdifException * @throws IOException */ private static void loadEntries( File ldifFile, List<LdifEntry> entries ) throws LdapLdifException, IOException { if ( ldifFile.isDirectory() ) { File[] files = ldifFile.listFiles( ldifFilter ); for ( File f : files ) { loadEntries( f, entries ); } } else { LdifReader reader = new LdifReader(); try { entries.addAll( reader.parseLdifFile( ldifFile.getAbsolutePath() ) ); } finally { reader.close(); } } } /** * Loads and instantiates a MechanismHandler from the configuration entry * * @param saslMechHandlerEntry the entry of OC type {@link ConfigSchemaConstants#ADS_LDAP_SERVER_SASL_MECH_HANDLER_OC} * @return an instance of the MechanismHandler type * @throws ConfigurationException if the SASL mechanism handler cannot be created */ public static MechanismHandler createSaslMechHandler( SaslMechHandlerBean saslMechHandlerBean ) throws ConfigurationException { if ( ( saslMechHandlerBean == null ) || saslMechHandlerBean.isDisabled() ) { return null; } String mechClassName = saslMechHandlerBean.getSaslMechClassName(); Class<?> mechClass = null; try { mechClass = Class.forName( mechClassName ); } catch ( ClassNotFoundException e ) { String message = "Cannot find the class " + mechClassName; LOG.error( message ); throw new ConfigurationException( message ); } MechanismHandler handler = null; try { handler = ( MechanismHandler ) mechClass.newInstance(); } catch ( InstantiationException e ) { String message = "Cannot instantiate the class : " + mechClassName; LOG.error( message ); throw new ConfigurationException( message ); } catch ( IllegalAccessException e ) { String message = "Cnnot invoke the class' constructor for " + mechClassName; LOG.error( message ); throw new ConfigurationException( message ); } if ( mechClass == NtlmMechanismHandler.class ) { NtlmMechanismHandler ntlmHandler = ( NtlmMechanismHandler ) handler; ntlmHandler.setNtlmProviderFqcn( saslMechHandlerBean.getNtlmMechProvider() ); } return handler; } /** * Creates a Authenticator from the configuration * * @param authenticatorBean The created instance of authenticator * @return An instance of authenticator if the given authenticatorBean is not disabled */ public static Authenticator createAuthenticator( AuthenticatorBean authenticatorBean ) throws ConfigurationException { if ( authenticatorBean.isDisabled() ) { return null; } Authenticator authenticator = null; if ( authenticatorBean instanceof DelegatingAuthenticatorBean ) { authenticator = new DelegatingAuthenticator(); ( ( DelegatingAuthenticator ) authenticator ) .setDelegateHost( ( ( DelegatingAuthenticatorBean ) authenticatorBean ).getDelegateHost() ); ( ( DelegatingAuthenticator ) authenticator ) .setDelegatePort( ( ( DelegatingAuthenticatorBean ) authenticatorBean ).getDelegatePort() ); } else if ( authenticatorBean instanceof AuthenticatorImplBean ) { String fqcn = ( ( AuthenticatorImplBean ) authenticatorBean ).getAuthenticatorClass(); try { Class<?> authnImplClass = Class.forName( fqcn ); authenticator = ( Authenticator ) authnImplClass.newInstance(); } catch ( Exception e ) { String errorMsg = "Failed to instantiate the configured authenticator " + authenticatorBean.getAuthenticatorId(); LOG.warn( errorMsg ); throw new ConfigurationException( errorMsg, e ); } } return authenticator; } /** * Creates a Transport from the configuration * * @param transportBean The created instance of transport * @return An instance of transport */ public static Transport createTransport( TransportBean transportBean ) { if ( ( transportBean == null ) || transportBean.isDisabled() ) { return null; } Transport transport = null; if ( transportBean instanceof TcpTransportBean ) { transport = new TcpTransport(); } else { transport = new UdpTransport(); } transport.setPort( transportBean.getSystemPort() ); transport.setAddress( transportBean.getTransportAddress() ); transport.setBackLog( transportBean.getTransportBackLog() ); transport.setEnableSSL( transportBean.isTransportEnableSSL() ); transport.setNbThreads( transportBean.getTransportNbThreads() ); return transport; } /** * Creates the array of transports read from the DIT * * @param transportBeans The array of Transport configuration * @return An arry of Transport instance */ public static Authenticator[] createAuthenticators( List<AuthenticatorBean> list ) throws ConfigurationException { Set<Authenticator> authenticators = new HashSet<Authenticator>( list.size() ); int i = 0; for ( AuthenticatorBean authenticatorBean : list ) { if ( authenticatorBean.isEnabled() ) { authenticators.add( createAuthenticator( authenticatorBean ) ); } } return authenticators.toArray( new Authenticator[] {} ); } /** * Creates the array of transports read from the DIT * * @param transportBeans The array of Transport configuration * @return An arry of Transport instance */ public static Transport[] createTransports( TransportBean[] transportBeans ) { List<Transport> transports = new ArrayList<Transport>(); for ( TransportBean transportBean : transportBeans ) { if ( transportBean.isEnabled() ) { transports.add( createTransport( transportBean ) ); } } return transports.toArray( new Transport[transports.size()] ); } /** * Helper method to create an Array of EncryptionTypes from an array of Strings */ private static EncryptionType[] createEncryptionTypes( List<String> encryptionTypes ) { if ( ( encryptionTypes == null ) || ( encryptionTypes.size() == 0 ) ) { return new EncryptionType[0]; } List<EncryptionType> types = new ArrayList<EncryptionType>(); for ( String encryptionType : encryptionTypes ) { EncryptionType et = EncryptionType.getByName( encryptionType ); if ( et == EncryptionType.UNKNOWN ) { LOG.warn( "Unknown encryption type {}", encryptionType ); } else { types.add( et ); } } return types.toArray( new EncryptionType[0] ); } /** * Instantiates a NtpServer based on the configuration present in the partition * * @param ntpServerBean The NtpServerBean containing the NtpServer configuration * @return Instance of NtpServer * @throws org.apache.directory.api.ldap.model.exception.LdapException */ public static NtpServer createNtpServer( NtpServerBean ntpServerBean, DirectoryService directoryService ) throws LdapException { // Fist, do nothing if the NtpServer is disabled if ( ( ntpServerBean == null ) || ntpServerBean.isDisabled() ) { return null; } NtpServer ntpServer = new NtpServer(); // The service ID ntpServer.setServiceId( ntpServerBean.getServerId() ); // The transports Transport[] transports = createTransports( ntpServerBean.getTransports() ); ntpServer.setTransports( transports ); return ntpServer; } /** * Instantiates a DhcpServer based on the configuration present in the partition * * @param dhcpServerBean The DhcpServerBean containing the DhcpServer configuration * @return Instance of DhcpServer * @throws LdapException * public static DhcpServer createDhcpServer( DhcpServerBean dhcpServerBean, DirectoryService directoryService ) throws LdapException { // Fist, do nothing if the DhcpServer is disabled if ( !dhcpServerBean.isEnabled() ) { return null; } DhcpServer dhcpServer = new DhcpServer(); // The service ID dhcpServer.setServiceId( dhcpServerBean.getServerId() ); // The transports Transport[] transports = createTransports( dhcpServerBean.getTransports() ); dhcpServer.setTransports( transports ); return dhcpServer; } /** * Instantiates a KdcServer based on the configuration present in the partition * * @param kdcServerBean The KdcServerBean containing the KdcServer configuration * @return Instance of KdcServer * @throws org.apache.directory.api.ldap.model.exception.LdapException */ public static KdcServer createKdcServer( DirectoryServiceBean directoryServiceBean, DirectoryService directoryService ) throws LdapException { KdcServerBean kdcServerBean = directoryServiceBean.getKdcServerBean(); // Fist, do nothing if the KdcServer is disabled if ( ( kdcServerBean == null ) || kdcServerBean.isDisabled() ) { return null; } KerberosConfig kdcConfig = new KerberosConfig(); // AllowableClockSkew kdcConfig.setAllowableClockSkew( kdcServerBean.getKrbAllowableClockSkew() ); // BodyChecksumVerified kdcConfig.setBodyChecksumVerified( kdcServerBean.isKrbBodyChecksumVerified() ); // EmptyAddressesAllowed kdcConfig.setEmptyAddressesAllowed( kdcServerBean.isKrbEmptyAddressesAllowed() ); // EncryptionType EncryptionType[] encryptionTypes = createEncryptionTypes( kdcServerBean.getKrbEncryptionTypes() ); kdcConfig.setEncryptionTypes( encryptionTypes ); // ForwardableAllowed kdcConfig.setForwardableAllowed( kdcServerBean.isKrbForwardableAllowed() ); // KdcPrincipal kdcConfig.setServicePrincipal( "krbtgt/" + kdcServerBean.getKrbPrimaryRealm() + "@" + kdcServerBean.getKrbPrimaryRealm() ); // MaximumRenewableLifetime kdcConfig.setMaximumRenewableLifetime( kdcServerBean.getKrbMaximumRenewableLifetime() ); // MaximumTicketLifetime kdcConfig.setMaximumTicketLifetime( kdcServerBean.getKrbMaximumTicketLifetime() ); // PaEncTimestampRequired kdcConfig.setPaEncTimestampRequired( kdcServerBean.isKrbPaEncTimestampRequired() ); // PostdatedAllowed kdcConfig.setPostdatedAllowed( kdcServerBean.isKrbPostdatedAllowed() ); // PrimaryRealm kdcConfig.setPrimaryRealm( kdcServerBean.getKrbPrimaryRealm() ); // ProxiableAllowed kdcConfig.setProxiableAllowed( kdcServerBean.isKrbProxiableAllowed() ); // RenewableAllowed kdcConfig.setRenewableAllowed( kdcServerBean.isKrbRenewableAllowed() ); // searchBaseDn kdcConfig.setSearchBaseDn( kdcServerBean.getSearchBaseDn().getName() ); KdcServer kdcServer = new KdcServer( kdcConfig ); kdcServer.setDirectoryService( directoryService ); kdcServer.setEnabled( true ); // The ID kdcServer.setServiceId( kdcServerBean.getServerId() ); // The transports Transport[] transports = createTransports( kdcServerBean.getTransports() ); kdcServer.setTransports( transports ); ChangePasswordServerBean changePasswordServerBean = directoryServiceBean.getChangePasswordServerBean(); // Fist, do nothing if the ChangePasswordServer is disabled if ( ( changePasswordServerBean != null ) && !changePasswordServerBean.isDisabled() ) { ChangePasswordServer changePasswordServer = new ChangePasswordServer( new ChangePasswordConfig( kdcConfig ) ); changePasswordServer.setEnabled( true ); changePasswordServer.setDirectoryService( directoryService ); // Transports Transport[] chngPwdTransports = createTransports( changePasswordServerBean.getTransports() ); changePasswordServer.setTransports( chngPwdTransports ); kdcServer.setChangePwdServer( changePasswordServer ); } return kdcServer; } /** * Instantiates the HttpWebApps based on the configuration present in the partition * * @param httpWebAppBeans The list of HttpWebAppBeans containing the HttpWebAppBeans configuration * @return Instances of HttpWebAppBean * @throws LdapException */ public static Set<WebApp> createHttpWebApps( List<HttpWebAppBean> httpWebAppBeans, DirectoryService directoryService ) throws LdapException { Set<WebApp> webApps = new HashSet<WebApp>(); if ( httpWebAppBeans == null ) { return webApps; } for ( HttpWebAppBean httpWebAppBean : httpWebAppBeans ) { if ( httpWebAppBean.isDisabled() ) { continue; } WebApp webApp = new WebApp(); // HttpAppCtxPath webApp.setContextPath( httpWebAppBean.getHttpAppCtxPath() ); // HttpWarFile webApp.setWarFile( httpWebAppBean.getHttpWarFile() ); webApps.add( webApp ); } return webApps; } /** * Instantiates a HttpServer based on the configuration present in the partition * * @param httpServerBean The HttpServerBean containing the HttpServer configuration * @return Instance of LdapServer * @throws LdapException */ public static HttpServer createHttpServer( HttpServerBean httpServerBean, DirectoryService directoryService ) throws LdapException { // Fist, do nothing if the HttpServer is disabled if ( ( httpServerBean == null ) || httpServerBean.isDisabled() ) { return null; } HttpServer httpServer = new HttpServer(); // HttpConfFile httpServer.setConfFile( httpServerBean.getHttpConfFile() ); // The transports TransportBean[] transports = httpServerBean.getTransports(); for ( TransportBean transportBean : transports ) { if ( transportBean.isDisabled() ) { continue; } if ( transportBean instanceof TcpTransportBean ) { TcpTransport transport = new TcpTransport( transportBean.getSystemPort() ); transport.setAddress( transportBean.getTransportAddress() ); if ( transportBean.getTransportId().equalsIgnoreCase( HttpServer.HTTP_TRANSPORT_ID ) ) { httpServer.setHttpTransport( transport ); } else if ( transportBean.getTransportId().equalsIgnoreCase( HttpServer.HTTPS_TRANSPORT_ID ) ) { httpServer.setHttpsTransport( transport ); } else { LOG.warn( "Transport ids of HttpServer should be either 'http' or 'https'" ); } } } // The webApps httpServer.setWebApps( createHttpWebApps( httpServerBean.getHttpWebApps(), directoryService ) ); return httpServer; } /** * Instantiates a ChangePasswordServer based on the configuration present in the partition * * @param ldapServerBean The ChangePasswordServerBean containing the ChangePasswordServer configuration * @return Instance of ChangePasswordServer * @throws LdapException * public static ChangePasswordServer createChangePasswordServer( ChangePasswordServerBean changePasswordServerBean, DirectoryService directoryService ) throws LdapException { // Fist, do nothing if the LdapServer is disabled if ( ( changePasswordServerBean == null ) || changePasswordServerBean.isDisabled() ) { return null; } ChangePasswordServer changePasswordServer = new ChangePasswordServer(); changePasswordServer.setEnabled( true ); changePasswordServer.setDirectoryService( directoryService ); // AllowableClockSkew changePasswordServer.setAllowableClockSkew( changePasswordServerBean.getKrbAllowableClockSkew() ); // TODO CatalogBased //changePasswordServer.setCatalogBased( changePasswordServerBean.isCatalogBase() ); // EmptyAddressesAllowed changePasswordServer.setEmptyAddressesAllowed( changePasswordServerBean.isKrbEmptyAddressesAllowed() ); // EncryptionTypes EncryptionType[] encryptionTypes = createEncryptionTypes( changePasswordServerBean.getKrbEncryptionTypes() ); changePasswordServer.setEncryptionTypes( encryptionTypes ); // PolicyCategoryCount changePasswordServer.setPolicyCategoryCount( changePasswordServerBean.getChgPwdPolicyCategoryCount() ); // PolicyPasswordLength changePasswordServer.setPolicyPasswordLength( changePasswordServerBean.getChgPwdPolicyPasswordLength() ); // policyTokenSize changePasswordServer.setPolicyTokenSize( changePasswordServerBean.getChgPwdPolicyTokenSize() ); // PrimaryRealm changePasswordServer.setPrimaryRealm( changePasswordServerBean.getKrbPrimaryRealm() ); // SearchBaseDn changePasswordServer.setSearchBaseDn( changePasswordServerBean.getSearchBaseDn().getName() ); // Id/Name changePasswordServer.setServiceName( changePasswordServerBean.getServerId() ); changePasswordServer.setServiceId( changePasswordServerBean.getServerId() ); // ServicePrincipal changePasswordServer.setServicePrincipal( changePasswordServerBean.getChgPwdServicePrincipal() ); // Transports Transport[] transports = createTransports( changePasswordServerBean.getTransports() ); changePasswordServer.setTransports( transports ); return changePasswordServer; } */ /** * Instantiates a LdapServer based on the configuration present in the partition * * @param ldapServerBean The LdapServerBean containing the LdapServer configuration * @return Instance of LdapServer * @throws LdapException */ public static LdapServer createLdapServer( LdapServerBean ldapServerBean, DirectoryService directoryService ) throws LdapException { // Fist, do nothing if the LdapServer is disabled if ( ( ldapServerBean == null ) || ldapServerBean.isDisabled() ) { return null; } LdapServer ldapServer = new LdapServer(); ldapServer.setDirectoryService( directoryService ); ldapServer.setEnabled( true ); // The ID ldapServer.setServiceId( ldapServerBean.getServerId() ); // SearchBaseDN ldapServer.setSearchBaseDn( ldapServerBean.getSearchBaseDn().getName() ); // KeyStore ldapServer.setKeystoreFile( ldapServerBean.getLdapServerKeystoreFile() ); // Certificate password ldapServer.setCertificatePassword( ldapServerBean.getLdapServerCertificatePassword() ); // ConfidentialityRequired ldapServer.setConfidentialityRequired( ldapServerBean.isLdapServerConfidentialityRequired() ); // Max size limit ldapServer.setMaxSizeLimit( ldapServerBean.getLdapServerMaxSizeLimit() ); // Max time limit ldapServer.setMaxTimeLimit( ldapServerBean.getLdapServerMaxTimeLimit() ); // MaxPDUSize ldapServer.setMaxPDUSize( ldapServerBean.getMaxPDUSize() ); // Sasl Host ldapServer.setSaslHost( ldapServerBean.getLdapServerSaslHost() ); // Sasl Principal ldapServer.setSaslPrincipal( ldapServerBean.getLdapServerSaslPrincipal() ); // Sasl realm ldapServer.setSaslRealms( ldapServerBean.getLdapServerSaslRealms() ); // Relplication pinger thread sleep time ldapServer.setReplPingerSleepTime( ldapServerBean.getReplPingerSleep() ); // Enabled cipher suites if ( ldapServerBean.getEnabledCipherSuites() != null ) { ldapServer.setEnabledCipherSuites( ldapServerBean.getEnabledCipherSuites() ); } // The transports Transport[] transports = createTransports( ldapServerBean.getTransports() ); ldapServer.setTransports( transports ); // SaslMechs for ( SaslMechHandlerBean saslMechHandlerBean : ldapServerBean.getSaslMechHandlers() ) { if ( saslMechHandlerBean.isEnabled() ) { String mechanism = saslMechHandlerBean.getSaslMechName(); ldapServer.addSaslMechanismHandler( mechanism, createSaslMechHandler( saslMechHandlerBean ) ); } } // ExtendedOpHandlers for ( ExtendedOpHandlerBean extendedpHandlerBean : ldapServerBean.getExtendedOps() ) { if ( extendedpHandlerBean.isEnabled() ) { try { Class<?> extendedOpClass = Class.forName( extendedpHandlerBean.getExtendedOpHandlerClass() ); ExtendedOperationHandler extOpHandler = ( ExtendedOperationHandler ) extendedOpClass.newInstance(); ldapServer.addExtendedOperationHandler( extOpHandler ); } catch ( Exception e ) { String message = "Failed to load and instantiate ExtendedOperationHandler implementation " + extendedpHandlerBean.getExtendedOpId() + ": " + e.getMessage(); LOG.error( message ); throw new ConfigurationException( message ); } } } // ReplReqHandler boolean replicationEnabled = ldapServerBean.isReplEnabled(); if ( replicationEnabled ) { String fqcn = ldapServerBean.getReplReqHandler(); if ( fqcn != null ) { try { Class<?> replProvImplClz = Class.forName( fqcn ); ReplicationRequestHandler rp = ( ReplicationRequestHandler ) replProvImplClz.newInstance(); ldapServer.setReplicationReqHandler( rp ); } catch ( Exception e ) { String message = "Failed to load and instantiate ReplicationRequestHandler implementation : " + fqcn; LOG.error( message ); throw new ConfigurationException( message ); } } else { // Try with the default handler ReplicationRequestHandler rp = new SyncReplRequestHandler(); ldapServer.setReplicationReqHandler( rp ); } } ldapServer.setReplConsumers( createReplConsumers( ldapServerBean.getReplConsumers() ) ); return ldapServer; } /** * instantiate the ReplicationConsumers based on the configuration present in ReplConsumerBeans * * @param replConsumerBeans the list of consumers configured * @return a list of ReplicationConsumer instances * @throws ConfigurationException */ public static List<ReplicationConsumer> createReplConsumers( List<ReplConsumerBean> replConsumerBeans ) throws ConfigurationException { List<ReplicationConsumer> lst = new ArrayList<ReplicationConsumer>(); if ( replConsumerBeans == null ) { return lst; } for ( ReplConsumerBean replBean : replConsumerBeans ) { String className = replBean.getReplConsumerImpl(); ReplicationConsumer consumer = null; Class<?> consumerClass = null; SyncReplConfiguration config = null; try { if ( className == null ) { consumer = new ReplicationConsumerImpl(); } else { consumerClass = Class.forName( className ); consumer = ( ReplicationConsumer ) consumerClass.newInstance(); } // we don't support any other configuration impls atm, but this configuration should suffice for many needs config = new SyncReplConfiguration(); config.setBaseDn( replBean.getSearchBaseDn() ); config.setRemoteHost( replBean.getReplProvHostName() ); config.setRemotePort( replBean.getReplProvPort() ); try { config.setAliasDerefMode( AliasDerefMode.getDerefMode( replBean.getReplAliasDerefMode() ) ); } catch ( IllegalArgumentException iae ) { LOG.error( iae.getMessage() + ", defaulted to 'never'" ); } config.setAttributes( replBean.getReplAttributes().toArray( new String[0] ) ); config.setRefreshInterval( replBean.getReplRefreshInterval() ); config.setRefreshNPersist( replBean.isReplRefreshNPersist() ); int scope = SearchScope.getSearchScope( replBean.getReplSearchScope() ); config.setSearchScope( SearchScope.getSearchScope( scope ) ); config.setFilter( replBean.getReplSearchFilter() ); config.setSearchTimeout( replBean.getReplSearchTimeout() ); config.setReplUserDn( replBean.getReplUserDn() ); config.setReplUserPassword( replBean.getReplUserPassword() ); config.setSearchSizeLimit( replBean.getReplSearchSizeLimit() ); config.setUseTls( replBean.isReplUseTls() ); config.setStrictCertVerification( replBean.isReplStrictCertValidation() ); config.setConfigEntryDn( replBean.getDn() ); consumer.setConfig( config ); lst.add( consumer ); } catch ( Exception e ) { throw new ConfigurationException( "cannot configure the replication consumer with FQCN " + className, e ); } } return lst; } /** * Create a new instance of a JdbmIndex from an instance of JdbmIndexBean * * @param JdbmIndexBean The JdbmIndexBean to convert * @return An JdbmIndex instance * @throws Exception If the instance cannot be created */ public static JdbmIndex<?> createJdbmIndex( JdbmPartition partition, JdbmIndexBean jdbmIndexBean, DirectoryService directoryService ) { if ( ( jdbmIndexBean == null ) || jdbmIndexBean.isDisabled() ) { return null; } String indexFileName = jdbmIndexBean.getIndexFileName(); if ( indexFileName == null ) { indexFileName = jdbmIndexBean.getIndexAttributeId(); } JdbmIndex<?> index = null; boolean hasReverse = jdbmIndexBean.getIndexHasReverse(); if ( jdbmIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_RDN_AT ) || jdbmIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_RDN_AT_OID ) ) { index = new JdbmRdnIndex(); } else if ( jdbmIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_ALIAS_AT ) || jdbmIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_ALIAS_AT_OID ) ) { index = new JdbmDnIndex( ApacheSchemaConstants.APACHE_ALIAS_AT_OID ); } else { index = new JdbmIndex<String>( jdbmIndexBean.getIndexAttributeId(), hasReverse ); } index.setCacheSize( jdbmIndexBean.getIndexCacheSize() ); index.setNumDupLimit( jdbmIndexBean.getIndexNumDupLimit() ); // Find the OID for this index SchemaManager schemaManager = directoryService.getSchemaManager(); try { AttributeType indexAT = schemaManager.lookupAttributeTypeRegistry( indexFileName ); indexFileName = indexAT.getOid(); } catch ( LdapException le ) { // Not found ? We will use the index file name } if ( jdbmIndexBean.getIndexWorkingDir() != null ) { index.setWkDirPath( new File( jdbmIndexBean.getIndexWorkingDir() ).toURI() ); } else { // Set the Partition working dir as a default index.setWkDirPath( partition.getPartitionPath() ); } return index; } /** * Create the list of Index from the configuration */ private static Set<Index<?, String>> createJdbmIndexes( JdbmPartition partition, List<IndexBean> indexesBeans, DirectoryService directoryService ) //throws Exception { Set<Index<?, String>> indexes = new HashSet<Index<?, String>>(); for ( IndexBean indexBean : indexesBeans ) { if ( indexBean.isEnabled() && ( indexBean instanceof JdbmIndexBean ) ) { indexes.add( createJdbmIndex( partition, ( JdbmIndexBean ) indexBean, directoryService ) ); } } return indexes; } /** * Create a new instance of a JdbmPartition * * @param jdbmPartitionBean the JdbmPartition bean * @return The instantiated JdbmPartition * @throws LdapInvalidDnException * @throws Exception If the instance cannot be created */ public static JdbmPartition createJdbmPartition( DirectoryService directoryService, JdbmPartitionBean jdbmPartitionBean ) throws ConfigurationException { if ( ( jdbmPartitionBean == null ) || jdbmPartitionBean.isDisabled() ) { return null; } JdbmPartition jdbmPartition = new JdbmPartition( directoryService.getSchemaManager(), directoryService.getDnFactory() ); jdbmPartition.setCacheSize( jdbmPartitionBean.getPartitionCacheSize() ); jdbmPartition.setId( jdbmPartitionBean.getPartitionId() ); jdbmPartition.setOptimizerEnabled( jdbmPartitionBean.isJdbmPartitionOptimizerEnabled() ); File partitionPath = new File( directoryService.getInstanceLayout().getPartitionsDirectory(), jdbmPartitionBean.getPartitionId() ); jdbmPartition.setPartitionPath( partitionPath.toURI() ); try { jdbmPartition.setSuffixDn( jdbmPartitionBean.getPartitionSuffix() ); } catch ( LdapInvalidDnException lide ) { String message = "Cannot set the Dn " + jdbmPartitionBean.getPartitionSuffix() + ", " + lide.getMessage(); LOG.error( message ); throw new ConfigurationException( message ); } jdbmPartition.setSyncOnWrite( jdbmPartitionBean.isPartitionSyncOnWrite() ); jdbmPartition.setIndexedAttributes( createJdbmIndexes( jdbmPartition, jdbmPartitionBean.getIndexes(), directoryService ) ); setContextEntry( jdbmPartitionBean, jdbmPartition ); return jdbmPartition; } /** * Create the a Partition instantiated from the configuration * * @param partitionBean the Partition bean * @return The instantiated Partition * @throws ConfigurationException If we cannot process the Partition */ public static Partition createPartition( DirectoryService directoryService, PartitionBean partitionBean ) throws ConfigurationException { if ( ( partitionBean == null ) || partitionBean.isDisabled() ) { return null; } if ( partitionBean instanceof JdbmPartitionBean ) { return createJdbmPartition( directoryService, ( JdbmPartitionBean ) partitionBean ); } else if ( partitionBean instanceof MavibotPartitionBean ) { return createMavibotPartition( directoryService, ( MavibotPartitionBean ) partitionBean ); } else { return null; } } /** * Create the set of Partitions instantiated from the configuration * * @param partitionBeans the list of Partition beans * @return A Map of all the instantiated partitions * @throws ConfigurationException If we cannot process some Partition */ public static Map<String, Partition> createPartitions( DirectoryService directoryService, List<PartitionBean> partitionBeans ) throws ConfigurationException { Map<String, Partition> partitions = new HashMap<String, Partition>( partitionBeans.size() ); for ( PartitionBean partitionBean : partitionBeans ) { if ( partitionBean.isDisabled() ) { continue; } Partition partition = createPartition( directoryService, partitionBean ); if ( partition != null ) { partitions.put( partitionBean.getPartitionId(), partition ); } } return partitions; } /** * Instantiates a DirectoryService based on the configuration present in the partition * * @param directoryServiceBean The bean containing the configuration * @param baseDirectory The working path for this DirectoryService * @return An instance of DirectoryService * @throws Exception */ public static DirectoryService createDirectoryService( DirectoryServiceBean directoryServiceBean, InstanceLayout instanceLayout, SchemaManager schemaManager ) throws Exception { DirectoryService directoryService = new DefaultDirectoryService(); // The schemaManager directoryService.setSchemaManager( schemaManager ); // MUST attributes // DirectoryService ID directoryService.setInstanceId( directoryServiceBean.getDirectoryServiceId() ); // Replica ID directoryService.setReplicaId( directoryServiceBean.getDsReplicaId() ); // WorkingDirectory directoryService.setInstanceLayout( instanceLayout ); // Interceptors List<Interceptor> interceptors = createInterceptors( directoryServiceBean.getInterceptors() ); directoryService.setInterceptors( interceptors ); // Partitions Map<String, Partition> partitions = createPartitions( directoryService, directoryServiceBean.getPartitions() ); Partition systemPartition = partitions.remove( "system" ); if ( systemPartition == null ) { //throw new Exception( I18n.err( I18n.ERR_505 ) ); } directoryService.setSystemPartition( systemPartition ); directoryService.setPartitions( new HashSet<Partition>( partitions.values() ) ); // MAY attributes // AccessControlEnabled directoryService.setAccessControlEnabled( directoryServiceBean.isDsAccessControlEnabled() ); // AllowAnonymousAccess directoryService.setAllowAnonymousAccess( directoryServiceBean.isDsAllowAnonymousAccess() ); // ChangeLog ChangeLog cl = createChangeLog( directoryServiceBean.getChangeLog() ); if ( cl != null ) { directoryService.setChangeLog( cl ); } // DenormalizedOpAttrsEnabled directoryService.setDenormalizeOpAttrsEnabled( directoryServiceBean.isDsDenormalizeOpAttrsEnabled() ); // Journal Journal journal = createJournal( directoryServiceBean.getJournal() ); if ( journal != null ) { directoryService.setJournal( journal ); } // PasswordHidden directoryService.setPasswordHidden( directoryServiceBean.isDsPasswordHidden() ); // SyncPeriodMillis directoryService.setSyncPeriodMillis( directoryServiceBean.getDsSyncPeriodMillis() ); // testEntries String entryFilePath = directoryServiceBean.getDsTestEntries(); if ( entryFilePath != null ) { directoryService.setTestEntries( readTestEntries( entryFilePath ) ); } // Enabled if ( !directoryServiceBean.isEnabled() ) { // will only be useful if we ever allow more than one DS to be configured and // switch between them // decide which one to use based on this flag // TODO } return directoryService; } public static MavibotPartition createMavibotPartition( DirectoryService directoryService, MavibotPartitionBean mvbtPartitionBean ) throws ConfigurationException { if ( ( mvbtPartitionBean == null ) || mvbtPartitionBean.isDisabled() ) { return null; } MavibotPartition mvbtPartition = new MavibotPartition( directoryService.getSchemaManager(), directoryService.getDnFactory() ); mvbtPartition.setId( mvbtPartitionBean.getPartitionId() ); //mvbtPartition.setOptimizerEnabled( mvbtPartitionBean.isJdbmPartitionOptimizerEnabled() ); File partitionPath = new File( directoryService.getInstanceLayout().getPartitionsDirectory(), mvbtPartitionBean.getPartitionId() ); mvbtPartition.setPartitionPath( partitionPath.toURI() ); try { mvbtPartition.setSuffixDn( mvbtPartitionBean.getPartitionSuffix() ); } catch ( LdapInvalidDnException lide ) { String message = "Cannot set the Dn " + mvbtPartitionBean.getPartitionSuffix() + ", " + lide.getMessage(); LOG.error( message ); throw new ConfigurationException( message ); } mvbtPartition.setSyncOnWrite( mvbtPartitionBean.isPartitionSyncOnWrite() ); mvbtPartition.setIndexedAttributes( createMavibotIndexes( mvbtPartition, mvbtPartitionBean.getIndexes(), directoryService ) ); setContextEntry( mvbtPartitionBean, mvbtPartition ); return mvbtPartition; } /** * Create the list of MavibotIndex from the configuration */ private static Set<Index<?, String>> createMavibotIndexes( MavibotPartition partition, List<IndexBean> indexesBeans, DirectoryService directoryService ) //throws Exception { Set<Index<?, String>> indexes = new HashSet<Index<?, String>>(); for ( IndexBean indexBean : indexesBeans ) { if ( indexBean.isEnabled() && ( indexBean instanceof MavibotIndexBean ) ) { indexes.add( createMavibotIndex( partition, ( MavibotIndexBean ) indexBean, directoryService ) ); } } return indexes; } /** * Create a new instance of a MavibotIndex from an instance of MavibotIndexBean * * @param MavibotIndexBean The MavibotIndexBean to convert * @return An MavibotIndex instance * @throws Exception If the instance cannot be created */ public static MavibotIndex<?> createMavibotIndex( MavibotPartition partition, MavibotIndexBean mavobotIndexBean, DirectoryService directoryService ) { if ( ( mavobotIndexBean == null ) || mavobotIndexBean.isDisabled() ) { return null; } MavibotIndex<?> index = null; boolean hasReverse = mavobotIndexBean.getIndexHasReverse(); if ( mavobotIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_RDN_AT ) || mavobotIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_RDN_AT_OID ) ) { index = new MavibotRdnIndex(); } else if ( mavobotIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_ALIAS_AT ) || mavobotIndexBean.getIndexAttributeId().equalsIgnoreCase( ApacheSchemaConstants.APACHE_ALIAS_AT_OID ) ) { index = new MavibotDnIndex( ApacheSchemaConstants.APACHE_ALIAS_AT_OID ); } else { index = new MavibotIndex<String>( mavobotIndexBean.getIndexAttributeId(), hasReverse ); } index.setWkDirPath( partition.getPartitionPath() ); return index; } /** * Sets the configured context entry if present in the given partition bean * * @param bean the partition configuration bean * @param partition the partition instance * @throws ConfigurationException */ private static void setContextEntry( PartitionBean bean, AbstractPartition partition ) throws ConfigurationException { String contextEntry = bean.getContextEntry(); if ( contextEntry != null ) { try { // Replace '\n' to real LF String entryStr = contextEntry.replaceAll( "\\\\n", "\n" ); LdifReader ldifReader = new LdifReader(); List<LdifEntry> entries = ldifReader.parseLdif( entryStr ); if ( ( entries != null ) && ( entries.size() > 0 ) ) { LdifEntry entry = entries.get( 0 ); partition.setContextEntry( entry.getEntry() ); } try { ldifReader.close(); } catch ( IOException ioe ) { LOG.error( "Cannot close the ldif reader" ); } } catch ( LdapLdifException lle ) { String message = "Cannot parse the context entry : " + contextEntry + ", " + lle.getMessage(); LOG.error( message ); throw new ConfigurationException( message ); } } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/transform/InstanceTargetMarshaller.java
3905
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codedeploy.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.codedeploy.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * InstanceTargetMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class InstanceTargetMarshaller { private static final MarshallingInfo<String> DEPLOYMENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentId").build(); private static final MarshallingInfo<String> TARGETID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("targetId").build(); private static final MarshallingInfo<String> TARGETARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("targetArn").build(); private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("status").build(); private static final MarshallingInfo<java.util.Date> LASTUPDATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastUpdatedAt").timestampFormat("unixTimestamp").build(); private static final MarshallingInfo<List> LIFECYCLEEVENTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lifecycleEvents").build(); private static final MarshallingInfo<String> INSTANCELABEL_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("instanceLabel").build(); private static final InstanceTargetMarshaller instance = new InstanceTargetMarshaller(); public static InstanceTargetMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(InstanceTarget instanceTarget, ProtocolMarshaller protocolMarshaller) { if (instanceTarget == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instanceTarget.getDeploymentId(), DEPLOYMENTID_BINDING); protocolMarshaller.marshall(instanceTarget.getTargetId(), TARGETID_BINDING); protocolMarshaller.marshall(instanceTarget.getTargetArn(), TARGETARN_BINDING); protocolMarshaller.marshall(instanceTarget.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(instanceTarget.getLastUpdatedAt(), LASTUPDATEDAT_BINDING); protocolMarshaller.marshall(instanceTarget.getLifecycleEvents(), LIFECYCLEEVENTS_BINDING); protocolMarshaller.marshall(instanceTarget.getInstanceLabel(), INSTANCELABEL_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
KoriSamui/PlayN
flash/src/playn/flash/FlashCanvas.java
14352
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.flash; import flash.display.BitmapData; import flash.gwt.FlashImport; import com.google.gwt.core.client.JavaScriptObject; import pythagoras.f.MathUtil; import playn.core.Asserts; import playn.core.Canvas; import playn.core.Gradient; import playn.core.Image; import playn.core.Path; import playn.core.Pattern; import playn.core.TextLayout; class FlashCanvas implements Canvas { @FlashImport({"com.googlecode.flashcanvas.CanvasRenderingContext2D"}) final static class Context2d extends JavaScriptObject { public native void setGlobalCompositeOperation(String composite) /*-{ this.globalCompositeOperation = composite; }-*/; public native void arc(float x, float y, float radius, float sa, float ea, boolean anticlockwise) /*-{ this.arc(x, y, radius, sa, ea, anticlockwise); }-*/; public native void setStrokeWidth(float w) /*-{ this.lineWidth = w; }-*/; /** * Enum for text baseline style. */ public enum TextBaseline { ALPHABETIC("alphabetic"), BOTTOM("bottom"), HANGING("hanging"), IDEOGRAPHIC("ideographic"), MIDDLE("middle"), TOP("top"); private final String value; private TextBaseline(String value) { this.value = value; } public String getValue() { return value; } } protected Context2d() {} public native void resize(int x, int y) /*-{ this.resize(x,y); }-*/; public native void beginPath() /*-{ this.beginPath(); }-*/; public native void moveTo(double x, double y) /*-{ this.moveTo(x, y); }-*/; public native void lineTo(double x, double y) /*-{ this.lineTo(x, y); }-*/; public native void stroke() /*-{ this.stroke(); }-*/; public native void clip() /*-{ this.clip(); }-*/; public native void setGlobalAlpha(float alpha) /*-{ this.globalAlpha = alpha; }-*/; public native void setStrokeStyle(String color) /*-{ this.strokeStyle = color; }-*/; public native void setFillStyle(String color) /*-{ this.fillStyle = color; }-*/; /** * @param bitmapData * @param x * @param y */ public native void drawImage(BitmapData bitmapData, float x, float y) /*-{ this._renderImage(bitmapData, [x, y]); }-*/; public native void drawImage(BitmapData bitmapData, float x, float y, float w, float h) /*-{ this._renderImage(bitmapData, [x, y, w, h]); }-*/; public native void drawImage(BitmapData bitmapData, float x, float y, float w, float h, float sx, float sy, float sw, float sh) /*-{ this._renderImage(bitmapData, [sx, sy, sw, sh, x, y, w, h]); }-*/; /** * */ public native void restore() /*-{ this.restore(); }-*/; public native void save() /*-{ this.save(); }-*/; /** * @param radians */ public native void rotate(float radians) /*-{ // TODO Auto-generated method stub this.rotate(radians); }-*/; public native void scale(float sx, float sy) /*-{ // TODO Auto-generated method stub this.scale(sx, sy); }-*/; public native void translate(float tx, float ty) /*-{ // TODO Auto-generated method stub this.translate(tx, ty); }-*/; /** * @param m11 * @param m12 * @param m21 * @param m22 * @param dx * @param dy */ public native void transform(float m11, float m12, float m21, float m22, float dx, float dy) /*-{ // TODO Auto-generated method stub this.transform(m11, m12, m21, m22, dx, dy); }-*/; public native void setTransform(float m11, float m12, float m21, float m22, float dx, float dy) /*-{ // TODO Auto-generated method stub this.setTransform(m11, m12, m21, m22, dx, dy); }-*/; public native void fillText(String text, float x, float y) /*-{ this.fillText(text, x, y); }-*/; public native void rect(float x, float y, float w, float h) /*-{ this.rect(x, y, w, h); }-*/; public native void fillRect(float x, float y, float w, float h) /*-{ this.fillRect(x, y, w, h); }-*/; public native void strokeText(String text, float x, float y) /*-{ this.strokeText(text, x, y); }-*/; public native void arcTo(double curX, double curY, double x, double y, double radius) /*-{ this.arcTo(curX, curY, x, y, radius); }-*/; public native void bezierCurveTo(double c1x, double c1y, double c2x, double c2y, double x, double y) /*-{ this.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); }-*/; public native void quadraticCurveTo( double cpx, double cpy, double x, double y) /*-{ this.quadraticCurveTo(cpx, cpy, x, y); }-*/; public native void closePath() /*-{ this.closePath(); }-*/; public native void fill() /*-{ this.fill(); }-*/; public native void strokeRect(float x, float y, float w, float h) /*-{ this.strokeRect(x, y, w, h); }-*/; public native BitmapData bitmapData() /*-{ return this.canvas.bitmapData; }-*/; public native void clearRect(int x, int y, int width, int height) /*-{ this.clearRect(x, y, width, height); }-*/; public native void setLineWidth(float width) /*-{ this.lineWidth = width; }-*/; public native void setTextBaseline(String baseline) /*-{ this.textBaseline = baseline; }-*/; public native void setFont(String font) /*-{ this.font = font; }-*/; final static class Measure extends JavaScriptObject { protected Measure(){} public native int getWidth() /*-{ return this.width; }-*/; public native int getHeight() /*-{ return this.height-4; }-*/; } public native Measure measureText(String line) /*-{ return this.measureText(line); }-*/; } @FlashImport({"com.googlecode.flashcanvas.Canvas"}) final static class CanvasElement extends JavaScriptObject { protected CanvasElement() {} public static native CanvasElement create() /*-{ return new com.googlecode.flashcanvas.Canvas(); }-*/; public static native CanvasElement create(int width, int height) /*-{ return new com.googlecode.flashcanvas.Canvas(width, height); }-*/; public final native Context2d getContext() /*-{ return this.getContext("2d"); }-*/; } private final float width, height; private boolean dirty = true; private final Context2d context2d; FlashCanvas(float width, float height, Context2d context2d) { this.width = width; this.height = height; this.context2d = context2d; } @Override public Canvas clear() { context2d.clearRect(0, 0, MathUtil.iceil(width), MathUtil.iceil(height)); dirty = true; return this; } @Override public Canvas clearRect(float x, float y, float width, float height) { context2d.clearRect(MathUtil.ifloor(x), MathUtil.ifloor(y), MathUtil.iceil(width), MathUtil.iceil(height)); dirty = true; return this; } @Override public Canvas clip(Path path) { return this; } @Override public Path createPath() { return new FlashPath(); } @Override public Canvas drawImage(Image img, float x, float y) { Asserts.checkArgument(img instanceof FlashImage); dirty = true; context2d.drawImage(((FlashImage) img).bitmapData(), x, y); return this; } @Override public Canvas drawImage(Image img, float x, float y, float w, float h) { Asserts.checkArgument(img instanceof FlashImage); context2d.drawImage(((FlashImage) img).bitmapData(), x, y, w, h); dirty = true; return this; } @Override public Canvas drawImage(Image img, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh) { Asserts.checkArgument(img instanceof FlashImage); dirty = true; context2d.drawImage(((FlashImage) img).bitmapData(), dx, dy, dw, dh, sx, sy, sw, sh); return this; } @Override public Canvas drawImageCentered(Image img, float x, float y) { drawImage(img, x - img.width()/2, y - img.height()/2); dirty = true; return this; } @Override public Canvas drawLine(float x0, float y0, float x1, float y1) { context2d.beginPath(); context2d.moveTo(x0, y0); context2d.lineTo(x1, y1); context2d.stroke(); dirty = true; return this; } @Override public Canvas drawPoint(float x, float y) { context2d.fillRect(x, y, 1, 1); dirty = true; return this; } @Override public Canvas fillRoundRect(float x, float y, float w, float h, float radius) { addRoundRectPath(x, y, w, h, radius); context2d.fill(); dirty = true; return this; } @Override public Canvas fillText(TextLayout layout, float x, float y) { ((FlashTextLayout) layout).fill(context2d, x, y); dirty = true; return this; } @Override public Canvas drawText(String text, float x, float y) { context2d.strokeText(text, x, y); context2d.fillText(text, x, y); dirty = true; return this; } @Override public Canvas fillCircle(float x, float y, float radius) { dirty = true; context2d.beginPath(); context2d.arc(x, y, radius, 0, (float) (Math.PI*2), true); context2d.closePath(); context2d.fill(); return this; } @Override public Canvas fillPath(Path path) { ((FlashPath) path).replay(context2d); context2d.fill(); dirty = true; return this; } @Override public Canvas fillRect(float x, float y, float w, float h) { context2d.fillRect(x, y, w, h); dirty = true; return this; } @Override public final float height() { return height; } @Override public Canvas restore() { context2d.restore(); return this; } @Override public Canvas rotate(float radians) { context2d.rotate(radians); return this; } @Override public Canvas save() { context2d.save(); return this; } @Override public Canvas scale(float x, float y) { context2d.scale(x, y); return this; } @Override public Canvas setAlpha(float alpha) { context2d.setGlobalAlpha(alpha); return this; } @Override public Canvas setCompositeOperation(Composite composite) { context2d.setGlobalCompositeOperation(composite.name().toLowerCase().replace('_', '-')); return this; } @Override public Canvas setFillColor(int color) { context2d.setFillStyle(FlashGraphics.cssColorString(color)); return this; } @Override public Canvas setFillGradient(Gradient gradient) { return this; } @Override public Canvas setFillPattern(Pattern pattern) { return this; } @Override public Canvas setLineCap(LineCap cap) { return this; } @Override public Canvas setLineJoin(LineJoin join) { return this; } @Override public Canvas setMiterLimit(float miter) { return this; } @Override public Canvas setStrokeColor(int color) { context2d.setStrokeStyle(FlashGraphics.cssColorString(color)); return this; } @Override public Canvas setStrokeWidth(float w) { context2d.setStrokeWidth(w); return this; } @Deprecated @Override public Canvas setTransform(float m11, float m12, float m21, float m22, float dx, float dy) { context2d.setTransform(m11, m12, m21, m22, dx, dy); return this; } @Override public Canvas strokeCircle(float x, float y, float radius) { dirty = true; return this; } @Override public Canvas strokePath(Path path) { ((FlashPath) path).replay(context2d); context2d.stroke(); dirty = true; return this; } @Override public Canvas strokeRect(float x, float y, float w, float h) { context2d.strokeRect(x, y, w, h); dirty = true; return this; } @Override public Canvas strokeRoundRect(float x, float y, float w, float h, float radius) { addRoundRectPath(x, y, w, h, radius); context2d.stroke(); dirty = true; return this; } @Override public Canvas strokeText(TextLayout layout, float x, float y) { ((FlashTextLayout) layout).stroke(context2d, x, y); dirty = true; return this; } @Override public Canvas transform(float m11, float m12, float m21, float m22, float dx, float dy) { context2d.transform(m11, m12, m21, m22, dx, dy); return this; } @Override public Canvas translate(float x, float y) { context2d.translate(x, y); return this; } @Override public final float width() { return width; } public void quadraticCurveTo(float cpx, float cpy, float x, float y) { context2d.quadraticCurveTo(cpx, cpy, x, y); } public void lineTo(float x, float y) { context2d.lineTo(x, y); } public void moveTo(float x, float y) { context2d.moveTo((int) x, (int) y); } public void close() { context2d.closePath(); } public BitmapData bitmapData() { return context2d.bitmapData(); } public Context2d getContext2d() { return context2d; } void clearDirty() { dirty = false; } boolean dirty() { return dirty; } private void addRoundRectPath(float x, float y, float width, float height, float radius) { float midx = x + width/2, midy = y + height/2, maxx = x + width, maxy = y + height; context2d.beginPath(); context2d.moveTo(x, midy); context2d.arcTo(x, y, midx, y, radius); context2d.arcTo(maxx, y, maxx, midy, radius); context2d.arcTo(maxx, maxy, midx, maxy, radius); context2d.arcTo(x, maxy, x, midy, radius); context2d.closePath(); } }
apache-2.0
lessthanoptimal/BoofCV
main/boofcv-geo/src/test/java/boofcv/alg/distort/TestFlipVertical_F64.java
1219
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.distort; import boofcv.testing.BoofStandardJUnit; import georegression.struct.point.Point2D_F64; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Peter Abeles */ public class TestFlipVertical_F64 extends BoofStandardJUnit { @Test void basicTest() { FlipVertical_F64 alg = new FlipVertical_F64(100); Point2D_F64 found = new Point2D_F64(); alg.compute(20,30,found); assertEquals(20,found.x,1e-8); assertEquals(100 - 30 - 1, found.y, 1e-8); } }
apache-2.0
MaDaPHaKa/Orient-object
server/src/main/java/com/orientechnologies/orient/server/replication/OReplicatorRecordHook.java
3423
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.server.replication; import java.io.IOException; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseComplex; import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; import com.orientechnologies.orient.core.db.record.ORecordOperation; import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.server.network.protocol.distributed.ODistributedRequesterThreadLocal; /** * Record hook implementation. Catches all the relevant events and propagates to the other cluster nodes. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) */ public class OReplicatorRecordHook implements ORecordHook, ODatabaseLifecycleListener { private OReplicator replicator; /** * Auto install itself as lifecycle listener for databases. */ public OReplicatorRecordHook(final OReplicator iReplicator) { replicator = iReplicator; Orient.instance().addDbLifecycleListener(this); } @Override public boolean onTrigger(final TYPE iType, final ORecord<?> iRecord) { if (ODistributedRequesterThreadLocal.INSTANCE.get()) // REPLICATED RECORD, AVOID TO PROPAGATE IT AGAIN return false; if (iRecord instanceof ODocument && replicator.isIgnoredDocumentClass(((ODocument) iRecord).getClassName())) // AVOID TO REPLICATE THE CONFLICT return false; try { switch (iType) { case AFTER_CREATE: replicator.distributeRequest(new ORecordOperation((ORecordInternal<?>) iRecord, ORecordOperation.CREATED)); break; case AFTER_UPDATE: replicator.distributeRequest(new ORecordOperation((ORecordInternal<?>) iRecord, ORecordOperation.UPDATED)); break; case AFTER_DELETE: replicator.distributeRequest(new ORecordOperation((ORecordInternal<?>) iRecord, ORecordOperation.DELETED)); break; } } catch (IOException e) { throw new ODistributedSynchronizationException("Error on distribution of the record to the configured cluster", e); } return false; } /** * Install the itself as trigger to catch all the events against records */ @Override public void onOpen(final ODatabase iDatabase) { ((ODatabaseComplex<?>) iDatabase).registerHook(this); } /** * Remove itself as trigger to catch all the events against records */ @Override public void onClose(final ODatabase iDatabase) { ((ODatabaseComplex<?>) iDatabase).unregisterHook(this); } }
apache-2.0
dumoulma/kmeans-mr
src/main/java/ca/ulaval/ift/graal/utils/Util.java
1583
package ca.ulaval.ift.graal.utils; import java.io.IOException; import java.math.BigDecimal; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.mahout.math.VectorWritable; public final class Util { public static double round(double unrounded, int precision) { BigDecimal bd = new BigDecimal(unrounded); BigDecimal rounded = bd.setScale(precision, BigDecimal.ROUND_HALF_EVEN); return rounded.doubleValue(); } public static void showClusters(Configuration conf, Path resultPath) throws IOException { FileSystem fs = FileSystem.get(conf); FileStatus[] outputFileList = fs.listStatus(resultPath); for (FileStatus status : outputFileList) { if (!status.isDir()) { Path path = status.getPath(); if (!path.getName().equals("_SUCCESS")) { System.out.println("FOUND " + path.toString()); try (SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf)) { IntWritable key = new IntWritable(); VectorWritable v = new VectorWritable(); while (reader.next(key, v)) { System.out.println(key + " / " + v); } } } } } } private Util() { } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/core/portal/dao/PortletDaoImpl.java
6838
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.core.portal.dao; import com.tle.common.Check; import com.tle.common.institution.CurrentInstitution; import com.tle.common.portal.entity.Portlet; import com.tle.core.entity.dao.impl.AbstractEntityDaoImpl; import com.tle.core.guice.Bind; import com.tle.core.portal.service.PortletSearch; import java.util.List; import javax.inject.Singleton; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; /** @author aholland */ @Singleton @Bind(PortletDao.class) @SuppressWarnings("nls") public class PortletDaoImpl extends AbstractEntityDaoImpl<Portlet> implements PortletDao { public PortletDaoImpl() { super(Portlet.class); } @Override @SuppressWarnings("unchecked") public List<Portlet> getForUser(final String userId) { List<Portlet> res = (List<Portlet>) getHibernateTemplate() .execute( new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException { Query query = session.createQuery( "FROM Portlet WHERE" + " (owner = :owner OR institutional = :institutional)" + " AND enabled = :enabled AND institution = :institution ORDER BY dateCreated"); query.setCacheable(true); query.setParameter("owner", userId); query.setParameter("institutional", true); query.setParameter("enabled", true); query.setParameter("institution", CurrentInstitution.get()); return query.list(); } }); return res; } @Override public List<Portlet> search(PortletSearch search, int offset, int perPage) { return enumerateAll( new PortletSearchListCallback( search.getQuery(), offset, perPage, search.getOwner(), search.getType(), search.isOnlyInstWide())); } protected static class PortletSearchListCallback extends DefaultSearchListCallback { private final String owner; private final String type; private final Boolean onlyInstWide; public PortletSearchListCallback( String freetext, int offset, int max, String owner, String type, Boolean onlyInstWide) { super(new EnabledCallback(new PagedListCallback(null, offset, max), null), freetext); this.owner = owner; this.type = type; this.onlyInstWide = onlyInstWide; } @Override public String createAdditionalWhere() { String finalWhere = super.createAdditionalWhere(); if (!Check.isEmpty(owner)) { finalWhere = concat(finalWhere, "owner = :owner", " AND "); } if (!Check.isEmpty(type)) { finalWhere = concat(finalWhere, "type = :type", " AND "); } if (onlyInstWide != null) { finalWhere = concat(finalWhere, "institutional = :institutional", " AND "); } return finalWhere; } @Override public void processQuery(Query query) { super.processQuery(query); if (freetext != null) { query.setParameter("freetext", freetext); } if (!Check.isEmpty(owner)) { query.setParameter("owner", owner); } if (!Check.isEmpty(type)) { query.setParameter("type", type); } if (onlyInstWide != null) { query.setParameter("institutional", onlyInstWide); } } } private long count(final ListCallback callback) { return ((Number) getHibernateTemplate() .execute( new TLEHibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException { StringBuilder hql = new StringBuilder(); hql.append("SELECT "); if (callback != null && callback.isDistinct()) { hql.append("DISTINCT "); } hql.append("count(be) FROM "); hql.append(getPersistentClass().getName()); hql.append(" be "); if (callback != null && callback.getAdditionalJoins() != null) { hql.append(" "); hql.append(callback.getAdditionalJoins()); hql.append(" "); } hql.append("WHERE be.institution = :institution"); if (callback != null && callback.getAdditionalWhere() != null) { hql.append(" AND "); hql.append(callback.getAdditionalWhere()); } if (callback != null && callback.getOrderBy() != null) { hql.append(" ORDER BY " + callback.getOrderBy()); } Query query = session.createQuery(hql.toString()); query.setParameter("institution", CurrentInstitution.get()); query.setCacheable(true); query.setReadOnly(true); if (callback != null) { callback.processQuery(query); } return query.uniqueResult(); } })) .longValue(); } @Override public long count(PortletSearch search) { return count( new PortletSearchListCallback( search.getQuery(), -1, -1, search.getOwner(), search.getType(), search.isOnlyInstWide())); } }
apache-2.0
izbrannick/Radio
mobile/src/main/java/dk/glutter/android/knr/ui/PlaybackControlsFragment.java
11615
/* * Copyright (C) 2014 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 dk.glutter.android.knr.ui; import android.app.Fragment; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import dk.glutter.android.knr.AlbumArtCache; import dk.glutter.android.knr.MusicService; import dk.glutter.android.knr.R; import dk.glutter.android.knr.utils.LogHelper; /** * A class that shows the Media Queue to the user. */ public class PlaybackControlsFragment extends Fragment { private static final String TAG = LogHelper.makeLogTag(PlaybackControlsFragment.class); private ImageButton mPlayPause; private TextView mTitle; private TextView mSubtitle; private TextView mExtraInfo; private ImageView mAlbumArt; private String mArtUrl; // Receive callbacks from the MediaController. Here we update our state such as which queue // is being shown, the current title and description and the PlaybackState. private final MediaControllerCompat.Callback mCallback = new MediaControllerCompat.Callback() { @Override public void onPlaybackStateChanged(@NonNull PlaybackStateCompat state) { LogHelper.d(TAG, "Received playback state change to state ", state.getState()); PlaybackControlsFragment.this.onPlaybackStateChanged(state); } @Override public void onMetadataChanged(MediaMetadataCompat metadata) { if (metadata == null) { return; } LogHelper.d(TAG, "Received metadata state change to mediaId=", metadata.getDescription().getMediaId(), " song=", metadata.getDescription().getTitle()); PlaybackControlsFragment.this.onMetadataChanged(metadata); } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_playback_controls, container, false); mPlayPause = (ImageButton) rootView.findViewById(R.id.play_pause); mPlayPause.setEnabled(true); mPlayPause.setOnClickListener(mButtonListener); mTitle = (TextView) rootView.findViewById(R.id.title); mSubtitle = (TextView) rootView.findViewById(R.id.artist); mExtraInfo = (TextView) rootView.findViewById(R.id.extra_info); mAlbumArt = (ImageView) rootView.findViewById(R.id.album_art); rootView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), FullScreenPlayerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); MediaMetadataCompat metadata = controller.getMetadata(); if (metadata != null) { intent.putExtra(MusicPlayerActivity.EXTRA_CURRENT_MEDIA_DESCRIPTION, metadata.getDescription()); } startActivity(intent); } }); return rootView; } @Override public void onStart() { super.onStart(); LogHelper.d(TAG, "fragment.onStart"); MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); if (controller != null) { onConnected(); } } @Override public void onStop() { super.onStop(); LogHelper.d(TAG, "fragment.onStop"); MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); if (controller != null) { controller.unregisterCallback(mCallback); } } public void onConnected() { MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); LogHelper.d(TAG, "onConnected, mediaController==null? ", controller == null); if (controller != null) { onMetadataChanged(controller.getMetadata()); onPlaybackStateChanged(controller.getPlaybackState()); controller.registerCallback(mCallback); } } private void onMetadataChanged(MediaMetadataCompat metadata) { LogHelper.d(TAG, "onMetadataChanged ", metadata); if (getActivity() == null) { LogHelper.w(TAG, "onMetadataChanged called when getActivity null," + "this should not happen if the callback was properly unregistered. Ignoring."); return; } if (metadata == null) { return; } mTitle.setText(metadata.getDescription().getTitle()); mSubtitle.setText(metadata.getDescription().getSubtitle()); String artUrl = null; if (metadata.getDescription().getIconUri() != null) { artUrl = metadata.getDescription().getIconUri().toString(); } if (!TextUtils.equals(artUrl, mArtUrl)) { mArtUrl = artUrl; Bitmap art = metadata.getDescription().getIconBitmap(); AlbumArtCache cache = AlbumArtCache.getInstance(); if (art == null) { art = cache.getIconImage(mArtUrl); } if (art != null) { mAlbumArt.setImageBitmap(art); } else { cache.fetch(artUrl, new AlbumArtCache.FetchListener() { @Override public void onError(String artUrl, Exception e) { Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.bg); mAlbumArt.setImageBitmap(image); } @Override public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) { if (icon != null) { LogHelper.d(TAG, "album art icon of w=", icon.getWidth(), " h=", icon.getHeight()); if (isAdded()) { mAlbumArt.setImageBitmap(icon); } } } } ); } } } public void setExtraInfo(String extraInfo) { if (extraInfo == null) { mExtraInfo.setVisibility(View.GONE); } else { mExtraInfo.setText(extraInfo); mExtraInfo.setVisibility(View.VISIBLE); } } private void onPlaybackStateChanged(PlaybackStateCompat state) { LogHelper.d(TAG, "onPlaybackStateChanged ", state); if (getActivity() == null) { LogHelper.w(TAG, "onPlaybackStateChanged called when getActivity null," + "this should not happen if the callback was properly unregistered. Ignoring."); return; } if (state == null) { return; } boolean enablePlay = false; switch (state.getState()) { case PlaybackStateCompat.STATE_PAUSED: case PlaybackStateCompat.STATE_STOPPED: enablePlay = true; break; case PlaybackStateCompat.STATE_ERROR: LogHelper.e(TAG, "error playbackstate: ", state.getErrorMessage()); Toast.makeText(getActivity(), state.getErrorMessage(), Toast.LENGTH_LONG).show(); break; } if (enablePlay) { mPlayPause.setImageDrawable( ContextCompat.getDrawable(getActivity(), R.drawable.ic_play_arrow_black_36dp)); } else { mPlayPause.setImageDrawable( ContextCompat.getDrawable(getActivity(), R.drawable.ic_pause_black_36dp)); } MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); String extraInfo = null; if (controller != null && controller.getExtras() != null) { String castName = controller.getExtras().getString(MusicService.EXTRA_CONNECTED_CAST); if (castName != null) { extraInfo = getResources().getString(R.string.casting_to_device, castName); } } setExtraInfo(extraInfo); } private final View.OnClickListener mButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); PlaybackStateCompat stateObj = controller.getPlaybackState(); final int state = stateObj == null ? PlaybackStateCompat.STATE_NONE : stateObj.getState(); LogHelper.d(TAG, "Button pressed, in state " + state); switch (v.getId()) { case R.id.play_pause: LogHelper.d(TAG, "Play button pressed, in state " + state); if (state == PlaybackStateCompat.STATE_PAUSED || state == PlaybackStateCompat.STATE_STOPPED || state == PlaybackStateCompat.STATE_NONE) { playMedia(); } else if (state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_BUFFERING || state == PlaybackStateCompat.STATE_CONNECTING) { pauseMedia(); } break; } } }; private void playMedia() { MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); if (controller != null) { controller.getTransportControls().play(); } } private void pauseMedia() { MediaControllerCompat controller = ((FragmentActivity) getActivity()) .getSupportMediaController(); if (controller != null) { controller.getTransportControls().pause(); } } }
apache-2.0
masonmei/apm-agent
profiler/src/main/java/com/baidu/oped/apm/profiler/sender/TcpDataSender.java
9044
/* * Copyright 2014 NAVER Corp. * * 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.baidu.oped.apm.profiler.sender; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.thrift.TBase; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baidu.oped.apm.rpc.Future; import com.baidu.oped.apm.rpc.FutureListener; import com.baidu.oped.apm.rpc.ResponseMessage; import com.baidu.oped.apm.rpc.client.PinpointSocket; import com.baidu.oped.apm.rpc.client.PinpointSocketReconnectEventListener; import com.baidu.oped.apm.rpc.util.TimerFactory; import com.baidu.oped.apm.thrift.dto.TResult; import com.baidu.oped.apm.thrift.io.HeaderTBaseDeserializer; import com.baidu.oped.apm.thrift.io.HeaderTBaseDeserializerFactory; import com.baidu.oped.apm.thrift.io.HeaderTBaseSerializer; import com.baidu.oped.apm.thrift.io.HeaderTBaseSerializerFactory; /** * @author emeroad * @author koo.taejin * @author netspider */ public class TcpDataSender extends AbstractDataSender implements EnhancedDataSender { private final Logger logger = LoggerFactory.getLogger(this.getClass()); static { // preClassLoad ChannelBuffers.buffer(2); } private final PinpointSocket socket; private final Timer timer; private final AtomicBoolean fireState = new AtomicBoolean(false); private final WriteFailFutureListener writeFailFutureListener; private final HeaderTBaseSerializer serializer = HeaderTBaseSerializerFactory.DEFAULT_FACTORY.createSerializer(); private final RetryQueue retryQueue = new RetryQueue(); private AsyncQueueingExecutor<Object> executor; public TcpDataSender(PinpointSocket socket) { this.socket = socket; this.timer = createTimer(); writeFailFutureListener = new WriteFailFutureListener(logger, "io write fail.", "host", -1); this.executor = createAsyncQueueingExecutor(1024 * 5, "Pinpoint-TcpDataExecutor"); } private Timer createTimer() { HashedWheelTimer timer = TimerFactory.createHashedWheelTimer("Pinpoint-DataSender-Timer", 100, TimeUnit.MILLISECONDS, 512); timer.start(); return timer; } @Override public boolean send(TBase<?, ?> data) { return executor.execute(data); } @Override public boolean request(TBase<?, ?> data) { return this.request(data, 3); } @Override public boolean request(TBase<?, ?> data, int retryCount) { RequestMarker message = new RequestMarker(data, retryCount); return executor.execute(message); } @Override public boolean request(TBase<?, ?> data, FutureListener<ResponseMessage> listener) { RequestMarker message = new RequestMarker(data, listener); return executor.execute(message); } @Override public boolean addReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { return this.socket.addPinpointSocketReconnectEventListener(eventListener); } @Override public boolean removeReconnectEventListener(PinpointSocketReconnectEventListener eventListener) { return this.socket.removePinpointSocketReconnectEventListener(eventListener); } @Override public void stop() { executor.stop(); Set<Timeout> stop = timer.stop(); if (!stop.isEmpty()) { logger.info("stop Timeout:{}", stop.size()); } } @Override protected void sendPacket(Object message) { try { if (message instanceof TBase) { byte[] copy = serialize(serializer, (TBase) message); if (copy == null) { return; } doSend(copy); } else if (message instanceof RequestMarker) { RequestMarker requestMarker = (RequestMarker) message; TBase tBase = requestMarker.getTBase(); int retryCount = requestMarker.getRetryCount(); FutureListener futureListener = requestMarker.getFutureListener(); byte[] copy = serialize(serializer, tBase); if (copy == null) { return; } if (futureListener != null) { doRequest(copy, futureListener); } else { doRequest(copy, retryCount, tBase); } } else { logger.error("sendPacket fail. invalid dto type:{}", message.getClass()); return; } } catch (Exception e) { logger.warn("tcp send fail. Caused:{}", e.getMessage(), e); } } private void doSend(byte[] copy) { Future write = this.socket.sendAsync(copy); write.setListener(writeFailFutureListener); } private void doRequest(final byte[] requestPacket, final int retryCount, final Object targetClass) { FutureListener futureListner = (new FutureListener<ResponseMessage>() { @Override public void onComplete(Future<ResponseMessage> future) { if (future.isSuccess()) { // Should cache? HeaderTBaseDeserializer deserializer = HeaderTBaseDeserializerFactory.DEFAULT_FACTORY.createDeserializer(); TBase<?, ?> response = deserialize(deserializer, future.getResult()); if (response instanceof TResult) { TResult result = (TResult) response; if (result.isSuccess()) { logger.debug("result success"); } else { logger.warn("request fail. clazz:{} Caused:{}", targetClass, result.getMessage()); retryRequest(requestPacket, retryCount, targetClass.getClass().getSimpleName()); } } else { logger.warn("Invalid ResponseMessage. {}", response); // This is not retransmission. need to log for debugging // it could be null // retryRequest(requestPacket); } } else { logger.warn("request fail. clazz:{} Caused:{}", targetClass, future.getCause().getMessage(), future.getCause()); retryRequest(requestPacket, retryCount, targetClass.getClass().getSimpleName()); } } }); doRequest(requestPacket, futureListner); } private void retryRequest(byte[] requestPacket, int retryCount, final String className) { RetryMessage retryMessage = new RetryMessage(retryCount, requestPacket); retryQueue.add(retryMessage); if (fireTimeout()) { timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { while(true) { RetryMessage retryMessage = retryQueue.get(); if (retryMessage == null) { // Maybe concurrency issue. But ignore it because it's unlikely. fireComplete(); return; } int fail = retryMessage.fail(); doRequest(retryMessage.getBytes(), fail, className); } } }, 1000 * 10, TimeUnit.MILLISECONDS); } } private void doRequest(final byte[] requestPacket, FutureListener futureListener) { final Future<ResponseMessage> response = this.socket.request(requestPacket); response.setListener(futureListener); } private boolean fireTimeout() { if (fireState.compareAndSet(false, true)) { return true; } else { return false; } } private void fireComplete() { logger.debug("fireComplete"); fireState.compareAndSet(true, false); } @Override public boolean isNetworkAvailable() { if (this.socket == null) { return false; } return this.socket.isConnected(); } }
apache-2.0
skekre98/apex-mlhr
demos/wordcount/src/main/java/com/datatorrent/demos/wordcount/ApplicationWithQuerySupport.java
5206
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.demos.wordcount; import java.net.URI; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datatorrent.api.annotation.ApplicationAnnotation; import com.datatorrent.api.StreamingApplication; import com.datatorrent.api.DAG; import com.datatorrent.api.Operator; import com.datatorrent.lib.appdata.schemas.SchemaUtils; import com.datatorrent.lib.appdata.snapshot.AppDataSnapshotServerMap; import com.datatorrent.lib.io.PubSubWebSocketAppDataQuery; import com.datatorrent.lib.io.PubSubWebSocketAppDataResult; import com.datatorrent.lib.io.ConsoleOutputOperator; import org.apache.hadoop.conf.Configuration; @ApplicationAnnotation(name="TopNWordsWithQueries") public class ApplicationWithQuerySupport implements StreamingApplication { private static final Logger LOG = LoggerFactory.getLogger(ApplicationWithQuerySupport.class); public static final String SNAPSHOT_SCHEMA = "WordDataSchema.json"; @Override public void populateDAG(DAG dag, Configuration conf) { // create operators LineReader lineReader = dag.addOperator("lineReader", new LineReader()); WordReader wordReader = dag.addOperator("wordReader", new WordReader()); WindowWordCount windowWordCount = dag.addOperator("windowWordCount", new WindowWordCount()); FileWordCount fileWordCount = dag.addOperator("fileWordCount", new FileWordCount()); WordCountWriter wcWriter = dag.addOperator("wcWriter", new WordCountWriter()); ConsoleOutputOperator console = dag.addOperator("console", new ConsoleOutputOperator()); console.setStringFormat("wordCount: %s"); // create streams dag.addStream("lines", lineReader.output, wordReader.input); dag.addStream("control", lineReader.control, fileWordCount.control); dag.addStream("words", wordReader.output, windowWordCount.input); dag.addStream("windowWordCounts", windowWordCount.output, fileWordCount.input); dag.addStream("fileWordCounts", fileWordCount.fileOutput, wcWriter.input); String gatewayAddress = dag.getValue(DAG.GATEWAY_CONNECT_ADDRESS); if ( ! StringUtils.isEmpty(gatewayAddress)) { // add query support URI uri = URI.create("ws://" + gatewayAddress + "/pubsub"); AppDataSnapshotServerMap snapshotServerFile = dag.addOperator("snapshotServerFile", new AppDataSnapshotServerMap()); AppDataSnapshotServerMap snapshotServerGlobal = dag.addOperator("snapshotServerGlobal", new AppDataSnapshotServerMap()); String snapshotServerJSON = SchemaUtils.jarResourceFileToString(SNAPSHOT_SCHEMA); snapshotServerFile.setSnapshotSchemaJSON(snapshotServerJSON); snapshotServerGlobal.setSnapshotSchemaJSON(snapshotServerJSON); PubSubWebSocketAppDataQuery wsQueryFile = new PubSubWebSocketAppDataQuery(); PubSubWebSocketAppDataQuery wsQueryGlobal = new PubSubWebSocketAppDataQuery(); wsQueryFile.setUri(uri); wsQueryGlobal.setUri(uri); snapshotServerFile.setEmbeddableQueryInfoProvider(wsQueryFile); snapshotServerGlobal.setEmbeddableQueryInfoProvider(wsQueryGlobal); PubSubWebSocketAppDataResult wsResultFile = dag.addOperator("wsResultFile", new PubSubWebSocketAppDataResult()); PubSubWebSocketAppDataResult wsResultGlobal = dag.addOperator("wsResultGlobal", new PubSubWebSocketAppDataResult()); wsResultFile.setUri(uri); wsResultGlobal.setUri(uri); Operator.InputPort<String> queryResultFilePort = wsResultFile.input; Operator.InputPort<String> queryResultGlobalPort = wsResultGlobal.input; dag.addStream("WordCountsFile", fileWordCount.outputPerFile, snapshotServerFile.input, console.input); dag.addStream("WordCountsGlobal", fileWordCount.outputGlobal, snapshotServerGlobal.input); dag.addStream("ResultFile", snapshotServerFile.queryResult, queryResultFilePort); dag.addStream("ResultGlobal", snapshotServerGlobal.queryResult, queryResultGlobalPort); } else { //throw new RuntimeException("Error: No GATEWAY_CONNECT_ADDRESS"); dag.addStream("WordCounts", fileWordCount.outputPerFile, console.input); } System.out.println("done with populateDAG, isDebugEnabled = " + LOG.isDebugEnabled()); LOG.info("Returning from populateDAG"); } }
apache-2.0
troels/nz-presto
presto-main/src/main/java/com/facebook/presto/operator/TaskStats.java
15006
/* * 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.facebook.presto.operator; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.joda.time.DateTime; import javax.annotation.Nullable; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static io.airlift.units.DataSize.Unit.BYTE; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class TaskStats { private final DateTime createTime; private final DateTime firstStartTime; private final DateTime lastStartTime; private final DateTime lastEndTime; private final DateTime endTime; private final Duration elapsedTime; private final Duration queuedTime; private final int totalDrivers; private final int queuedDrivers; private final int queuedPartitionedDrivers; private final int runningDrivers; private final int runningPartitionedDrivers; private final int blockedDrivers; private final int completedDrivers; private final double cumulativeMemory; private final DataSize memoryReservation; private final DataSize revocableMemoryReservation; private final DataSize systemMemoryReservation; private final Duration totalScheduledTime; private final Duration totalCpuTime; private final Duration totalUserTime; private final Duration totalBlockedTime; private final boolean fullyBlocked; private final Set<BlockedReason> blockedReasons; private final DataSize rawInputDataSize; private final long rawInputPositions; private final DataSize processedInputDataSize; private final long processedInputPositions; private final DataSize outputDataSize; private final long outputPositions; private final DataSize spilledDataSize; private final List<PipelineStats> pipelines; public TaskStats(DateTime createTime, DateTime endTime) { this(createTime, null, null, null, endTime, new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), 0, 0, 0, 0, 0, 0, 0, 0.0, new DataSize(0, BYTE), new DataSize(0, BYTE), new DataSize(0, BYTE), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), false, ImmutableSet.of(), new DataSize(0, BYTE), 0, new DataSize(0, BYTE), 0, new DataSize(0, BYTE), 0, new DataSize(0, BYTE), ImmutableList.of()); } @JsonCreator public TaskStats( @JsonProperty("createTime") DateTime createTime, @JsonProperty("firstStartTime") DateTime firstStartTime, @JsonProperty("lastStartTime") DateTime lastStartTime, @JsonProperty("lastEndTime") DateTime lastEndTime, @JsonProperty("endTime") DateTime endTime, @JsonProperty("elapsedTime") Duration elapsedTime, @JsonProperty("queuedTime") Duration queuedTime, @JsonProperty("totalDrivers") int totalDrivers, @JsonProperty("queuedDrivers") int queuedDrivers, @JsonProperty("queuedPartitionedDrivers") int queuedPartitionedDrivers, @JsonProperty("runningDrivers") int runningDrivers, @JsonProperty("runningPartitionedDrivers") int runningPartitionedDrivers, @JsonProperty("blockedDrivers") int blockedDrivers, @JsonProperty("completedDrivers") int completedDrivers, @JsonProperty("cumulativeMemory") double cumulativeMemory, @JsonProperty("memoryReservation") DataSize memoryReservation, @JsonProperty("revocableMemoryReservation") DataSize revocableMemoryReservation, @JsonProperty("systemMemoryReservation") DataSize systemMemoryReservation, @JsonProperty("totalScheduledTime") Duration totalScheduledTime, @JsonProperty("totalCpuTime") Duration totalCpuTime, @JsonProperty("totalUserTime") Duration totalUserTime, @JsonProperty("totalBlockedTime") Duration totalBlockedTime, @JsonProperty("fullyBlocked") boolean fullyBlocked, @JsonProperty("blockedReasons") Set<BlockedReason> blockedReasons, @JsonProperty("rawInputDataSize") DataSize rawInputDataSize, @JsonProperty("rawInputPositions") long rawInputPositions, @JsonProperty("processedInputDataSize") DataSize processedInputDataSize, @JsonProperty("processedInputPositions") long processedInputPositions, @JsonProperty("outputDataSize") DataSize outputDataSize, @JsonProperty("outputPositions") long outputPositions, @JsonProperty("spilledDataSize") DataSize spilledDataSize, @JsonProperty("pipelines") List<PipelineStats> pipelines) { this.createTime = requireNonNull(createTime, "createTime is null"); this.firstStartTime = firstStartTime; this.lastStartTime = lastStartTime; this.lastEndTime = lastEndTime; this.endTime = endTime; this.elapsedTime = requireNonNull(elapsedTime, "elapsedTime is null"); this.queuedTime = requireNonNull(queuedTime, "queuedTime is null"); checkArgument(totalDrivers >= 0, "totalDrivers is negative"); this.totalDrivers = totalDrivers; checkArgument(queuedDrivers >= 0, "queuedDrivers is negative"); this.queuedDrivers = queuedDrivers; checkArgument(queuedPartitionedDrivers >= 0, "queuedPartitionedDrivers is negative"); this.queuedPartitionedDrivers = queuedPartitionedDrivers; checkArgument(runningDrivers >= 0, "runningDrivers is negative"); this.runningDrivers = runningDrivers; checkArgument(runningPartitionedDrivers >= 0, "runningPartitionedDrivers is negative"); this.runningPartitionedDrivers = runningPartitionedDrivers; checkArgument(blockedDrivers >= 0, "blockedDrivers is negative"); this.blockedDrivers = blockedDrivers; checkArgument(completedDrivers >= 0, "completedDrivers is negative"); this.completedDrivers = completedDrivers; this.cumulativeMemory = requireNonNull(cumulativeMemory, "cumulativeMemory is null"); this.memoryReservation = requireNonNull(memoryReservation, "memoryReservation is null"); this.revocableMemoryReservation = requireNonNull(revocableMemoryReservation, "revocableMemoryReservation is null"); this.systemMemoryReservation = requireNonNull(systemMemoryReservation, "systemMemoryReservation is null"); this.totalScheduledTime = requireNonNull(totalScheduledTime, "totalScheduledTime is null"); this.totalCpuTime = requireNonNull(totalCpuTime, "totalCpuTime is null"); this.totalUserTime = requireNonNull(totalUserTime, "totalUserTime is null"); this.totalBlockedTime = requireNonNull(totalBlockedTime, "totalBlockedTime is null"); this.fullyBlocked = fullyBlocked; this.blockedReasons = ImmutableSet.copyOf(requireNonNull(blockedReasons, "blockedReasons is null")); this.rawInputDataSize = requireNonNull(rawInputDataSize, "rawInputDataSize is null"); checkArgument(rawInputPositions >= 0, "rawInputPositions is negative"); this.rawInputPositions = rawInputPositions; this.processedInputDataSize = requireNonNull(processedInputDataSize, "processedInputDataSize is null"); checkArgument(processedInputPositions >= 0, "processedInputPositions is negative"); this.processedInputPositions = processedInputPositions; this.outputDataSize = requireNonNull(outputDataSize, "outputDataSize is null"); checkArgument(outputPositions >= 0, "outputPositions is negative"); this.outputPositions = outputPositions; this.spilledDataSize = requireNonNull(spilledDataSize, "spilledDataSize is null"); this.pipelines = ImmutableList.copyOf(requireNonNull(pipelines, "pipelines is null")); } @JsonProperty public DateTime getCreateTime() { return createTime; } @Nullable @JsonProperty public DateTime getFirstStartTime() { return firstStartTime; } @Nullable @JsonProperty public DateTime getLastStartTime() { return lastStartTime; } @Nullable @JsonProperty public DateTime getLastEndTime() { return lastEndTime; } @Nullable @JsonProperty public DateTime getEndTime() { return endTime; } @JsonProperty public Duration getElapsedTime() { return elapsedTime; } @JsonProperty public Duration getQueuedTime() { return queuedTime; } @JsonProperty public int getTotalDrivers() { return totalDrivers; } @JsonProperty public int getQueuedDrivers() { return queuedDrivers; } @JsonProperty public int getRunningDrivers() { return runningDrivers; } @JsonProperty public int getBlockedDrivers() { return blockedDrivers; } @JsonProperty public int getCompletedDrivers() { return completedDrivers; } @JsonProperty public double getCumulativeMemory() { return cumulativeMemory; } @JsonProperty public DataSize getMemoryReservation() { return memoryReservation; } @JsonProperty public DataSize getRevocableMemoryReservation() { return revocableMemoryReservation; } @JsonProperty public DataSize getSystemMemoryReservation() { return systemMemoryReservation; } @JsonProperty public Duration getTotalScheduledTime() { return totalScheduledTime; } @JsonProperty public Duration getTotalCpuTime() { return totalCpuTime; } @JsonProperty public Duration getTotalUserTime() { return totalUserTime; } @JsonProperty public Duration getTotalBlockedTime() { return totalBlockedTime; } @JsonProperty public boolean isFullyBlocked() { return fullyBlocked; } @JsonProperty public Set<BlockedReason> getBlockedReasons() { return blockedReasons; } @JsonProperty public DataSize getRawInputDataSize() { return rawInputDataSize; } @JsonProperty public long getRawInputPositions() { return rawInputPositions; } @JsonProperty public DataSize getProcessedInputDataSize() { return processedInputDataSize; } @JsonProperty public long getProcessedInputPositions() { return processedInputPositions; } @JsonProperty public DataSize getOutputDataSize() { return outputDataSize; } @JsonProperty public long getOutputPositions() { return outputPositions; } @JsonProperty public DataSize getSpilledDataSize() { return spilledDataSize; } @JsonProperty public List<PipelineStats> getPipelines() { return pipelines; } @JsonProperty public int getQueuedPartitionedDrivers() { return queuedPartitionedDrivers; } @JsonProperty public int getRunningPartitionedDrivers() { return runningPartitionedDrivers; } public TaskStats summarize() { return new TaskStats( createTime, firstStartTime, lastStartTime, lastEndTime, endTime, elapsedTime, queuedTime, totalDrivers, queuedDrivers, queuedPartitionedDrivers, runningDrivers, runningPartitionedDrivers, blockedDrivers, completedDrivers, cumulativeMemory, memoryReservation, revocableMemoryReservation, systemMemoryReservation, totalScheduledTime, totalCpuTime, totalUserTime, totalBlockedTime, fullyBlocked, blockedReasons, rawInputDataSize, rawInputPositions, processedInputDataSize, processedInputPositions, outputDataSize, outputPositions, spilledDataSize, ImmutableList.of()); } public TaskStats summarizeFinal() { return new TaskStats( createTime, firstStartTime, lastStartTime, lastEndTime, endTime, elapsedTime, queuedTime, totalDrivers, queuedDrivers, queuedPartitionedDrivers, runningDrivers, runningPartitionedDrivers, blockedDrivers, completedDrivers, cumulativeMemory, memoryReservation, revocableMemoryReservation, systemMemoryReservation, totalScheduledTime, totalCpuTime, totalUserTime, totalBlockedTime, fullyBlocked, blockedReasons, rawInputDataSize, rawInputPositions, processedInputDataSize, processedInputPositions, outputDataSize, outputPositions, spilledDataSize, pipelines.stream() .map(PipelineStats::summarize) .collect(Collectors.toList())); } }
apache-2.0
yafraorg/yafra-java
org.yafra.server.jee/src/main/java/org/yafra/server/rest/PersonRSI.java
396
package org.yafra.server.rest; import java.util.List; import javax.ws.rs.core.Response; import org.yafra.server.jee.xmlobjects.WSPerson; public interface PersonRSI { List<WSPerson> getPersons(); WSPerson getPerson( String id); Response updateCustomer(WSPerson customer); Response addCustomer(WSPerson customer); Response deleteCustomer( String id); }
apache-2.0
thebillkidy/KdG_IAO301A
JavaWebapps/HelloWorld/src/main/java/com/feedient/IHello.java
124
package com.feedient; /** * Created by xaviergeerinck on 21/11/13. */ public interface IHello { String sayHello(); }
apache-2.0
amoudi87/asterixdb
asterix-om/src/main/java/org/apache/asterix/om/typecomputer/impl/ARectangleTypeComputer.java
1775
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.om.typecomputer.impl; import org.apache.asterix.om.typecomputer.base.IResultTypeComputer; import org.apache.asterix.om.types.BuiltinType; import org.apache.asterix.om.types.IAType; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression; import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.metadata.IMetadataProvider; public class ARectangleTypeComputer implements IResultTypeComputer { public static final ARectangleTypeComputer INSTANCE = new ARectangleTypeComputer(); private ARectangleTypeComputer() { } @Override public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env, IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException { return BuiltinType.ARECTANGLE; } }
apache-2.0
Crocutax/ZhihuDaily
app/src/main/java/com/wangxw/zhihudaily/MyApplication.java
534
package com.wangxw.zhihudaily; import android.app.Application; import android.content.Context; import com.orhanobut.logger.Logger; /** * Created by wangxw on 2017/1/8. * E-mail : wangxw725@163.com * function : */ public class MyApplication extends Application { private static Context mContext; @Override public void onCreate() { super.onCreate(); Logger.init("wxw"); mContext = getApplicationContext(); } public static Context getAppContext(){ return mContext; } }
apache-2.0
Crysty-Yui/smali2java
src/main/java/com/litecoding/smali2java/parser/method/Rule_methodRegisters.java
4185
/* ----------------------------------------------------------------------------- * Rule_methodRegisters.java * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.3 * Produced : Fri Apr 12 10:40:21 MUT 2013 * * ----------------------------------------------------------------------------- */ package com.litecoding.smali2java.parser.method; import java.util.ArrayList; import com.litecoding.smali2java.builder.Visitor; import com.litecoding.smali2java.parser.ParserContext; import com.litecoding.smali2java.parser.Rule; import com.litecoding.smali2java.parser.Terminal_StringValue; import com.litecoding.smali2java.parser.smali.Rule_intValue; import com.litecoding.smali2java.parser.smali.Rule_optPadding; import com.litecoding.smali2java.parser.smali.Rule_padding; import com.litecoding.smali2java.parser.text.Rule_CRLF; final public class Rule_methodRegisters extends Rule { private Rule_methodRegisters(String spelling, ArrayList<Rule> rules) { super(spelling, rules); } public Object accept(Visitor visitor) { return visitor.visit(this); } public static Rule_methodRegisters parse(ParserContext context) { context.push("methodRegisters"); boolean parsed = true; int s0 = context.index; ArrayList<Rule> e0 = new ArrayList<Rule>(); Rule rule; parsed = false; if (!parsed) { { ArrayList<Rule> e1 = new ArrayList<Rule>(); int s1 = context.index; parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_optPadding.parse(context); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Terminal_StringValue.parse(context, ".registers"); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_padding.parse(context); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_intValue.parse(context); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_optPadding.parse(context); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_CRLF.parse(context); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) e0.addAll(e1); else context.index = s1; } } rule = null; if (parsed) rule = new Rule_methodRegisters(context.text.substring(s0, context.index), e0); else context.index = s0; context.pop("methodRegisters", parsed); return (Rule_methodRegisters)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
apache-2.0
doodelicious/cas
support/cas-server-support-couchbase-core/src/main/java/org/apereo/cas/couchbase/core/CouchbaseClientFactory.java
5167
package org.apereo.cas.couchbase.core; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.view.DesignDocument; import com.couchbase.client.java.view.View; import com.google.common.base.Throwables; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * A factory class which produces a client for a particular Couchbase getBucket. * A design consideration was that we want the server to start even if Couchbase * is unavailable, picking up the connection when Couchbase comes online. Hence * the creation of the client is made using a scheduled task which is repeated * until successful connection is made. * * @author Fredrik Jönsson "fjo@kth.se" * @author Misagh Moayyed * @since 4.2 */ public class CouchbaseClientFactory { private static final Logger LOGGER = LoggerFactory.getLogger(CouchbaseClientFactory.class); private static final int DEFAULT_TIMEOUT = 5; private Cluster cluster; private Bucket bucket; private final List<View> views; private final Set<String> nodes; /* The name of the getBucket, will use the default getBucket unless otherwise specified. */ private String bucketName = "default"; /* Password for the getBucket if any. */ private String bucketPassword = StringUtils.EMPTY; /* Design document and views to create in the getBucket, if any. */ private final String designDocument; private long timeout = DEFAULT_TIMEOUT; /** * Instantiates a new Couchbase client factory. * * @param nodes cluster nodes * @param bucketName getBucket name * @param bucketPassword the bucket password * @param timeout connection timeout * @param documentName the document name * @param views the views */ public CouchbaseClientFactory(final Set<String> nodes, final String bucketName, final String bucketPassword, final long timeout, final String documentName, final List<View> views) { this.nodes = nodes; this.bucketName = bucketName; this.bucketPassword = bucketPassword; this.timeout = timeout; this.cluster = CouchbaseCluster.create(new ArrayList<>(this.nodes)); this.designDocument = documentName; this.views = views; } /** * Instantiates a new Couchbase client factory. * * @param nodes the nodes * @param bucketName the bucket name * @param bucketPassword the bucket password */ public CouchbaseClientFactory(final Set<String> nodes, final String bucketName, final String bucketPassword) { this(nodes, bucketName, bucketPassword, DEFAULT_TIMEOUT, null, null); } /** * Authenticate. * * @param uid the uid * @param psw the psw */ public void authenticate(final String uid, final String psw) { this.cluster = this.cluster.authenticate(uid, psw); } public Cluster getCluster() { return this.cluster; } /** * Inverse of connectBucket, shuts down the client, cancelling connection * task if not completed. */ public void shutdown() { try { if (this.cluster != null) { this.cluster.disconnect(); } } catch (final Exception e) { throw Throwables.propagate(e); } } /** * Retrieve the Couchbase getBucket. * * @return the getBucket. */ public Bucket getBucket() { if (this.bucket == null) { if (StringUtils.isBlank(this.bucketName)) { throw new IllegalArgumentException("Bucket name cannot be blank"); } try { LOGGER.debug("Trying to connect to couchbase getBucket [{}]", this.bucketName); this.bucket = this.cluster.openBucket(this.bucketName, this.bucketPassword, this.timeout, TimeUnit.SECONDS); LOGGER.info("Connected to Couchbase getBucket [{}]", this.bucketName); if (this.views != null && this.designDocument != null) { LOGGER.debug("Ensure that indexes exist in getBucket [{}]", this.bucket.name()); final DesignDocument newDocument = DesignDocument.create(this.designDocument, views); if (!newDocument.equals(this.bucket.bucketManager().getDesignDocument(this.designDocument))) { LOGGER.warn("Missing indexes in getBucket [{}] for document [{}]", this.bucket.name(), this.designDocument); this.bucket.bucketManager().upsertDesignDocument(newDocument); } } } catch (final Exception e) { throw new IllegalArgumentException("Failed to connect to Couchbase getBucket", e); } } return this.bucket; } }
apache-2.0
Malamut54/dbobrov
concurrency/src/main/java/ru/job4j/concurrency/second/User.java
474
package ru.job4j.concurrency.second; public class User { private int id; private String name; public static User of(String name) { User user = new User(); user.name = name; return user; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
apache-2.0
WeiChou/Wei.Lib2A
Wei.Lib2A/src/hobby/wei/c/Const.java
2461
/* * Copyright (C) 2014-present, Wei Chou (weichou2010@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package hobby.wei.c; /** * @author 周伟 Wei Chou(weichou2010@gmail.com) */ public class Const { @Deprecated public static final int REQUEST_CODE_NORMAL = 10000; public static final int REQUEST_CODE_LOGIN = 10001; public static final int REQUEST_CODE_LOGOUT = 10002; @Deprecated public static final int RESULT_CODE_EXIT = 99999; public static final int RESULT_CODE_USER = 99998; public static final String ACTION_LOGIN = "hobby.wei.c.action.LOGIN"; public static final String ACTION_LOGOUT = "hobby.wei.c.action.LOGOUT"; public static final String ACTION_AUTO_LOGIN = "hobby.wei.c.action.AUTO_LOGIN"; public static final String ACTION_AUTO_START = "hobby.wei.c.action.AUTO.START"; public static final String ACTION_STOP = "hobby.wei.c.action.STOP"; public static final String EXTRA_BACK_TO_NAME = "hobby.wei.c.extra.back.to.name"; public static final String EXTRA_BACK_TO_COUNT = "hobby.wei.c.extra.back.to.count"; public static final String EXTRA_BACK_CONTINUOUS = "hobby.wei.c.extra.back.continuous"; public static final String EXTRA_NORMAL = "hobby.wei.c.extra.normal"; public static final String EXTRA_LOGIN = "hobby.wei.c.extra.login"; public static final String EXTRA_LOGOUT = "hobby.wei.c.extra.logout"; public static final String EXTRA_USER_INFO = "hobby.wei.c.extra.user.info"; public static final String KEY_USER = "hobby.wei.c.key.user"; public static final String KEY_USER_CONF = "hobby.wei.c.key.user.config"; public static final String NOTIFY_NET_STATE_CHANGE = "hobby.wei.c.notify.net.state.change"; public static final String KEY_MSG = "hobby.wei.c.key.message"; public static final String KEY_PACKAGE = "hobby.wei.c.key.package"; public static final String KEY_CLASS_NAME = "hobby.wei.c.key.className"; }
apache-2.0
epimorphics/serverbase
src/main/java/com/epimorphics/server/stores/StoreBase.java
12306
/****************************************************************** * File: StoreBase.java * Created by: Dave Reynolds * Created on: 27 Nov 2012 * * (c) Copyright 2012, Epimorphics Limited * * 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.epimorphics.server.stores; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.apache.jena.fuseki.server.DatasetRef; import org.apache.jena.fuseki.server.DatasetRegistry; import org.apache.jena.query.text.EntityDefinition; import org.apache.jena.query.text.TextDatasetFactory; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.RAMDirectory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.epimorphics.server.core.Indexer; import com.epimorphics.server.core.Mutator; import com.epimorphics.server.core.Service; import com.epimorphics.server.core.ServiceBase; import com.epimorphics.server.core.ServiceConfig; import com.epimorphics.server.core.Store; import com.epimorphics.util.EpiException; import com.epimorphics.util.FileUtil; import com.epimorphics.util.NameUtils; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.ReadWrite; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.util.FileUtils; import com.hp.hpl.jena.vocabulary.RDFS; /** * Base implementation of a generic store. Supports linking to indexer and mutator services. * Supports optional logging of all requests to a nominated file system. * * @author <a href="mailto:dave@epimorphics.com">Dave Reynolds</a> */ public abstract class StoreBase extends ServiceBase implements Store, Service { static Logger log = LoggerFactory.getLogger(StoreBase.class); public static final String INDEXER_PARAM = "indexer"; public static final String MUTATOR_PARAM = "mutator"; public static final String JENA_TEXT_PARAM = "jena-text"; public static final String LOG_PARAM = "log"; public static final String ADD_ACTION = "ADD"; public static final String UPDATE_ACTION = "UPDATE"; public static final String DELETE_ACTION = "DELETE"; public static final String QUERY_ENDPOINT_PARAM = "ep"; protected Dataset dataset; protected volatile List<Indexer> indexers = new ArrayList<Indexer>(); protected volatile List<Mutator> mutators = new ArrayList<Mutator>(); protected String logDirectory; protected boolean inWrite = false; @Override public void init(Map<String, String> config, ServletContext context) { super.init(config, context); logDirectory = config.get(LOG_PARAM); if (logDirectory != null) { logDirectory = ServiceConfig.get().expandFileLocation(logDirectory); FileUtil.ensureDir(logDirectory); } } /** * Install a jena-text dataset wrapper round this store. * This is an alternative to the indexer system. */ protected void installJenaText() { if (config.containsKey(JENA_TEXT_PARAM)) { String dirname = getRequiredFileParam(JENA_TEXT_PARAM); Directory dir = null; if (dirname.equals("mem")) { dir = new RAMDirectory(); } else { try { File dirf = new File(dirname); dir = FSDirectory.open(dirf); } catch (IOException e) { throw new EpiException("Failed to create jena-text lucence index area", e); } } EntityDefinition entDef = new EntityDefinition("uri", "text", RDFS.label.asNode()) ; dataset = TextDatasetFactory.createLucene(dataset, dir, entDef) ; } } /** * Configure a Fuseki query servlet for this store. The * web.xml file needs to map the servlet to a matching context path. */ protected void installQueryEndpoint( ServletContext context) { String qEndpoint = config.get(QUERY_ENDPOINT_PARAM); if (qEndpoint != null) { String base = context.getContextPath(); if ( ! base.endsWith("/")) { base += "/"; } base += qEndpoint; DatasetRef ds = new DatasetRef(); ds.name = qEndpoint; ds.query.endpoints.add("query" ); ds.init(); ds.dataset = dataset.asDatasetGraph(); DatasetRegistry.get().put(base, ds); log.info("Installing SPARQL query endpoint at " + base + "/query"); } } @Override public void postInit() { String indexerNames = config.get(INDEXER_PARAM); if (indexerNames != null) { for (String indexerName : indexerNames.split(";")) { Service indexer = ServiceConfig.get().getService(indexerName); if (indexer instanceof Indexer) { indexers.add( (Indexer) indexer ); log.info("Configured indexer for store"); } else { throw new EpiException("Configured indexer doesn't seem to be an Indexer: " + indexerName); } } } String mutatorNames = config.get(MUTATOR_PARAM); if (mutatorNames != null) { for (String name : mutatorNames.split(";")) { Service mutator = ServiceConfig.get().getService(name); if (mutator instanceof Mutator) { mutators.add( (Mutator) mutator ); } else { throw new EpiException("Configured mutator doesn't seem to be a Mutator: " + name); } } } } protected abstract void doAddGraph(String graphname, Model graph); protected abstract void doAddGraph(String graphname, InputStream input, String mimeType); protected abstract void doDeleteGraph(String graphname); @Override abstract public Dataset asDataset(); @Override public void addGraph(String graphname, Model graph) { logAction(ADD_ACTION, graphname, graph); mutate(graph); index(graphname, graph, false); doAddGraph(graphname, graph); } @Override public void updateGraph(String graphname, Model graph) { logAction(UPDATE_ACTION, graphname, graph); doDeleteGraph(graphname); mutate(graph); index(graphname, graph, true); doAddGraph(graphname, graph); } @Override public void deleteGraph(String graphname) { logAction(DELETE_ACTION, graphname, null); for (Indexer i : indexers) { i.deleteGraph(graphname); } doDeleteGraph(graphname); } @Override public void addGraph(String graphname, InputStream input, String mimeType) { doAddGraph(graphname, input, mimeType); logNamed(ADD_ACTION, graphname); mutateNamed(graphname); indexNamed(graphname, false); } @Override public void updateGraph(String graphname, InputStream input, String mimeType) { doDeleteGraph(graphname); doAddGraph(graphname, input, mimeType); logNamed(UPDATE_ACTION, graphname); mutateNamed(graphname); indexNamed(graphname, true); } @Override synchronized public void addIndexer(Indexer indexer) { List<Indexer> newIndexes = new ArrayList<Indexer>( indexers ); newIndexes.add(indexer); // This should be an atomics switch of lists so no need to sync the methods that use the list indexers = newIndexes; } @Override synchronized public void addMutator(Mutator mutator) { List<Mutator> newl= new ArrayList<Mutator>( mutators ); newl.add(mutator); // This should be an atomics switch of lists so no need to sync the methods that use the list mutators = newl; } /** Lock the dataset for reading */ public synchronized void lock() { Dataset dataset = asDataset(); if (dataset.supportsTransactions()) { dataset.begin(ReadWrite.READ); } else { dataset.asDatasetGraph().getLock().enterCriticalSection(Lock.READ); } } /** Lock the dataset for write */ public synchronized void lockWrite() { Dataset dataset = asDataset(); if (dataset.supportsTransactions()) { dataset.begin(ReadWrite.WRITE); inWrite = true; } else { dataset.asDatasetGraph().getLock().enterCriticalSection(Lock.WRITE); } } /** Unlock the dataset */ public synchronized void unlock() { Dataset dataset = asDataset(); if (dataset.supportsTransactions()) { if (inWrite) { dataset.commit(); inWrite = false; } dataset.end(); } else { dataset.asDatasetGraph().getLock().leaveCriticalSection(); } } /** Unlock the dataset, aborting the transaction. Only useful if the dataset is transactional */ public synchronized void abort() { Dataset dataset = asDataset(); if (dataset.supportsTransactions()) { if (inWrite) { dataset.abort(); inWrite = false; } dataset.end(); } else { dataset.asDatasetGraph().getLock().leaveCriticalSection(); } } // Internal methods protected void mutate(Model graph) { for (Mutator mutator : mutators) { mutator.mutate(graph); } } protected void mutateNamed(String graphname) { if (!mutators.isEmpty()) { lockWrite(); try { mutate( asDataset().getNamedModel(graphname) ); } finally { unlock(); } } } protected void index(String graphname, Model graph, boolean update) { for (Indexer i : indexers) { if (update) { i.updateGraph(graphname, graph); } else { i.addGraph(graphname, graph); } } } protected void indexNamed(String graphname, boolean update) { lock(); try { index( graphname, asDataset().getNamedModel(graphname), update ); } finally { unlock(); } } protected void logAction(String action, String graph, Model data) { if (logDirectory != null) { String dir = logDirectory + File.separator + NameUtils.encodeSafeName(graph); FileUtil.ensureDir(dir); String filename = String.format("on-%s-%s.ttl", System.currentTimeMillis(), action); File logFile = new File(dir, filename); try { if (data != null) { OutputStream out = new FileOutputStream(logFile); data.write(out, FileUtils.langTurtle); out.close(); } else { logFile.createNewFile(); } } catch (IOException e) { log.error("Failed to create log file: " + logFile); } } } protected void logNamed(String action, String graphname) { if (logDirectory != null) { lockWrite(); try { logAction(action, graphname, asDataset().getNamedModel(graphname) ); } finally { unlock(); } } } }
apache-2.0
rzhedunov/rzhedunov
chapter_002/src/main/java/ru/job4j/tracker/StubInput.java
984
package ru.job4j.tracker; /** * Class StubInput 002.4.3. * * @author rzhedunov * @version 002.4.3. * @since 2018-01-11 */ public class StubInput implements Input { /** * A table of answers seria. */ private String[] answers; /** * A table of answers numbers. */ private int[] numberOfAnswers = {0, 1, 2, 3, 4, 5, 6}; /** * Current answer's position. */ private int position = 0; /** * Конструктор по умолчанию */ public StubInput(String[] answers) { this.answers = answers; } /** * A method to retrieve the next answer from stub class */ public String ask(String question) { return answers[position++]; } /** * The second method to retrieve the next answer from stub class (as an int) */ public int ask(String question, int[] range) throws MenuOutException { return Integer.valueOf(answers[position++]); } }
apache-2.0
Tataraovoleti/Struts2DbConnPool
src/com/java/struts/fazalcode/LoginAction.java
1125
/** * Copyright @ 2013 Fazal Code * All Rights Reserved to Fazal Code */ package com.java.struts.fazalcode; import com.java.struts.fazalcode.dao.LanguageSearchDaoImpl; import com.opensymphony.xwork2.ActionSupport; /** * @author Tatarao voleti * @date Dec 8, 2013 */ public class LoginAction extends ActionSupport { private static final long serialVersionUID = -4009189608883433657L; private String username; private String password; public String execute(){ /*if(username.equalsIgnoreCase("sanjay") && password.equalsIgnoreCase("sanjay")){ return SUCCESS; } else return ERROR;*/ LanguageSearchDaoImpl lsd=new LanguageSearchDaoImpl(); String val=lsd.isUserExist(username,password); return val; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "LoginAction [username=" + username + ", password=" + password + "]"; } }
apache-2.0
lastaflute/lastaflute-example-harbor
src/main/java/org/docksidestage/dbflute/bsentity/BsMemberStatus.java
20574
/* * Copyright 2015-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.dbflute.bsentity; import java.util.List; import java.util.ArrayList; import org.dbflute.dbmeta.DBMeta; import org.dbflute.dbmeta.AbstractEntity; import org.dbflute.dbmeta.accessory.DomainEntity; import org.docksidestage.dbflute.allcommon.DBMetaInstanceHandler; import org.docksidestage.dbflute.allcommon.CDef; import org.docksidestage.dbflute.exentity.*; /** * The entity of (会員ステータス)MEMBER_STATUS as TABLE. <br> * 会員のステータスを示す固定的なマスタテーブル。いわゆるテーブル区分値!<br> * 業務運用上で増えることはなく、増減するときはプログラム修正ともなうレベルの業務変更と考えられる。<br> * <br> * こういった固定的なマスタテーブルには、更新日時などの共通カラムは定義していないが、業務上そういった情報を管理する必要性が低いという理由に加え、ExampleDBとして共通カラムでER図が埋め尽くされてしまい見づらくなるというところで割り切っている。実業務では統一的に定義することもある。 * <pre> * [primary-key] * MEMBER_STATUS_CODE * * [column] * MEMBER_STATUS_CODE, MEMBER_STATUS_NAME, DESCRIPTION, DISPLAY_ORDER * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * * * [referrer table] * MEMBER, MEMBER_LOGIN * * [foreign property] * * * [referrer property] * memberList, memberLoginList * * [get/set template] * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * String memberStatusCode = entity.getMemberStatusCode(); * String memberStatusName = entity.getMemberStatusName(); * String description = entity.getDescription(); * Integer displayOrder = entity.getDisplayOrder(); * entity.setMemberStatusCode(memberStatusCode); * entity.setMemberStatusName(memberStatusName); * entity.setDescription(description); * entity.setDisplayOrder(displayOrder); * = = = = = = = = = =/ * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsMemberStatus extends AbstractEntity implements DomainEntity { // =================================================================================== // Definition // ========== /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= /** (会員ステータスコード)MEMBER_STATUS_CODE: {PK, NotNull, CHAR(3), classification=MemberStatus} */ protected String _memberStatusCode; /** (会員ステータス名称)MEMBER_STATUS_NAME: {NotNull, VARCHAR(50)} */ protected String _memberStatusName; /** (説明)DESCRIPTION: {NotNull, VARCHAR(200)} */ protected String _description; /** (表示順)DISPLAY_ORDER: {UQ, NotNull, INTEGER(10)} */ protected Integer _displayOrder; // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public DBMeta asDBMeta() { return DBMetaInstanceHandler.findDBMeta(asTableDbName()); } /** {@inheritDoc} */ public String asTableDbName() { return "MEMBER_STATUS"; } // =================================================================================== // Key Handling // ============ /** {@inheritDoc} */ public boolean hasPrimaryKeyValue() { if (_memberStatusCode == null) { return false; } return true; } /** * To be unique by the unique column. <br> * You can update the entity by the key when entity update (NOT batch update). * @param displayOrder (表示順): UQ, NotNull, INTEGER(10). (NotNull) */ public void uniqueBy(Integer displayOrder) { __uniqueDrivenProperties.clear(); __uniqueDrivenProperties.addPropertyName("displayOrder"); setDisplayOrder(displayOrder); } // =================================================================================== // Classification Property // ======================= /** * Get the value of memberStatusCode as the classification of MemberStatus. <br> * (会員ステータスコード)MEMBER_STATUS_CODE: {PK, NotNull, CHAR(3), classification=MemberStatus} <br> * status of member from entry to withdrawal * <p>It's treated as case insensitive and if the code value is null, it returns null.</p> * @return The instance of classification definition (as ENUM type). (NullAllowed: when the column value is null) */ public CDef.MemberStatus getMemberStatusCodeAsMemberStatus() { return CDef.MemberStatus.codeOf(getMemberStatusCode()); } /** * Set the value of memberStatusCode as the classification of MemberStatus. <br> * (会員ステータスコード)MEMBER_STATUS_CODE: {PK, NotNull, CHAR(3), classification=MemberStatus} <br> * status of member from entry to withdrawal * @param cdef The instance of classification definition (as ENUM type). (NullAllowed: if null, null value is set to the column) */ public void setMemberStatusCodeAsMemberStatus(CDef.MemberStatus cdef) { setMemberStatusCode(cdef != null ? cdef.code() : null); } // =================================================================================== // Classification Setting // ====================== /** * Set the value of memberStatusCode as Formalized (FML). <br> * Formalized: as formal member, allowed to use all service */ public void setMemberStatusCode_Formalized() { setMemberStatusCodeAsMemberStatus(CDef.MemberStatus.Formalized); } /** * Set the value of memberStatusCode as Withdrawal (WDL). <br> * Withdrawal: withdrawal is fixed, not allowed to use service */ public void setMemberStatusCode_Withdrawal() { setMemberStatusCodeAsMemberStatus(CDef.MemberStatus.Withdrawal); } /** * Set the value of memberStatusCode as Provisional (PRV). <br> * Provisional: first status after entry, allowed to use only part of service */ public void setMemberStatusCode_Provisional() { setMemberStatusCodeAsMemberStatus(CDef.MemberStatus.Provisional); } // =================================================================================== // Classification Determination // ============================ /** * Is the value of memberStatusCode Formalized? <br> * Formalized: as formal member, allowed to use all service * <p>It's treated as case insensitive and if the code value is null, it returns false.</p> * @return The determination, true or false. */ public boolean isMemberStatusCodeFormalized() { CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus(); return cdef != null ? cdef.equals(CDef.MemberStatus.Formalized) : false; } /** * Is the value of memberStatusCode Withdrawal? <br> * Withdrawal: withdrawal is fixed, not allowed to use service * <p>It's treated as case insensitive and if the code value is null, it returns false.</p> * @return The determination, true or false. */ public boolean isMemberStatusCodeWithdrawal() { CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus(); return cdef != null ? cdef.equals(CDef.MemberStatus.Withdrawal) : false; } /** * Is the value of memberStatusCode Provisional? <br> * Provisional: first status after entry, allowed to use only part of service * <p>It's treated as case insensitive and if the code value is null, it returns false.</p> * @return The determination, true or false. */ public boolean isMemberStatusCodeProvisional() { CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus(); return cdef != null ? cdef.equals(CDef.MemberStatus.Provisional) : false; } /** * means member that can use services <br> * The group elements:[Formalized, Provisional] * @return The determination, true or false. */ public boolean isMemberStatusCode_ServiceAvailable() { CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus(); return cdef != null && cdef.isServiceAvailable(); } /** * Members are not formalized yet <br> * The group elements:[Provisional] * @return The determination, true or false. */ public boolean isMemberStatusCode_ShortOfFormalized() { CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus(); return cdef != null && cdef.isShortOfFormalized(); } // =================================================================================== // Foreign Property // ================ // =================================================================================== // Referrer Property // ================= /** (会員)MEMBER by MEMBER_STATUS_CODE, named 'memberList'. */ protected List<Member> _memberList; /** * [get] (会員)MEMBER by MEMBER_STATUS_CODE, named 'memberList'. * @return The entity list of referrer property 'memberList'. (NotNull: even if no loading, returns empty list) */ public List<Member> getMemberList() { if (_memberList == null) { _memberList = newReferrerList(); } return _memberList; } /** * [set] (会員)MEMBER by MEMBER_STATUS_CODE, named 'memberList'. * @param memberList The entity list of referrer property 'memberList'. (NullAllowed) */ public void setMemberList(List<Member> memberList) { _memberList = memberList; } /** (会員ログイン)MEMBER_LOGIN by LOGIN_MEMBER_STATUS_CODE, named 'memberLoginList'. */ protected List<MemberLogin> _memberLoginList; /** * [get] (会員ログイン)MEMBER_LOGIN by LOGIN_MEMBER_STATUS_CODE, named 'memberLoginList'. * @return The entity list of referrer property 'memberLoginList'. (NotNull: even if no loading, returns empty list) */ public List<MemberLogin> getMemberLoginList() { if (_memberLoginList == null) { _memberLoginList = newReferrerList(); } return _memberLoginList; } /** * [set] (会員ログイン)MEMBER_LOGIN by LOGIN_MEMBER_STATUS_CODE, named 'memberLoginList'. * @param memberLoginList The entity list of referrer property 'memberLoginList'. (NullAllowed) */ public void setMemberLoginList(List<MemberLogin> memberLoginList) { _memberLoginList = memberLoginList; } protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import return new ArrayList<ELEMENT>(); } // =================================================================================== // Basic Override // ============== @Override protected boolean doEquals(Object obj) { if (obj instanceof BsMemberStatus) { BsMemberStatus other = (BsMemberStatus)obj; if (!xSV(_memberStatusCode, other._memberStatusCode)) { return false; } return true; } else { return false; } } @Override protected int doHashCode(int initial) { int hs = initial; hs = xCH(hs, asTableDbName()); hs = xCH(hs, _memberStatusCode); return hs; } @Override protected String doBuildStringWithRelation(String li) { StringBuilder sb = new StringBuilder(); if (_memberList != null) { for (Member et : _memberList) { if (et != null) { sb.append(li).append(xbRDS(et, "memberList")); } } } if (_memberLoginList != null) { for (MemberLogin et : _memberLoginList) { if (et != null) { sb.append(li).append(xbRDS(et, "memberLoginList")); } } } return sb.toString(); } @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(xfND(_memberStatusCode)); sb.append(dm).append(xfND(_memberStatusName)); sb.append(dm).append(xfND(_description)); sb.append(dm).append(xfND(_displayOrder)); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } @Override protected String doBuildRelationString(String dm) { StringBuilder sb = new StringBuilder(); if (_memberList != null && !_memberList.isEmpty()) { sb.append(dm).append("memberList"); } if (_memberLoginList != null && !_memberLoginList.isEmpty()) { sb.append(dm).append("memberLoginList"); } if (sb.length() > dm.length()) { sb.delete(0, dm.length()).insert(0, "(").append(")"); } return sb.toString(); } @Override public MemberStatus clone() { return (MemberStatus)super.clone(); } // =================================================================================== // Accessor // ======== /** * [get] (会員ステータスコード)MEMBER_STATUS_CODE: {PK, NotNull, CHAR(3), classification=MemberStatus} <br> * 会員ステータスを識別するコード。<br> * 固定的なデータなので連番とか番号にはせず、データを直接見たときも人が直感的にわかるように、例えば "FML" とかの3桁のコード形式にしている。(3って何会員だっけ?とかの問答をやりたくないので) * @return The value of the column 'MEMBER_STATUS_CODE'. (basically NotNull if selected: for the constraint) */ public String getMemberStatusCode() { checkSpecifiedProperty("memberStatusCode"); return convertEmptyToNull(_memberStatusCode); } /** * [set] (会員ステータスコード)MEMBER_STATUS_CODE: {PK, NotNull, CHAR(3), classification=MemberStatus} <br> * 会員ステータスを識別するコード。<br> * 固定的なデータなので連番とか番号にはせず、データを直接見たときも人が直感的にわかるように、例えば "FML" とかの3桁のコード形式にしている。(3って何会員だっけ?とかの問答をやりたくないので) * @param memberStatusCode The value of the column 'MEMBER_STATUS_CODE'. (basically NotNull if update: for the constraint) */ protected void setMemberStatusCode(String memberStatusCode) { checkClassificationCode("MEMBER_STATUS_CODE", CDef.DefMeta.MemberStatus, memberStatusCode); registerModifiedProperty("memberStatusCode"); _memberStatusCode = memberStatusCode; } /** * [get] (会員ステータス名称)MEMBER_STATUS_NAME: {NotNull, VARCHAR(50)} <br> * 表示用の名称。<br> * 国際化対応するときはもっと色々考える必要があるかと...ということで英語名カラムがないので、そのまま区分値メソッド名の一部としても利用される。 * @return The value of the column 'MEMBER_STATUS_NAME'. (basically NotNull if selected: for the constraint) */ public String getMemberStatusName() { checkSpecifiedProperty("memberStatusName"); return convertEmptyToNull(_memberStatusName); } /** * [set] (会員ステータス名称)MEMBER_STATUS_NAME: {NotNull, VARCHAR(50)} <br> * 表示用の名称。<br> * 国際化対応するときはもっと色々考える必要があるかと...ということで英語名カラムがないので、そのまま区分値メソッド名の一部としても利用される。 * @param memberStatusName The value of the column 'MEMBER_STATUS_NAME'. (basically NotNull if update: for the constraint) */ public void setMemberStatusName(String memberStatusName) { registerModifiedProperty("memberStatusName"); _memberStatusName = memberStatusName; } /** * [get] (説明)DESCRIPTION: {NotNull, VARCHAR(200)} <br> * 会員ステータスそれぞれの説明。<br> * 区分値の一つ一つの要素に気の利いた説明があるとディベロッパーがとても助かるので絶対に欲しい。 * @return The value of the column 'DESCRIPTION'. (basically NotNull if selected: for the constraint) */ public String getDescription() { checkSpecifiedProperty("description"); return convertEmptyToNull(_description); } /** * [set] (説明)DESCRIPTION: {NotNull, VARCHAR(200)} <br> * 会員ステータスそれぞれの説明。<br> * 区分値の一つ一つの要素に気の利いた説明があるとディベロッパーがとても助かるので絶対に欲しい。 * @param description The value of the column 'DESCRIPTION'. (basically NotNull if update: for the constraint) */ public void setDescription(String description) { registerModifiedProperty("description"); _description = description; } /** * [get] (表示順)DISPLAY_ORDER: {UQ, NotNull, INTEGER(10)} <br> * UI上のステータスの表示順を示すNO。<br> * 並べるときは、このカラムに対して昇順のソート条件にする。 * @return The value of the column 'DISPLAY_ORDER'. (basically NotNull if selected: for the constraint) */ public Integer getDisplayOrder() { checkSpecifiedProperty("displayOrder"); return _displayOrder; } /** * [set] (表示順)DISPLAY_ORDER: {UQ, NotNull, INTEGER(10)} <br> * UI上のステータスの表示順を示すNO。<br> * 並べるときは、このカラムに対して昇順のソート条件にする。 * @param displayOrder The value of the column 'DISPLAY_ORDER'. (basically NotNull if update: for the constraint) */ public void setDisplayOrder(Integer displayOrder) { registerModifiedProperty("displayOrder"); _displayOrder = displayOrder; } /** * For framework so basically DON'T use this method. * @param memberStatusCode The value of the column 'MEMBER_STATUS_CODE'. (basically NotNull if update: for the constraint) */ public void mynativeMappingMemberStatusCode(String memberStatusCode) { setMemberStatusCode(memberStatusCode); } }
apache-2.0
ChristopherMann/2FactorWallet
android_wallet/src/main/java/de/uni_bonn/bit/TLSClientHelper.java
3854
/* * Copyright 2014 Christopher Mann * * 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 de.uni_bonn.bit; import org.apache.avro.ipc.NettyTransceiver; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.ssl.SslHandler; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; import java.util.concurrent.Executors; /** * This class contains some helper methods for establishing a TLS connection. */ public class TLSClientHelper { public static NettyTransceiver createNettyTransceiver(PublicKey publicKey, List<String> ipAddresses) throws IOException { String ipAddress = IPAddressHelper.findFirstAddressInCommonNetwork(ipAddresses); NettyTransceiver client = new NettyTransceiver( new InetSocketAddress(ipAddress, 7001), new SSLChannelFactory(publicKey)); return client; } private static class SSLChannelFactory extends NioClientSocketChannelFactory { private PublicKey publicKey; public SSLChannelFactory(PublicKey publicKey) { super(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); this.publicKey = publicKey; } @Override public SocketChannel newChannel(ChannelPipeline pipeline) { try { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, new TrustManager[]{new BogusTrustManager(publicKey)}, null); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); pipeline.addFirst("ssl", new SslHandler(sslEngine)); return super.newChannel(pipeline); } catch (Exception ex) { throw new RuntimeException("Cannot create SSL channel", ex); } } } /** * Bogus trust manager accepting any certificate */ private static class BogusTrustManager implements X509TrustManager { private PublicKey publicKey; public BogusTrustManager(PublicKey publicKey) { this.publicKey = publicKey; } @Override public void checkClientTrusted(X509Certificate[] certs, String s) { // nothing } @Override public void checkServerTrusted(X509Certificate[] certs, String s) throws CertificateException { if(certs.length != 1) throw new CertificateException("Only a single self-signed certificate is expected, but a longer certificate chain was provided."); X509Certificate cert = certs[0]; if(! cert.getPublicKey().equals(publicKey)) throw new CertificateException("The server is not using the expected public key"); } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }
apache-2.0
simonjupp/java-skos-api
skos-impl/src/main/java/uk/ac/manchester/cs/skos/properties/SKOSHistoryNoteObjectPropertyImpl.java
1889
package uk.ac.manchester.cs.skos.properties; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.skos.SKOSPropertyVisitor; import org.semanticweb.skos.properties.SKOSHistoryNoteObjectProperty; import uk.ac.manchester.cs.skos.SKOSObjectPropertyImpl; import uk.ac.manchester.cs.skos.SKOSRDFVocabulary; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Simon Jupp<br> * Date: Sep 4, 2008<br> * The University of Manchester<br> * Bio-Health Informatics Group<br> */ public class SKOSHistoryNoteObjectPropertyImpl extends SKOSObjectPropertyImpl implements SKOSHistoryNoteObjectProperty { public SKOSHistoryNoteObjectPropertyImpl(OWLDataFactory dataFactory) { super(dataFactory.getOWLObjectProperty(IRI.create(SKOSRDFVocabulary.HISTORYNOTE.getURI()))); } public void accept(SKOSPropertyVisitor visitor) { } }
apache-2.0
macula-projects/macula-cart
macula-cart-repository/src/main/java/org/macula/cart/config/AppConfig.java
430
/** * AppConfiguration.java 2016年10月27日 */ package org.macula.cart.config; import org.macula.core.config.MaculaAppConfig; import org.springframework.context.annotation.Configuration; /** * <p> * <b>AppConfig</b> APP配置,用来代替macula-*-app.xml,也可以共存 * </p> * * @since 2016年10月27日 * @author Rain * @version $Id$ */ @Configuration public class AppConfig implements MaculaAppConfig { }
apache-2.0
consulo/consulo-xml
xml-psi-impl/src/main/java/com/intellij/xml/index/SchemaTypeInheritanceIndex.java
6104
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xml.index; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.PairConvertor; import com.intellij.util.containers.EncoderDecoder; import com.intellij.util.containers.MultiMap; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.FileContent; import com.intellij.util.indexing.ID; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.DataInputOutputUtil; import com.intellij.util.io.IOUtil; import com.intellij.util.text.CharArrayUtil; import javax.annotation.Nonnull; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; /** * Created with IntelliJ IDEA. * User: Irina.Chernushina * Date: 7/4/12 * Time: 6:29 PM * <p/> * map: tag name->file url */ public class SchemaTypeInheritanceIndex extends XmlIndex<Set<SchemaTypeInfo>> { private static final ID<String, Set<SchemaTypeInfo>> NAME = ID.create("SchemaTypeInheritance"); private static final Logger LOG = Logger.getInstance("#com.intellij.xml.index.SchemaTypeInheritanceIndex"); private static List<Set<SchemaTypeInfo>> getDirectChildrenOfType(final Project project, final String ns, final String name) { GlobalSearchScope filter = createFilter(project); return FileBasedIndex.getInstance().getValues(NAME, NsPlusTag.INSTANCE.encode(Pair.create(ns, name)), filter); } public static PairConvertor<String, String, List<Set<SchemaTypeInfo>>> getWorker(final Project project, final VirtualFile currentFile) { return new MyWorker(currentFile, project); } private static class MyWorker implements PairConvertor<String, String, List<Set<SchemaTypeInfo>>> { private final Project myProject; private final VirtualFile myCurrentFile; private final GlobalSearchScope myFilter; private final boolean myShouldParseCurrent; private MultiMap<SchemaTypeInfo, SchemaTypeInfo> myMap; private MyWorker(VirtualFile currentFile, Project project) { myCurrentFile = currentFile; myProject = project; myFilter = createFilter(project); myShouldParseCurrent = (myCurrentFile != null && !myFilter.contains(myCurrentFile)); } @Override public List<Set<SchemaTypeInfo>> convert(String ns, String name) { List<Set<SchemaTypeInfo>> type = getDirectChildrenOfType(myProject, ns, name); if(myShouldParseCurrent) { if(myMap == null) { try { myMap = XsdComplexTypeInfoBuilder.parse(CharArrayUtil.readerFromCharSequence(VfsUtilCore.loadText(myCurrentFile))); type.add(new HashSet<SchemaTypeInfo>(myMap.get(new SchemaTypeInfo(name, true, ns)))); } catch(IOException e) { LOG.info(e); } } } return type; } } @Override public boolean dependsOnFileContent() { return true; } @Override public int getVersion() { return 1; } @Nonnull @Override public ID<String, Set<SchemaTypeInfo>> getName() { return NAME; } @Nonnull @Override public DataIndexer<String, Set<SchemaTypeInfo>, FileContent> getIndexer() { return new DataIndexer<String, Set<SchemaTypeInfo>, FileContent>() { @Nonnull @Override public Map<String, Set<SchemaTypeInfo>> map(@Nonnull FileContent inputData) { final Map<String, Set<SchemaTypeInfo>> map = new HashMap<String, Set<SchemaTypeInfo>>(); final MultiMap<SchemaTypeInfo, SchemaTypeInfo> multiMap = XsdComplexTypeInfoBuilder.parse(CharArrayUtil.readerFromCharSequence(inputData.getContentAsText())); for(SchemaTypeInfo key : multiMap.keySet()) { map.put(NsPlusTag.INSTANCE.encode(Pair.create(key.getNamespaceUri(), key.getTagName())), new HashSet<SchemaTypeInfo>(multiMap.get(key))); } return map; } }; } @Nonnull @Override public DataExternalizer<Set<SchemaTypeInfo>> getValueExternalizer() { return new DataExternalizer<Set<SchemaTypeInfo>>() { @Override public void save(@Nonnull DataOutput out, Set<SchemaTypeInfo> value) throws IOException { DataInputOutputUtil.writeINT(out, value.size()); for(SchemaTypeInfo key : value) { IOUtil.writeUTF(out, key.getNamespaceUri()); IOUtil.writeUTF(out, key.getTagName()); out.writeBoolean(key.isIsTypeName()); } } @Override public Set<SchemaTypeInfo> read(@Nonnull DataInput in) throws IOException { final Set<SchemaTypeInfo> set = new HashSet<SchemaTypeInfo>(); final int size = DataInputOutputUtil.readINT(in); for(int i = 0; i < size; i++) { final String nsUri = IOUtil.readUTF(in); final String tagName = IOUtil.readUTF(in); final boolean isType = in.readBoolean(); set.add(new SchemaTypeInfo(tagName, isType, nsUri)); } return set; } }; } private static class NsPlusTag implements EncoderDecoder<Pair<String, String>, String> { private final static NsPlusTag INSTANCE = new NsPlusTag(); private final static char ourSeparator = ':'; @Override public String encode(Pair<String, String> pair) { return pair.getFirst() + ourSeparator + pair.getSecond(); } @Override public Pair<String, String> decode(String s) { final int i = s.indexOf(ourSeparator); return i <= 0 ? Pair.create("", s) : Pair.create(s.substring(0, i), s.substring(i + 1)); } } }
apache-2.0
JohnCny/PCCREDIT_QZ
src/java/com/cardpay/pccredit/report/web/QuailManaProceReturnController.java
1989
package com.cardpay.pccredit.report.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.cardpay.pccredit.report.filter.StatisticalFilter; import com.cardpay.pccredit.report.model.QuailManaReturnMonitor; import com.cardpay.pccredit.report.model.manaProceMonitor; import com.cardpay.pccredit.report.service.ProceMonitorService; import com.wicresoft.jrad.base.auth.JRadModule; import com.wicresoft.jrad.base.auth.JRadOperation; import com.wicresoft.jrad.base.web.JRadModelAndView; import com.wicresoft.jrad.base.web.controller.BaseController; import com.wicresoft.util.spring.mvc.mv.AbstractModelAndView; /** * ProceMonitorController类的描述 * * @author 王海东 * @created on 2014-12-19 * * @version $Id:$ */ @Controller @RequestMapping("/report/cardqualitymana/*") @JRadModule("report.cardqualitymana") public class QuailManaProceReturnController extends BaseController { @Autowired private ProceMonitorService proceMonitorService; /** * 浏览页面 * * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "browse.page", method = { RequestMethod.GET }) public AbstractModelAndView browse(@ModelAttribute StatisticalFilter filter, HttpServletRequest request) { filter.setRequest(request); List<QuailManaReturnMonitor> result = proceMonitorService.getQuailReturnMonitorStatistical(filter); JRadModelAndView mv = new JRadModelAndView("/report/cardquality/manager_quality_return_browse", request); mv.addObject(PAGED_RESULT, result); return mv; } }
apache-2.0
noloman/kittentrate
app/src/androidTest/java/manulorenzo/me/kittentrate/ExampleInstrumentedTest.java
756
package manulorenzo.me.kittentrate; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("manulorenzo.me.kittentrate", appContext.getPackageName()); } }
apache-2.0
gtkrug/bae-shib3
src/main/java/net/gfipm/shibboleth/dataconnector/GfipmBAEDataConnector.java
14526
/* * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.] Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in * writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.gfipm.shibboleth.dataconnector; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import net.shibboleth.idp.attribute.IdPAttribute; import net.shibboleth.idp.attribute.IdPAttributeValue; import net.shibboleth.idp.attribute.StringAttributeValue; import net.shibboleth.idp.attribute.resolver.AbstractDataConnector; import net.shibboleth.idp.attribute.resolver.ResolutionException; import net.shibboleth.idp.attribute.resolver.context.AttributeResolutionContext; import net.shibboleth.idp.attribute.resolver.context.AttributeResolverWorkContext; import net.shibboleth.idp.attribute.resolver.PluginDependencySupport; import net.shibboleth.utilities.java.support.annotation.constraint.NonnullAfterInit; import net.shibboleth.utilities.java.support.annotation.constraint.NullableElements; import net.shibboleth.utilities.java.support.component.ComponentInitializationException; import net.shibboleth.utilities.java.support.component.ComponentSupport; import net.shibboleth.utilities.java.support.primitive.StringSupport; import net.shibboleth.utilities.java.support.logic.Constraint; import org.opensaml.security.x509.X509Credential; import org.opensaml.security.credential.Credential; import java.security.PrivateKey; import java.security.cert.X509Certificate; import org.gtri.gfipm.bae.v2_0.SubjectIdentifier; import org.gtri.gfipm.bae.v2_0.EmailSubjectIdentifier; import org.gtri.gfipm.bae.v2_0.FASCNSubjectIdentifier; import org.gtri.gfipm.bae.v2_0.PIVUUIDSubjectIdentifier; import org.gtri.gfipm.bae.v2_0.InvalidFASCNException; import org.gtri.gfipm.bae.v2_0.BAEServerInfo; import org.gtri.gfipm.bae.v2_0.BAEClientInfo; import org.gtri.gfipm.bae.v2_0.BAEServer; import org.gtri.gfipm.bae.v2_0.BAEServerFactory; import org.gtri.gfipm.bae.v2_0.BAEServerInfoFactory; import org.gtri.gfipm.bae.v2_0.BAEClientInfoFactory; import org.gtri.gfipm.bae.v2_0.BackendAttribute; import org.gtri.gfipm.bae.v2_0.BackendAttributeValue; import org.gtri.gfipm.bae.v2_0.BAEServerException; import org.gtri.gfipm.bae.v2_0.BAEServerCreationException; import org.gtri.gfipm.bae.v2_0.WebServiceRequestOptions; import org.gtri.gfipm.bae.v2_0.WebServiceRequestOptionsFactory; import com.google.common.collect.Lists; /** * Data connector implementation that returns staticly defined attributes. */ public class GfipmBAEDataConnector extends AbstractDataConnector { /** Log4j logger. */ @NonnullAfterInit private final Logger log = LoggerFactory.getLogger(GfipmBAEDataConnector.class); private String baeUrl; private String subjectId; private String baeEntityId; private String myEntityId; private int searchTimeLimit; /** bae/return attribute names. */ private List<BAEAttributeNameMap> baeAttributes; private Map<String,String> baeAttrMap; /** Trust material used when connecting to the server over https. */ private Credential x509Trust; private Credential x509Key; private X509Certificate myCert; private PrivateKey myKey; private List<X509Certificate> serverCerts; /** BAE Connector */ private BAEServerInfo serverInfo; private BAEClientInfo clientInfo; private BAEServer baeServer; /** * Constructor. */ public GfipmBAEDataConnector() { } /** * Set and Get Methods used by initialization */ public void setSearchTimeLimit(@Nullable int timeout) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); searchTimeLimit = timeout; } @NonnullAfterInit public int getSearchTimeLimit() { return searchTimeLimit; } public void setBaeUrl(@Nullable String url) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); baeUrl = StringSupport.trimOrNull(url); } @NonnullAfterInit public String getBaeUrl() { return baeUrl; } public void setMyEntityId(@Nullable String id) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); myEntityId = StringSupport.trimOrNull(id); } @NonnullAfterInit public String getMyEntityId() { return myEntityId; } public void setBaeEntityId(@Nullable String id) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); baeEntityId = StringSupport.trimOrNull(id); } @NonnullAfterInit public String getBaeEntityId() { return baeEntityId; } public void setSubjectId(@Nullable String id) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); subjectId = StringSupport.trimOrNull(id); } @NonnullAfterInit public String getSubjectId() { return subjectId; } private String getPrincipal ( @Nonnull final AttributeResolutionContext resolutionContext, @Nonnull final AttributeResolverWorkContext workContext) { final Map<String,List<IdPAttributeValue<?>>> dependencyAttributes = PluginDependencySupport.getAllAttributeValues(workContext, getDependencies()); for (final Entry<String,List<IdPAttributeValue<?>>> dependencyAttribute : dependencyAttributes.entrySet()) { log.debug("Adding dependent attribute '{}' with the following values to the connector context: {}", dependencyAttribute.getKey(), dependencyAttribute.getValue()); if ( dependencyAttribute.getKey() == subjectId ) { String principalObjString = dependencyAttribute.getValue().toString(); int start = principalObjString.indexOf ('='); int end = principalObjString.indexOf ('}'); return principalObjString.substring (start + 1, end); } } return null; } /** * Method for generating a subject identifier. "Intelligently" determines type */ private SubjectIdentifier GetSubjectIdentifier (String PrincipalName) { // Test if it is a PIV-I Style UUID if (PrincipalName.indexOf ("uuid") != -1) { log.debug("Principal: " + PrincipalName + " resolved as PIV-I UUID type."); String trimmedUUID = PrincipalName.substring(9); // Remove "urn:uuid:" from the beginning. log.debug("Trimmed UUID: " + trimmedUUID); return new PIVUUIDSubjectIdentifier(trimmedUUID); } // Test if it is a FASCN try { FASCNSubjectIdentifier fascnId = new FASCNSubjectIdentifier(PrincipalName); log.debug("Principal: " + PrincipalName + " resolved as FASCN type."); return fascnId; } catch (InvalidFASCNException e) { // Not a valid FASCN so we default to e-mail address. log.debug("Principal: " + PrincipalName + " defaulting to E-mail type."); return new EmailSubjectIdentifier (PrincipalName); } } /** {@inheritDoc} */ /** {@inheritDoc} */ @Override @Nonnull protected Map<String, IdPAttribute> doDataConnectorResolve( @Nonnull final AttributeResolutionContext resolutionContext, @Nonnull final AttributeResolverWorkContext workContext) throws ResolutionException { log.debug("Resolving BAE Data Connector."); Map<String, IdPAttribute> attribute = new HashMap<String, IdPAttribute>(); final Map<String,List<IdPAttributeValue<?>>> dependencyAttributes = PluginDependencySupport.getAllAttributeValues (workContext, getDependencies()); if (dependencyAttributes == null || dependencyAttributes.isEmpty()) { log.debug("Source attribute " + subjectId + " for connector " + getId() +" provided no values, cannot resolve."); return Collections.EMPTY_MAP; } if (dependencyAttributes.size() > 1) { log.warn("Source attribute " + subjectId + " for connector " + getId() +" has more than one value, just using the first."); } String strPrincipal = getPrincipal (resolutionContext, workContext); log.debug ("Querying for Id : " + strPrincipal ); try { // SubjectIdentifier identifier = new FASCNSubjectIdentifier (strPrincipal); SubjectIdentifier identifier = GetSubjectIdentifier (strPrincipal); Collection<BackendAttribute> attributes = baeServer.attributeQuery(identifier); for (BackendAttribute a : attributes) { // If we find this attribute in our map, then it is an attribute we process if ( baeAttrMap.get (a.getName()) != null ) { String attribName = baeAttrMap.get (a.getName()); String attribValue = a.getValue().getStringValue(); List<IdPAttributeValue<String>> baXmlAttr = Lists.newArrayListWithExpectedSize(1); baXmlAttr.add(new StringAttributeValue(attribValue)); final IdPAttribute tempAttribute = new IdPAttribute(attribName); tempAttribute.setValues(baXmlAttr); attribute.put (tempAttribute.getId(), tempAttribute); } } } catch (BAEServerException e) { log.error ("BAE Server Error: {}", e); } catch (Exception e) { log.error ("Query Failed: {}", e); } return attribute; } /** * This returns the trust managers that will be used for all TLS and SSL connections to the BAE Responder. * * @return <code>TrustManager[]</code> */ public Credential getTrustCredential () { return x509Trust; } /** * This sets the trust manager that will be used for BAE queries. * * @param tc <code>Credential</code> to create TrustManagers with */ public void setTrustCredential (Credential tc) { x509Trust = tc; if (tc != null) { if (tc instanceof X509Credential) { X509Credential trust = (X509Credential) tc; Collection<X509Certificate> coll = trust.getEntityCertificateChain(); if (coll instanceof List) serverCerts = (List)coll; else serverCerts = new ArrayList(coll); } } } /** * This returns the key managers that will be used for all TLS and SSL connections to the BAE Responder. * * @return <code>KeyManager[]</code> */ public Credential getAuthCredential() { return x509Key; } /** * This sets the key managers that will be used for all TLS/WS-Security activity. * * @param kc <code>X509Credential</code> to create KeyManagers with */ public void setAuthCredential (X509Credential kc) { x509Key = kc; if ( kc != null) { if (kc instanceof X509Credential) { X509Credential keypair = (X509Credential) kc; myKey = keypair.getPrivateKey(); myCert = keypair.getEntityCertificate(); log.debug ("myKey = {}", myKey); log.debug ("myCert = {}", myCert); } } } public void setBaeAttributes(List<BAEAttributeNameMap> list) { baeAttributes = list; baeAttrMap = new HashMap<String,String> (); for (BAEAttributeNameMap attrib : list) { baeAttrMap.put (attrib.QueryName, attrib.ReturnName); } } @Override protected void doInitialize() throws ComponentInitializationException { if (null == baeUrl) { throw new ComponentInitializationException(getLogPrefix() + " No BAE Responder URL found."); } if (null == baeEntityId) { throw new ComponentInitializationException(getLogPrefix() + " No BAE Responder Entity Id found."); } if (null == serverCerts) { throw new ComponentInitializationException(getLogPrefix() + " No BAE Responder Trust Certificate(s) found."); } if (null == myEntityId) { throw new ComponentInitializationException(getLogPrefix() + " No BAE Requester Entity Id found."); } if (null == myCert) { throw new ComponentInitializationException(getLogPrefix() + " No BAE Requester Certificate found."); } if (null == myKey) { throw new ComponentInitializationException(getLogPrefix() + " No BAE Requester Private Key found."); } if (null == baeAttrMap) { throw new ComponentInitializationException(getLogPrefix() + " No Attribute Map found."); } if (null == subjectId) { throw new ComponentInitializationException(getLogPrefix() + " No Subject Identifier attribute found."); } serverInfo = BAEServerInfoFactory.getInstance().createBAEServerInfo(baeUrl, baeEntityId, serverCerts); clientInfo = BAEClientInfoFactory.getInstance().createBAEClientInfo(myEntityId, myCert, myKey); Map<String,String> mapOptions = new HashMap<String,String> (); mapOptions.put (WebServiceRequestOptions.CLIENT_CERT_AUTH, "true"); mapOptions.put (WebServiceRequestOptions.SERVER_CERT_AUTH, "false"); WebServiceRequestOptions wsRequestOptions = WebServiceRequestOptionsFactory.getInstance().createWebServiceRequestOptions(mapOptions); try { baeServer = BAEServerFactory.getInstance().createBAEServer(serverInfo, clientInfo, wsRequestOptions); } catch (BAEServerCreationException e) { log.error ("BAE Server Creation Error: {}", e); throw new ComponentInitializationException(getLogPrefix() + " BAE Server could not be initialized."); } } }
apache-2.0
marcioaug/wycash
src/main/java/net/marcioguimaraes/wycash/model/Money.java
1366
package net.marcioguimaraes.wycash.model; import net.marcioguimaraes.wycash.expression.Expression; import net.marcioguimaraes.wycash.expression.Sum; public class Money implements Expression { public int amount; private String currency; public Money(int amount, String currency) { this.amount = amount; this.currency = currency; } public static Money dollar(int amount) { return new Money(amount, "USD"); } public static Money franc(int amount) { return new Money(amount, "CHF"); } public String currency() { return this.currency; } public Money times(int multiplier) { return new Money(this.amount * multiplier, currency); } public Expression plus(Money addend) { return new Sum(this, addend); } public Money reduce(Bank bank, String to) { int rate = bank.rate(currency, to); return new Money(amount / rate, to); } @Override public boolean equals(Object obj) { if (obj.getClass().equals(this.getClass())) { Money money = (Money) obj; return (this.amount == money.amount && money.currency.equals(this.currency)); } return false; } @Override public String toString() { return this.amount + " " + this.currency; } }
apache-2.0
BiaoPro/asteroid
src/com/asteroid/action/AttentionAction.java
1889
/** * * 文件创建时间:2014年6月21日 */ package com.asteroid.action; import java.util.List; import com.asteroid.controller.attention.AttentionDao; import com.asteroid.model.Attention; import com.asteroid.model.User; import com.asteroid.service.ReleaseService; import com.asteroid.service.UserService; import com.asteroid.util.SessionManage; import com.opensymphony.xwork2.ActionSupport; /** * @author 吴泽标 * */ public class AttentionAction extends ActionSupport { private int user_id; private int a_userid; public String addAttention(){ this.setUser_id(SessionManage.getUserid()); AttentionDao dao=new AttentionDao(); Attention vo = new Attention(getUser_id(),getA_userid()); if( dao.findById(getUser_id(),getA_userid())){ addActionError("已关注过!"); return ERROR; } if (dao.save(vo)){ addActionError("关注成功"); upadeUserList(); return SUCCESS; } else{ addActionError("关注失败"); return ERROR; } } public String delAttention(){ this.setUser_id(SessionManage.getUserid()); AttentionDao dao=new AttentionDao(); if (dao.delete(getUser_id(), getA_userid())){ addActionError("取消关注"); upadeUserList(); return SUCCESS; }else{ return ERROR; } } private void upadeUserList(){ ReleaseService service=new ReleaseService(); List<User> userList=service.getAttentionUserList(SessionManage.getUserid()); SessionManage.getSession().setAttribute("userList", userList); } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public int getA_userid() { return a_userid; } public void setA_userid(int a_userid) { this.a_userid = a_userid; } }
apache-2.0
brandtg/switchboard
switchboard-mysql/src/main/java/com/google/code/or/binlog/impl/parser/IncidentEventParser.java
1785
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.or.binlog.impl.parser; import com.google.code.or.binlog.BinlogEventV4Header; import com.google.code.or.binlog.BinlogParserContext; import com.google.code.or.binlog.impl.event.IncidentEvent; import com.google.code.or.io.XInputStream; import java.io.IOException; /** * * @author Jingqi Xu */ public class IncidentEventParser extends AbstractBinlogEventParser { /** * */ public IncidentEventParser() { super(IncidentEvent.EVENT_TYPE); } /** * */ public void parse(XInputStream is, BinlogEventV4Header header, BinlogParserContext context) throws IOException { final IncidentEvent event = new IncidentEvent(header); event.setIncidentNumber(is.readInt(1)); event.setMessageLength(is.readInt(1)); if (event.getMessageLength() > 0) event.setMessage(is.readFixedLengthString(event.getMessageLength())); context.getEventListener().onEvents(event); } }
apache-2.0
dbflute-session/mailflute
src/test/java/org/dbflute/mail/BindOptionTest.java
6316
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.dbflute.mail; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Map; import javax.mail.internet.AddressException; import org.dbflute.mail.send.SMailAddress; import org.dbflute.mail.send.SMailDeliveryDepartment; import org.dbflute.mail.send.SMailPostalMotorbike; import org.dbflute.mail.send.SMailPostalParkingLot; import org.dbflute.mail.send.SMailPostalPersonnel; import org.dbflute.mail.send.embedded.personnel.SMailDogmaticPostalPersonnel; import org.dbflute.twowaysql.exception.EmbeddedVariableCommentParameterNullValueException; import org.dbflute.utflute.core.PlainTestCase; /** * @author jflute */ public class BindOptionTest extends PlainTestCase { // =================================================================================== // Definition // ========== private static final String FORMATAS_ML = "office/bindop/bindoption_formatas.dfmail"; private static final String ORELSE_ML = "office/bindop/bindoption_orelse.dfmail"; // =================================================================================== // formatAs() // ========== public void test_bindOption_formatAs_basic() throws Exception { // ## Arrange ## Postcard postcard = new Postcard(); prepareMockAddress(postcard); LocalDateTime current = currentLocalDateTime(); Map<String, Object> map = newHashMap("birthdate", current.toLocalDate(), "formalizedDatetime", current); postcard.useBodyFile(FORMATAS_ML).useTemplateText(map); // ## Act ## prepareOffice().deliver(postcard); // ## Assert ## String plain = postcard.toCompletePlainText().get(); String subject = postcard.getOfficePostingDiscloser().get().getSavedSubject().get(); log(ln() + subject + ln() + plain); assertContains(subject, current.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))); assertContains(plain, current.format(DateTimeFormatter.ofPattern("yyyy+MM+dd"))); assertContains(plain, current.format(DateTimeFormatter.ofPattern("yyyy@MM@dd HH:mm:ss.SSS"))); } public void test_bindOption_formatAs_null() throws Exception { // ## Arrange ## Postcard postcard = new Postcard(); prepareMockAddress(postcard); Map<String, Object> map = newHashMap("birthdate", null, "formalizedDatetime", null); postcard.useBodyFile(FORMATAS_ML).useTemplateText(map); // ## Act ## // ## Assert ## assertException(EmbeddedVariableCommentParameterNullValueException.class, () -> prepareOffice().deliver(postcard)); } // =================================================================================== // orElse() // ======== public void test_bindOption_orElse_exists() throws Exception { // ## Arrange ## Postcard postcard = new Postcard(); prepareMockAddress(postcard); Map<String, Object> map = newHashMap("memberName", "mystic", "memberAccount", "oneman"); postcard.useBodyFile(ORELSE_ML).useTemplateText(map); // ## Act ## prepareOffice().deliver(postcard); // ## Assert ## String plain = postcard.toCompletePlainText().get(); String subject = postcard.getOfficePostingDiscloser().get().getSavedSubject().get(); log(ln() + subject + ln() + plain); assertContains(subject, "mystic"); assertContains(plain, "mystic"); assertContains(plain, "oneman"); } public void test_bindOption_orElse_null() throws Exception { // ## Arrange ## Postcard postcard = new Postcard(); prepareMockAddress(postcard); Map<String, Object> map = newHashMap("memberName", null, "memberAccount", null); postcard.useBodyFile(ORELSE_ML).useTemplateText(map); // ## Act ## prepareOffice().deliver(postcard); // ## Assert ## String plain = postcard.toCompletePlainText().get(); String subject = postcard.getOfficePostingDiscloser().get().getSavedSubject().get(); log(ln() + subject + ln() + plain); assertContains(subject, "sea"); assertContains(plain, "land"); assertContains(plain, "piari"); } // =================================================================================== // Test Helper // =========== protected void prepareMockAddress(Postcard postcard) throws AddressException { postcard.setFrom(new SMailAddress("sea@example.com", "Sea")); postcard.addTo(new SMailAddress("land@example.com", "Land")); } protected PostOffice prepareOffice() { SMailPostalParkingLot parkingLot = new SMailPostalParkingLot(); SMailPostalMotorbike motorbike = new SMailPostalMotorbike(); parkingLot.registerMotorbikeAsMain(motorbike); SMailPostalPersonnel personnel = new SMailDogmaticPostalPersonnel().asTraining(); SMailDeliveryDepartment deliveryDepartment = new SMailDeliveryDepartment(parkingLot, personnel); return new PostOffice(deliveryDepartment); } }
apache-2.0
waans11/incubator-asterixdb
asterixdb/asterix-om/src/main/java/org/apache/asterix/dataflow/data/nontagged/printers/adm/AUnorderedlistPrinterFactory.java
3039
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.dataflow.data.nontagged.printers.adm; import java.io.PrintStream; import org.apache.asterix.common.exceptions.AsterixException; import org.apache.asterix.om.pointables.PointableAllocator; import org.apache.asterix.om.pointables.base.DefaultOpenFieldType; import org.apache.asterix.om.pointables.base.IVisitablePointable; import org.apache.asterix.om.pointables.printer.adm.APrintVisitor; import org.apache.asterix.om.types.ATypeTag; import org.apache.asterix.om.types.AUnorderedListType; import org.apache.asterix.om.types.IAType; import org.apache.hyracks.algebricks.common.utils.Pair; import org.apache.hyracks.algebricks.data.IPrinter; import org.apache.hyracks.algebricks.data.IPrinterFactory; import org.apache.hyracks.api.exceptions.HyracksDataException; public class AUnorderedlistPrinterFactory implements IPrinterFactory { private static final long serialVersionUID = 1L; private final AUnorderedListType unorderedlistType; public AUnorderedlistPrinterFactory(AUnorderedListType unorderedlistType) { this.unorderedlistType = unorderedlistType; } @Override public IPrinter createPrinter() { final PointableAllocator allocator = new PointableAllocator(); final IAType inputType = unorderedlistType == null ? DefaultOpenFieldType.getDefaultOpenFieldType(ATypeTag.UNORDEREDLIST) : unorderedlistType; final IVisitablePointable listAccessor = allocator.allocateListValue(inputType); final APrintVisitor printVisitor = new APrintVisitor(); final Pair<PrintStream, ATypeTag> arg = new Pair<>(null, null); return new IPrinter() { @Override public void init() { arg.second = inputType.getTypeTag(); } @Override public void print(byte[] b, int start, int l, PrintStream ps) throws HyracksDataException { try { listAccessor.set(b, start, l); arg.first = ps; listAccessor.accept(printVisitor, arg); } catch (AsterixException e) { throw new HyracksDataException(e); } } }; } }
apache-2.0
remibergsma/cosmic
cosmic-core/api/src/main/java/com/cloud/api/command/admin/storage/FindStoragePoolsForMigrationCmd.java
3266
package com.cloud.api.command.admin.storage; import com.cloud.api.APICommand; import com.cloud.api.ApiCommandJobType; import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Parameter; import com.cloud.api.response.ListResponse; import com.cloud.api.response.StoragePoolResponse; import com.cloud.api.response.VolumeResponse; import com.cloud.storage.StoragePool; import com.cloud.utils.Pair; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @APICommand(name = "findStoragePoolsForMigration", description = "Lists storage pools available for migration of a volume.", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class FindStoragePoolsForMigrationCmd extends BaseListCmd { public static final Logger s_logger = LoggerFactory.getLogger(FindStoragePoolsForMigrationCmd.class.getName()); private static final String s_name = "findstoragepoolsformigrationresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = VolumeResponse.class, required = true, description = "the ID of the volume") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.StoragePool; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { final Pair<List<? extends StoragePool>, List<? extends StoragePool>> pools = _mgr.listStoragePoolsForMigrationOfVolume(getId()); final ListResponse<StoragePoolResponse> response = new ListResponse<>(); final List<StoragePoolResponse> poolResponses = new ArrayList<>(); final List<? extends StoragePool> allPools = pools.first(); final List<? extends StoragePool> suitablePoolList = pools.second(); for (final StoragePool pool : allPools) { final StoragePoolResponse poolResponse = _responseGenerator.createStoragePoolForMigrationResponse(pool); Boolean suitableForMigration = false; for (final StoragePool suitablePool : suitablePoolList) { if (suitablePool.getId() == pool.getId()) { suitableForMigration = true; break; } } poolResponse.setSuitableForMigration(suitableForMigration); poolResponse.setObjectName("storagepool"); poolResponses.add(poolResponse); } response.setResponses(poolResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); } public Long getId() { return id; } @Override public String getCommandName() { return s_name; } }
apache-2.0
repeats/Repeat
src/utilities/Desktop.java
1590
package utilities; import java.awt.Desktop.Action; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import utilities.SubprocessUttility.ExecutionException; public class Desktop { private static final Logger LOGGER = Logger.getLogger(Desktop.class.getName()); public static boolean openFile(File file) { if (java.awt.Desktop.isDesktopSupported() && java.awt.Desktop.getDesktop().isSupported(Action.OPEN)) { try { java.awt.Desktop.getDesktop().open(file); } catch (IOException e) { LOGGER.log(Level.WARNING, "IOException when opening file.", e); return false; } return true; } if (OSIdentifier.IS_WINDOWS) { return openFileWindows(file); } if (OSIdentifier.IS_LINUX) { return openFileLinux(file); } if (OSIdentifier.IS_OSX) { return openFileOSX(file); } return false; } private static boolean openFileWindows(File file) { return openWithCommand("explorer", file); } private static boolean openFileLinux(File file) { if (openWithCommand("xdg-open", file)) { return true; } if (openWithCommand("kde-open", file)) { return true; } if (openWithCommand("gnome-open", file)) { return true; } return false; } private static boolean openFileOSX(File file) { return openWithCommand("open", file); } private static boolean openWithCommand(String cmd, File file) { try { SubprocessUttility.execute(cmd + " " + file.getAbsolutePath()); } catch (ExecutionException e) { return false; } return true; } private Desktop() {} }
apache-2.0
pvoosten/Longbow
src/longbow/core/DefaultTransformationContext.java
6704
/* * Copyright 2008 Philip van Oosten (Mentoring Systems BVBA) * * 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 longbow.core; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import longbow.*; import longbow.util.CompositeIterable; /** * * @author Philip van Oosten * */ public class DefaultTransformationContext implements TransformationContext { /** * Listeners for changes of this context */ private final Map<ContextListener, Object> contextListeners; private final Map<String, Input> inputs; private final Map<String, Output> outputs; private volatile Transformation transformation; private final WeakReference<Workflow> workflow; private Runner runner; private final LongbowFactory factory; public DefaultTransformationContext(final Workflow workflow, final LongbowFactory factory) { this.factory = factory; contextListeners = new WeakHashMap<ContextListener, Object>(); inputs = new HashMap<String, Input>(); outputs = new HashMap<String, Output>(); this.workflow = new WeakReference<Workflow>(workflow); } public void addContextListener(final ContextListener listener) { if (listener != null) { contextListeners.put(listener, null); } } public void addInput(final String inputid, final Metadata metadata) { if (!designMode()) { return; } if (inputid != null && metadata != null && !inputs.containsKey(inputid)) { inputs.put(inputid, factory.createInput(this, metadata)); fireContextChanged(); } } public void addOutput(final String outputid, final Metadata metadata) { if (!designMode()) { return; } if (outputid != null && metadata != null && !outputs.containsKey(outputid)) { outputs.put(outputid, factory.createOutput(this, metadata)); fireContextChanged(); } } public void executeTransformation() { if (!runMode()) { return; } synchronized (transformation) { transformation.importData(); transformation.processData(); transformation.exportData(); } } public void fireContextChanged() { final ContextEvent event = new ContextEvent(this); transformation.contextChange(event); for (final ContextListener listener : contextListeners.keySet()) { if (listener != transformation) { listener.contextChange(event); } } getWorkflow().fireContextChanged(event); } public void fireRemoved() { final ContextEvent event = new ContextEvent(this); transformation.contextRemoved(event); for (final ContextListener listener : contextListeners.keySet()) { if (listener != transformation) { listener.contextRemoved(event); } } getWorkflow().fireRemoved(event); } public Input getInput(final String inputid) { if (!designMode()) { return null; } return inputs.get(inputid); } public DataWrapper getInputWrapper(final String inputid) { if (runMode() || designMode()) { return null; } return inputs.get(inputid).getConnection().getDataWrapper(); } public Output getOutput(final String outputid) { if (!designMode()) { return null; } return outputs.get(outputid); } public DataWrapper getOutputWrapper(final String outputid) { if (runMode() || designMode()) { return null; } final Output output = outputs.get(outputid); if (!output.isConnected() && !output.isOptional()) { throw new IllegalStateException("Context should not be executable now"); } return outputs.get(outputid).getConnection().getDataWrapper(); } public Workflow getWorkflow() { return workflow.get(); } public boolean hasInput(final String inputid) { return inputs.containsKey(inputid); } public boolean hasListener(final ContextListener listener) { return listener != transformation && contextListeners.containsKey(listener); } public boolean hasOutput(final String outputid) { return outputs.containsKey(outputid); } @SuppressWarnings("unchecked") public boolean isExecutable() { // the contained transformation must be executable boolean executable = transformation.isExecutable(); // only optional ports can be unconnected if (executable) { final Iterable<Port> ports = new CompositeIterable<Port>(inputs.values(), outputs.values()); for (final Port port : ports) { if (!port.isOptional() && !port.isConnected()) { executable = false; break; } } } return executable; } public void mark() { if (!runMode()) { return; } assert runner != null; runner.mark(this); } public void removeContextListener(final ContextListener listener) { contextListeners.remove(listener); } public void removeInput(final String inputid) { if (!designMode()) { return; } inputs.remove(inputid); } public void removeOutput(final String outputid) { if (!designMode()) { return; } outputs.remove(outputid); } public void setRunner(final Runner runner) { if (runMode() || designMode()) { return; } this.runner = runner; } public void setTransformation(final Transformation transformation) { if (!designMode()) { return; } inputs.clear(); outputs.clear(); this.transformation = transformation; fireAddToContext(); } public void startExecution() { if (runMode() || designMode()) { return; } transformation.startExecution(this); } public void stopExecution() { if (runMode() || designMode()) { return; } transformation.stopExecution(); } public void sweep() { if (!runMode()) { return; } runner.sweep(this); } @Override public String toString() { return "Context of a " + transformation.getClass().getCanonicalName(); } private boolean designMode() { final Workflow wf = workflow.get(); return wf != null && wf.getMode() == Mode.DESIGN; } private void fireAddToContext() { final ContextEvent event = new ContextEvent(this); transformation.addToContext(event); for (final ContextListener listener : contextListeners.keySet()) { if (listener != transformation) { listener.addToContext(event); } } getWorkflow().fireAddToContext(event); } private boolean runMode() { final Workflow wf = workflow.get(); return wf != null && wf.getMode() == Mode.RUN; } }
apache-2.0
AleGogogo/MaoMaoRobot
app/src/main/java/com/example/lyw/maomaorobot/base/BaseCardView.java
1156
package com.example.lyw.maomaorobot.base; import android.content.Context; import android.view.LayoutInflater; import android.view.View; /** * Created by bluerain on 17-1-14. */ public abstract class BaseCardView<T> implements ICardItem { protected Context mContext; protected T mData; protected View mRootView; protected int mRes; private LayoutInflater mLayoutInflater; public void setRes(int res) { mRes = res; } public void setData(T data) { mData = data; } public void setContext(Context context) { mContext = context; mLayoutInflater = LayoutInflater.from(mContext); } protected abstract View onDraw(Context context, T data, LayoutInflater inflater); protected abstract void onBind(View rootView, T data, LayoutInflater inflater); @Override public View draw(Object data) { mData = (T) data; mRootView = onDraw(mContext, mData, mLayoutInflater); return mRootView; } @Override public void bind(View view, Object data) { mData = (T) data; onBind(mRootView, mData, mLayoutInflater); } }
apache-2.0
bencomp/dataverse
src/main/java/edu/harvard/iq/dataverse/api/datadeposit/MediaResourceManagerImpl.java
18759
package edu.harvard.iq.dataverse.api.datadeposit; import edu.harvard.iq.dataverse.DataFile; import edu.harvard.iq.dataverse.DataFileServiceBean; import edu.harvard.iq.dataverse.Dataset; import edu.harvard.iq.dataverse.DatasetServiceBean; import edu.harvard.iq.dataverse.DatasetVersion; import edu.harvard.iq.dataverse.Dataverse; import edu.harvard.iq.dataverse.EjbDataverseEngine; import edu.harvard.iq.dataverse.FileMetadata; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.impl.DeleteDataFileCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand; import edu.harvard.iq.dataverse.ingest.IngestServiceBean; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.swordapp.server.AuthCredentials; import org.swordapp.server.Deposit; import org.swordapp.server.DepositReceipt; import org.swordapp.server.MediaResource; import org.swordapp.server.MediaResourceManager; import org.swordapp.server.SwordAuthException; import org.swordapp.server.SwordConfiguration; import org.swordapp.server.SwordError; import org.swordapp.server.SwordServerException; import org.swordapp.server.UriRegistry; public class MediaResourceManagerImpl implements MediaResourceManager { private static final Logger logger = Logger.getLogger(MediaResourceManagerImpl.class.getCanonicalName()); @EJB EjbDataverseEngine commandEngine; @EJB DatasetServiceBean datasetService; @EJB DataFileServiceBean dataFileService; @EJB IngestServiceBean ingestService; @Inject SwordAuth swordAuth; @Inject UrlManager urlManager; @Override public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException { AuthenticatedUser user = swordAuth.auth(authCredentials); urlManager.processUrl(uri); String globalId = urlManager.getTargetIdentifier(); if (urlManager.getTargetType().equals("study") && globalId != null) { logger.fine("looking up dataset with globalId " + globalId); Dataset dataset = datasetService.findByGlobalId(globalId); if (dataset != null) { /** * @todo: support downloading of files (SWORD 2.0 Profile 6.4. - * Retrieving the content) * http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_retrievingcontent * * This ticket is mostly about terms of use: * https://github.com/IQSS/dataverse/issues/183 */ boolean getMediaResourceRepresentationSupported = false; if (getMediaResourceRepresentationSupported) { Dataverse dvThatOwnsDataset = dataset.getOwner(); if (swordAuth.hasAccessToModifyDataverse(user, dvThatOwnsDataset)) { /** * @todo Zip file download is being implemented in * https://github.com/IQSS/dataverse/issues/338 */ InputStream fixmeInputStream = new ByteArrayInputStream("FIXME: replace with zip of all dataset files".getBytes()); String contentType = "application/zip"; String packaging = UriRegistry.PACKAGE_SIMPLE_ZIP; boolean isPackaged = true; MediaResource mediaResource = new MediaResource(fixmeInputStream, contentType, packaging, isPackaged); return mediaResource; } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to get a media resource representation of the dataset with global ID " + dataset.getGlobalId()); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Downloading files via the SWORD-based Dataverse Data Deposit API is not (yet) supported: https://github.com/IQSS/dataverse/issues/183"); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't find dataset with global ID of " + globalId); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't dermine target type or identifier from URL: " + uri); } } @Override public DepositReceipt replaceMediaResource(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException { /** * @todo: Perhaps create a new version of a dataset here? * * "The server MUST effectively replace all the existing content in the * item, although implementations may choose to provide versioning or * some other mechanism for retaining the overwritten content." -- * http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_editingcontent_binary * * Also, if you enable this method, think about the SwordError currently * being returned by replaceOrAddFiles with shouldReplace set to true * and an empty zip uploaded. If no files are unzipped the user will see * a error about this but the files will still be deleted! */ throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Replacing the files of a dataset is not supported. Please delete and add files separately instead."); } @Override public void deleteMediaResource(String uri, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException { AuthenticatedUser user = swordAuth.auth(authCredentials); urlManager.processUrl(uri); String targetType = urlManager.getTargetType(); String fileId = urlManager.getTargetIdentifier(); if (targetType != null && fileId != null) { if ("file".equals(targetType)) { String fileIdString = urlManager.getTargetIdentifier(); if (fileIdString != null) { Long fileIdLong; try { fileIdLong = Long.valueOf(fileIdString); } catch (NumberFormatException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "File id must be a number, not '" + fileIdString + "'. URL was: " + uri); } if (fileIdLong != null) { logger.info("preparing to delete file id " + fileIdLong); DataFile fileToDelete = dataFileService.find(fileIdLong); if (fileToDelete != null) { Dataset dataset = fileToDelete.getOwner(); SwordUtil.datasetLockCheck(dataset); Dataset datasetThatOwnsFile = fileToDelete.getOwner(); Dataverse dataverseThatOwnsFile = datasetThatOwnsFile.getOwner(); if (swordAuth.hasAccessToModifyDataverse(user, dataverseThatOwnsFile)) { try { /** * @todo with only one command, should we be * falling back on the permissions system to * enforce if the user can delete a file or * not. If we do, a 403 Forbidden is * returned. For now, we'll have belt and * suspenders and do our normal sword auth * check. */ commandEngine.submit(new UpdateDatasetCommand(dataset, user, fileToDelete)); } catch (CommandException ex) { throw SwordUtil.throwSpecialSwordErrorWithoutStackTrace(UriRegistry.ERROR_BAD_REQUEST, "Could not delete file: " + ex); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify " + dataverseThatOwnsFile.getAlias()); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to find file id " + fileIdLong + " from URL: " + uri); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to find file id in URL: " + uri); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not file file to delete in URL: " + uri); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unsupported file type found in URL: " + uri); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Target or identifer not specified in URL: " + uri); } } @Override public DepositReceipt addResource(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException { boolean shouldReplace = false; return replaceOrAddFiles(uri, deposit, authCredentials, swordConfiguration, shouldReplace); } DepositReceipt replaceOrAddFiles(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration, boolean shouldReplace) throws SwordError, SwordAuthException, SwordServerException { AuthenticatedUser user = swordAuth.auth(authCredentials); urlManager.processUrl(uri); String globalId = urlManager.getTargetIdentifier(); if (urlManager.getTargetType().equals("study") && globalId != null) { logger.fine("looking up dataset with globalId " + globalId); Dataset dataset = datasetService.findByGlobalId(globalId); if (dataset == null) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset with global ID of " + globalId); } SwordUtil.datasetLockCheck(dataset); Dataverse dvThatOwnsDataset = dataset.getOwner(); if (!swordAuth.hasAccessToModifyDataverse(user, dvThatOwnsDataset)) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataset with global ID " + dataset.getGlobalId()); } // Right now we are only supporting UriRegistry.PACKAGE_SIMPLE_ZIP but // in the future maybe we'll support other formats? Rdata files? Stata files? /** * @todo decide if we want non zip files to work. Technically, now * that we're letting ingestService.createDataFiles unpack the zip * for us, the following *does* work: * * curl--data-binary @path/to/trees.png -H "Content-Disposition: * filename=trees.png" -H "Content-Type: image/png" -H "Packaging: * http://purl.org/net/sword/package/SimpleZip" * * We *might* want to continue to force API users to only upload zip * files so that some day we can support a including a file or files * that contain the metadata (i.e. description) for each file in the * zip: https://github.com/IQSS/dataverse/issues/723 */ if (!deposit.getPackaging().equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) { throw new SwordError(UriRegistry.ERROR_CONTENT, 415, "Package format " + UriRegistry.PACKAGE_SIMPLE_ZIP + " is required but format specified in 'Packaging' HTTP header was " + deposit.getPackaging()); } String uploadedZipFilename = deposit.getFilename(); DatasetVersion editVersion = dataset.getEditVersion(); if (deposit.getInputStream() == null) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Deposit input stream was null."); } int bytesAvailableInInputStream = 0; try { bytesAvailableInInputStream = deposit.getInputStream().available(); } catch (IOException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine number of bytes available in input stream: " + ex); } if (bytesAvailableInInputStream == 0) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Bytes available in input stream was " + bytesAvailableInInputStream + ". Please check the file you are attempting to deposit."); } /** * @todo Think about if we should instead pass in "application/zip" * rather than letting ingestService.createDataFiles() guess the * contentType by passing it "null". See also the note above about * SimpleZip vs. other contentTypes. */ String guessContentTypeForMe = null; List<DataFile> dataFiles = new ArrayList<>(); try { try { dataFiles = ingestService.createDataFiles(editVersion, deposit.getInputStream(), uploadedZipFilename, guessContentTypeForMe); } catch (EJBException ex) { Throwable cause = ex.getCause(); if (cause != null) { if (cause instanceof IllegalArgumentException) { /** * @todo should be safe to remove this catch of * EJBException and IllegalArgumentException once * this ticket is resolved: * * IllegalArgumentException: MALFORMED when * uploading certain zip files * https://github.com/IQSS/dataverse/issues/1021 */ throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles. Problem with zip file, perhaps: " + cause); } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles: " + cause); } } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles. No cause: " + ex.getMessage()); } } } catch (IOException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to dataset: " + ex.getMessage()); } if (!dataFiles.isEmpty()) { ingestService.addFiles(editVersion, dataFiles); } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No files to add to dataset. Perhaps the zip file was empty."); } Command<Dataset> cmd; cmd = new UpdateDatasetCommand(dataset, user); try { dataset = commandEngine.submit(cmd); } catch (CommandException ex) { throw returnEarly("Couldn't update dataset " + ex); } catch (EJBException ex) { /** * @todo stop bothering to catch an EJBException once this has * been implemented: * * Have commands catch ConstraintViolationException and turn * them into something that inherits from CommandException · * https://github.com/IQSS/dataverse/issues/1009 */ Throwable cause = ex; StringBuilder sb = new StringBuilder(); sb.append(ex.getLocalizedMessage()); while (cause.getCause() != null) { cause = cause.getCause(); sb.append(cause + " "); if (cause instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause; for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) { sb.append(" Invalid value \"").append(violation.getInvalidValue()).append("\" for ") .append(violation.getPropertyPath()).append(" at ") .append(violation.getLeafBean()).append(" - ") .append(violation.getMessage()); } } } throw returnEarly("EJBException: " + sb.toString()); } ingestService.startIngestJobs(dataset, user); ReceiptGenerator receiptGenerator = new ReceiptGenerator(); String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri); DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, dataset); return depositReceipt; } else { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to determine target type or identifier from URL: " + uri); } } /** * @todo get rid of this method */ private SwordError returnEarly(String error) { SwordError swordError = new SwordError(error); StackTraceElement[] emptyStackTrace = new StackTraceElement[0]; swordError.setStackTrace(emptyStackTrace); return swordError; } }
apache-2.0
ogregoire/fror-common
src/main/java/be/fror/common/io/ByteSink.java
1795
/* * Copyright 2015 Olivier Grégoire. * * 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 be.fror.common.io; import static be.fror.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UncheckedIOException; import java.io.Writer; import java.nio.charset.Charset; /** * * @author Olivier Grégoire */ public abstract class ByteSink { protected ByteSink() { } public final OutputStream openStream() throws UncheckedIOException { try { return doOpenStream(); } catch (IOException e) { throw new UncheckedIOException(e); } } protected abstract OutputStream doOpenStream() throws IOException; public CharSink asCharSink(Charset charset) { return new AsCharSink(checkNotNull(charset)); } private class AsCharSink extends CharSink { private final Charset charset; private AsCharSink(Charset charset) { this.charset = charset; } @Override protected Writer doOpenStream() throws IOException { return new OutputStreamWriter(ByteSink.this.doOpenStream(), charset); } @Override public String toString() { return ByteSink.this.toString() + ".asCharSink(" + charset + ")"; } } }
apache-2.0
JFJava/ris_repo
ris-dao/src/main/java/com/jfsoft/mapper/BaseCheckpartMapper.java
1753
/** * BaseCheckpartMapper.java * Copyright© 2017 北京金风易通科技有限公司 * All rights reserved. * ----------------------------------------------- * 2017-08-18 Created */ package com.jfsoft.mapper; import com.jfsoft.model.BaseCheckpart; import java.math.BigDecimal; import java.util.List; import java.util.Map; public interface BaseCheckpartMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table BASE_CHECKPART */ int deleteByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table BASE_CHECKPART */ int insert(BaseCheckpart record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table BASE_CHECKPART */ int insertSelective(BaseCheckpart record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table BASE_CHECKPART */ BaseCheckpart selectByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table BASE_CHECKPART */ int updateByPrimaryKeySelective(BaseCheckpart record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table BASE_CHECKPART */ int updateByPrimaryKey(BaseCheckpart record); List<BaseCheckpart> getCheckpartList(String areacode); BigDecimal getMaxCode(); List<BaseCheckpart> getPartByNo(Map<String,Object> params); List<BaseCheckpart> getPartList(String areacode); BaseCheckpart findByName(String name); }
apache-2.0
sherlok/sherlok_javaclient
src/test/java/org/sherlok/client/SherlokClientTest.java
1155
package org.sherlok.client; import static org.junit.Assert.assertEquals; import java.util.List; import java.util.Map.Entry; import org.junit.Ignore; import org.junit.Test; import org.sherlok.mappings.Annotation; import org.sherlok.mappings.SherlokResult; /** * Hum: cannot test this Sherlok client with Sherlok server, because of Maven * circular dependencies. However, this Sherlok client code is thouroughly * tested in Sherlok server (sherlok_core). */ @Ignore public class SherlokClientTest { final String DEFAULT_PIPELINE = "opennlp.ners.en"; final String TEST_TEXT = "Jack Burton (born April 29, 1954 in El Paso), also known as Jake Burton, is an American snowboarder and founder of Burton Snowboards."; @Test public void test() throws Exception { SherlokClient client = new SherlokClient(); SherlokResult res = client.annotate(DEFAULT_PIPELINE, TEST_TEXT); for (Entry<Integer, Annotation> a : res.getAnnotations().entrySet()) { System.out.println(a.getValue()); } List<Annotation> entities = res.get("NamedEntity"); assertEquals(3, entities.size()); } }
apache-2.0
venvich/pdt_28_vika
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/generator/GroupDataGenerator.java
2827
package ru.stqa.pft.addressbook.generator; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.XStream; import ru.stqa.pft.addressbook.model.GroupData; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class GroupDataGenerator { @Parameter (names = "-c", description = "Group count") public int count; @Parameter (names = "-f", description = "Target file") public String file; @Parameter (names = "-d", description = "Data format") public String format; public static void main(String[] args) throws IOException { GroupDataGenerator generator = new GroupDataGenerator(); JCommander jCommander = new JCommander(generator); try { jCommander.parse(args); } catch (ParameterException ex) { jCommander.usage(); return; } generator.run(); } private void run() throws IOException { List<GroupData> groups = generateGroups(count); if (format.equals("scv")) { saveAsCsv(groups, new File(file)); } else if (format.equals("xml")) { SaveAsXml(groups, new File(file)); } else if (format.equals("json")) { SaveAsJson(groups, new File(file)); } else { System.out.println("Unrecognized format " + format); } } private void SaveAsJson(List<GroupData> groups, File file) throws IOException { Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); String json = gson.toJson(groups); try (Writer writer = new FileWriter(file)) { writer.write(json); } } private void SaveAsXml(List<GroupData> groups, File file) throws IOException { XStream xstream = new XStream(); xstream.processAnnotations(GroupData.class); String xml = xstream.toXML(groups); try (Writer writer = new FileWriter(file)) { writer.write(xml); } } private void saveAsCsv(List<GroupData> groups, File file) throws IOException { System.out.println(new File(".").getAbsolutePath()); try (Writer writer = new FileWriter(file)) { for (GroupData group : groups) { writer.write(String.format("%s;%s;%s\n", group.getName(), group.getHeader(), group.getFooter())); } } } private List<GroupData> generateGroups(int count) { List<GroupData> groups = new ArrayList<GroupData>(); for (int i = 0; i < count; i++) { groups.add(new GroupData() .withName(String.format("Test %s", i)) .withHeader(String.format("Header %s", i)) .withFooter(String.format("Footer %s", i))); } return groups; } }
apache-2.0
littlezhou/hadoop
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/StaleNodeHandler.java
2596
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds.scm.node; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.protocol.DatanodeDetails; import org.apache.hadoop.hdds.scm.pipeline.Pipeline; import org.apache.hadoop.hdds.scm.pipeline.PipelineID; import org.apache.hadoop.hdds.scm.pipeline.PipelineManager; import org.apache.hadoop.hdds.scm.pipeline.RatisPipelineUtils; import org.apache.hadoop.hdds.server.events.EventHandler; import org.apache.hadoop.hdds.server.events.EventPublisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Set; /** * Handles Stale node event. */ public class StaleNodeHandler implements EventHandler<DatanodeDetails> { private static final Logger LOG = LoggerFactory.getLogger(StaleNodeHandler.class); private final NodeManager nodeManager; private final PipelineManager pipelineManager; private final Configuration conf; public StaleNodeHandler(NodeManager nodeManager, PipelineManager pipelineManager, OzoneConfiguration conf) { this.nodeManager = nodeManager; this.pipelineManager = pipelineManager; this.conf = conf; } @Override public void onMessage(DatanodeDetails datanodeDetails, EventPublisher publisher) { Set<PipelineID> pipelineIds = nodeManager.getPipelines(datanodeDetails); for (PipelineID pipelineID : pipelineIds) { try { Pipeline pipeline = pipelineManager.getPipeline(pipelineID); RatisPipelineUtils .finalizeAndDestroyPipeline(pipelineManager, pipeline, conf, true); } catch (IOException e) { LOG.info("Could not finalize pipeline={} for dn={}", pipelineID, datanodeDetails); } } } }
apache-2.0
ahome-it/ahome-tooling-common
src/main/java/com/ait/tooling/common/api/types/IIdentifiedTypeValue.java
768
/* Copyright (c) 2017 Ahome' Innovation Technologies. All rights reserved. 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.ait.tooling.common.api.types; public interface IIdentifiedTypeValue<V> extends IIdentifiedType, IIdentifiedValue<V> { }
apache-2.0
xsonorg/xson
src/main/java/org/xson/core/generator/LongGenerator.java
477
package org.xson.core.generator; import org.xson.core.XsonGenerator; import org.xson.core.asm.MethodVisitor; public class LongGenerator implements XsonGenerator { // @Override // public void generateWriterCode(MethodVisitor mv) { // mv.visitMethodInsn(INVOKESTATIC, WRITER_DESC, "getLongDateFrame", "(J)[B"); // } @Override public void generateReaderCode(MethodVisitor mv) { mv.visitMethodInsn(INVOKEVIRTUAL, READER_DESC, "getLong", "()J"); } }
apache-2.0
mfornos/humanize
humanize-slim/src/test/java/humanize/text/TestHumanizeFormat.java
2659
package humanize.text; import humanize.Humanize; import java.text.Format; import java.text.ParseException; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.testng.Assert; import org.testng.annotations.Test; public class TestHumanizeFormat { @Test public void basic() { Assert.assertEquals(Humanize.ordinal(10, Locale.ENGLISH), "10th"); FormatFactory factory = HumanizeFormatProvider.factory(); Format f = factory.getFormat("humanize", "ordinal", Locale.UK); Assert.assertEquals(f.format(10), "10th"); f = factory.getFormat("humanize", "binaryPrefix", Locale.UK); Assert.assertEquals(f.format(0), "0 bytes"); f = factory.getFormat("humanize", "binary.prefix", Locale.UK); Assert.assertEquals(f.format(0), "0 bytes"); f = factory.getFormat("humanize", "binary-prefix", Locale.UK); Assert.assertEquals(f.format(0), "0 bytes"); f = factory.getFormat("humanize", "binary_prefix", Locale.UK); Assert.assertEquals(f.format(0), "0 bytes"); f = factory.getFormat("humanize", "binary prefix", Locale.UK); Assert.assertEquals(f.format(0), "0 bytes"); f = factory.getFormat("humanize", "camelize", Locale.UK); Assert.assertEquals(f.format("hello world"), "helloWorld"); f = factory.getFormat("humanize", "metricPrefix", Locale.UK); Assert.assertEquals(f.format(10000000), "10M"); f = factory.getFormat("humanize", "oxford", Locale.UK); List<String> list = Arrays.asList(new String[] { "One", "Two" }); Assert.assertEquals(f.format(list), "One and Two"); Assert.assertNull(factory.getFormat("humanize", "none", Locale.UK)); } @Test public void invalidCall() { FormatFactory factory = HumanizeFormatProvider.factory(); Format f = factory.getFormat("humanize", "ordinal", Locale.UK); Assert.assertEquals(f.format(new Object[] { "juidui" }), "[invalid call: 'argument type mismatch']"); } @Test public void nestedFormatsTest() { List<String> list = Arrays.asList(new String[] { "One", "Two" }); Assert.assertEquals(Humanize.format(Locale.UK, "prefix {0,number} {1,humanize,oxford} suffix", 10, list), "prefix 10 One and Two suffix"); } @Test(expectedExceptions = UnsupportedOperationException.class) public void parse() throws ParseException { FormatFactory factory = HumanizeFormatProvider.factory(); Format f = factory.getFormat("humanize", "ordinal", Locale.UK); f.parseObject("any"); } }
apache-2.0
blad/nosey
example/src/androidTest/java/com/btellez/nosey/ApplicationTest.java
349
package com.btellez.nosey; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
shybovycha/buck
test/com/facebook/buck/util/zip/UnzipTest.java
10918
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util.zip; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import com.facebook.buck.io.file.MoreFiles; import com.facebook.buck.io.file.MorePosixFilePermissions; import com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemFactory; import com.facebook.buck.testutil.ZipArchive; import com.facebook.buck.testutil.integration.TemporaryPaths; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.Set; import java.util.zip.ZipEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class UnzipTest { private static final byte[] DUMMY_FILE_CONTENTS = "BUCK Unzip Test String!\nNihao\n".getBytes(); @Rule public TemporaryPaths tmpFolder = new TemporaryPaths(); private Path zipFile; @Before public void setUp() { zipFile = tmpFolder.getRoot().resolve("tmp.zip"); } @Test public void testExtractZipFile() throws InterruptedException, IOException { try (ZipArchive zipArchive = new ZipArchive(this.zipFile, true)) { zipArchive.add("1.bin", DUMMY_FILE_CONTENTS); zipArchive.add("subdir/2.bin", DUMMY_FILE_CONTENTS); zipArchive.addDir("emptydir"); } Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("1.bin"))); Path bin2 = extractFolder.toAbsolutePath().resolve("subdir/2.bin"); assertTrue(Files.exists(bin2)); assertTrue(Files.isDirectory(extractFolder.toAbsolutePath().resolve("emptydir"))); try (InputStream input = Files.newInputStream(bin2)) { byte[] buffer = new byte[DUMMY_FILE_CONTENTS.length]; int bytesRead = input.read(buffer, 0, DUMMY_FILE_CONTENTS.length); assertEquals(DUMMY_FILE_CONTENTS.length, bytesRead); for (int i = 0; i < DUMMY_FILE_CONTENTS.length; i++) { assertEquals(DUMMY_FILE_CONTENTS[i], buffer[i]); } } assertEquals( ImmutableList.of(extractFolder.resolve("1.bin"), extractFolder.resolve("subdir/2.bin")), result); } @Test public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws InterruptedException, IOException { // getFakeTime returs time with some non-zero millis. By doing division and multiplication by // 1000 we get rid of that. final long time = ZipConstants.getFakeTime() / 1000 * 1000; // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("test.exe"); entry.setUnixMode( (int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------"))); entry.setSize(DUMMY_FILE_CONTENTS.length); entry.setMethod(ZipEntry.STORED); entry.setTime(time); zip.putArchiveEntry(entry); zip.write(DUMMY_FILE_CONTENTS); zip.closeArchiveEntry(); } // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable. Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); Path exe = extractFolder.toAbsolutePath().resolve("test.exe"); assertTrue(Files.exists(exe)); assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time)); assertTrue(Files.isExecutable(exe)); assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result); } @Test public void testExtractSymlink() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("link.txt"); entry.setUnixMode((int) MoreFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); zip.putArchiveEntry(entry); zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); } @Test public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("link.txt"); entry.setUnixMode((int) MoreFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); // Mark the file as being executable. Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE); long externalAttributes = entry.getExternalAttributes() + (MorePosixFilePermissions.toMode(filePermissions) << 16); entry.setExternalAttributes(externalAttributes); zip.putArchiveEntry(entry); zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); } @Test public void testExtractWeirdIndex() throws InterruptedException, IOException { try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz")); zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length); zip.closeArchiveEntry(); zip.putArchiveEntry(new ZipArchiveEntry("foo/")); zip.closeArchiveEntry(); zip.putArchiveEntry(new ZipArchiveEntry("qux/")); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo"))); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar/baz"))); assertEquals(ImmutableList.of(extractFolder.resolve("foo/bar/baz")), result); } @Test public void testNonCanonicalPaths() throws InterruptedException, IOException { String names[] = { "foo/./", "foo/./bar/", "foo/./bar/baz.cpp", "foo/./bar/baz.h", }; try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { for (String name : names) { zip.putArchiveEntry(new ZipArchiveEntry(name)); zip.closeArchiveEntry(); } } Path extractFolder = tmpFolder.newFolder(); Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); for (String name : names) { assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name))); } Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); for (String name : names) { assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name))); } } @Test public void testParentDirPaths() throws InterruptedException, IOException { try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { // It seems very unlikely that a zip file would contain ".." paths, but handle it anyways. zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/")); zip.closeArchiveEntry(); zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/../")); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); Unzip.extractZipFile( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo"))); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar"))); } }
apache-2.0
michalkurka/h2o-3
h2o-extensions/target-encoder/src/main/java/ai/h2o/targetencoding/TargetEncoderModel.java
32893
package ai.h2o.targetencoding; import hex.Model; import hex.ModelCategory; import hex.ModelMetrics; import water.*; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Frame; import water.fvec.Vec; import water.fvec.task.FillNAWithDoubleValueTask; import water.logging.Logger; import water.logging.LoggerFactory; import water.udf.CFuncRef; import water.util.*; import java.util.*; import java.util.PrimitiveIterator.OfInt; import java.util.stream.IntStream; import java.util.stream.Stream; import static ai.h2o.targetencoding.TargetEncoderHelper.*; import static ai.h2o.targetencoding.interaction.InteractionSupport.addFeatureInteraction; public class TargetEncoderModel extends Model<TargetEncoderModel, TargetEncoderModel.TargetEncoderParameters, TargetEncoderModel.TargetEncoderOutput> { public static final String ALGO_NAME = "TargetEncoder"; public static final int NO_FOLD = -1; static final String NA_POSTFIX = "_NA"; static final String TMP_COLUMN_POSTFIX = "_tmp"; static final String ENCODED_COLUMN_POSTFIX = "_te"; static final BlendingParams DEFAULT_BLENDING_PARAMS = new BlendingParams(10, 20); private static final Logger logger = LoggerFactory.getLogger(TargetEncoderModel.class); public enum DataLeakageHandlingStrategy { LeaveOneOut, KFold, None, } public static class TargetEncoderParameters extends Model.Parameters { public String[][] _columns_to_encode; public boolean _blending = false; public double _inflection_point = DEFAULT_BLENDING_PARAMS.getInflectionPoint(); public double _smoothing = DEFAULT_BLENDING_PARAMS.getSmoothing(); public DataLeakageHandlingStrategy _data_leakage_handling = DataLeakageHandlingStrategy.None; public double _noise = 0.01; public boolean _keep_original_categorical_columns = true; // not a good default, but backwards compatible. boolean _keep_interaction_columns = false; // not exposed: convenient for testing. @Override public String algoName() { return ALGO_NAME; } @Override public String fullName() { return "TargetEncoder"; } @Override public String javaName() { return TargetEncoderModel.class.getName(); } @Override public long progressUnits() { return 1; } public BlendingParams getBlendingParameters() { return _blending ? _inflection_point!=0 && _smoothing!=0 ? new BlendingParams(_inflection_point, _smoothing) : DEFAULT_BLENDING_PARAMS : null; } @Override protected boolean defaultDropConsCols() { return false; } } public static class TargetEncoderOutput extends Model.Output { public final TargetEncoderParameters _parms; public final int _nclasses; public ColumnsToSingleMapping[] _input_to_encoding_column; // maps input columns (or groups of columns) to the single column being effectively encoded (= key in _target_encoding_map). public ColumnsMapping[] _input_to_output_columns; // maps input columns (or groups of columns) to their corresponding encoded one(s). public IcedHashMap<String, Frame> _target_encoding_map; public IcedHashMap<String, Boolean> _te_column_to_hasNAs; //XXX: Map is a wrong choice for this, IcedHashSet would be perfect though public TargetEncoderOutput(TargetEncoder te) { super(te); _parms = te._parms; _nclasses = te.nclasses(); } void init(IcedHashMap<String, Frame> teMap, ColumnsToSingleMapping[] columnsToEncodeMapping) { _target_encoding_map = teMap; _input_to_encoding_column = columnsToEncodeMapping; _input_to_output_columns = buildInOutColumnsMapping(); _te_column_to_hasNAs = buildCol2HasNAsMap(); _model_summary = constructSummary(); } /** * builds the name of encoded columns */ private ColumnsMapping[] buildInOutColumnsMapping() { ColumnsMapping[] encMapping = new ColumnsMapping[_input_to_encoding_column.length]; for (int i=0; i < encMapping.length; i++) { ColumnsToSingleMapping toEncode = _input_to_encoding_column[i]; String[] groupCols = toEncode.from(); String columnToEncode = toEncode.toSingle(); Frame encodings = _target_encoding_map.get(columnToEncode); String[] encodedColumns = listUsedTargetClasses().mapToObj(tc -> encodedColumnName(columnToEncode, tc, encodings.vec(TARGETCLASS_COL)) ).toArray(String[]::new); encMapping[i] = new ColumnsMapping(groupCols, encodedColumns); } return encMapping; } private IcedHashMap<String, Boolean> buildCol2HasNAsMap() { final IcedHashMap<String, Boolean> col2HasNAs = new IcedHashMap<>(); for (Map.Entry<String, Frame> entry : _target_encoding_map.entrySet()) { String teColumn = entry.getKey(); Frame encodingsFrame = entry.getValue(); int teColCard = _parms.train().vec(teColumn) == null ? -1 // justifies the >0 test below: if teColumn is a transient (generated for interactions and therefore not in train), it can't have NAs as they're all already encoded. : _parms.train().vec(teColumn).cardinality(); boolean hasNAs = teColCard > 0 && teColCard < encodingsFrame.vec(teColumn).cardinality(); //XXX: _parms.train().vec(teColumn).naCnt() > 0 ? col2HasNAs.put(teColumn, hasNAs); } return col2HasNAs; } private IntStream listUsedTargetClasses() { return _nclasses == 1 ? IntStream.of(NO_TARGET_CLASS) // regression : _nclasses == 2 ? IntStream.of(1) // binary (use only positive target) : IntStream.range(1, _nclasses); // multiclass (skip only the 0 target for symmetry with binary) } private TwoDimTable constructSummary(){ TwoDimTable summary = new TwoDimTable( "Target Encoder model summary", "Summary for target encoder model", new String[_input_to_output_columns.length], new String[]{"Original name(s)", "Encoded column name(s)"}, new String[]{"string", "string"}, null, null ); for (int i = 0; i < _input_to_output_columns.length; i++) { ColumnsMapping mapping = _input_to_output_columns[i]; summary.set(i, 0, String.join(", ", mapping.from())); summary.set(i, 1, String.join(", ", mapping.to())); } return summary; } @Override public ModelCategory getModelCategory() { return ModelCategory.TargetEncoder; } } private static String encodedColumnName(String columnToEncode, int targetClass, Vec targetCol) { if (targetClass == NO_TARGET_CLASS || targetCol == null) { return columnToEncode + ENCODED_COLUMN_POSTFIX; } else { String targetClassName = targetCol.domain()[targetClass]; return columnToEncode + "_" + StringUtils.sanitizeIdentifier(targetClassName) + ENCODED_COLUMN_POSTFIX; } } /******* Start TargetEncoderModel per se *******/ public TargetEncoderModel(Key<TargetEncoderModel> selfKey, TargetEncoderParameters parms, TargetEncoderOutput output) { super(selfKey, parms, output); } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { throw H2O.unimpl("No Model Metrics for TargetEncoder."); } public Frame transformTraining(Frame fr) { return transformTraining(fr, NO_FOLD); } public Frame transformTraining(Frame fr, int outOfFold) { assert outOfFold == NO_FOLD || _parms._data_leakage_handling == DataLeakageHandlingStrategy.KFold; return transform(fr, true, outOfFold, _parms.getBlendingParameters(), _parms._noise); } public Frame transform(Frame fr) { return transform(fr, _parms.getBlendingParameters(), _parms._noise); } public Frame transform(Frame fr, BlendingParams blendingParams, double noiseLevel) { return transform(fr, false, NO_FOLD, blendingParams, noiseLevel); } /** * Applies target encoding to unseen data during training. * This means that DataLeakageHandlingStrategy is enforced to None. * * In the context of Target Encoding, {@link #transform(Frame, BlendingParams, double)} should be used to encode new data. * Whereas {@link #transformTraining(Frame)} should be used to encode training data. * * @param fr Data to transform * @param asTraining true iff transforming training data. * @param outOfFold if provided (if not = {@value NO_FOLD}), if asTraining=true, and if the model was trained with Kfold strategy, * then the frame will be encoded by aggregating encodings from all folds except this one. * This is mainly used during cross-validation. * @param blendingParams Parameters for blending. If null, blending parameters from models parameters are loaded. * If those are not set, DEFAULT_BLENDING_PARAMS from TargetEncoder class are used. * @param noiseLevel Level of noise applied (use -1 for default noise level, 0 to disable noise). * @return An instance of {@link Frame} with transformed fr, registered in DKV. */ public Frame transform(Frame fr, boolean asTraining, int outOfFold, BlendingParams blendingParams, double noiseLevel) { if (!canApplyTargetEncoding(fr)) return fr; Frame adaptFr = null; try { adaptFr = adaptForEncoding(fr); return applyTargetEncoding( adaptFr, asTraining, outOfFold, blendingParams, noiseLevel, null ); } finally { if (adaptFr != null) Frame.deleteTempFrameAndItsNonSharedVecs(adaptFr, fr); } } @Override protected double[] score0(double data[], double preds[]){ throw new UnsupportedOperationException("TargetEncoderModel doesn't support scoring on raw data. Use transform() or score() instead."); } /** * {@link #score(Frame)} always encodes as if the data were new (ie. not training data). */ @Override public Frame score(Frame fr, String destination_key, Job j, boolean computeMetrics, CFuncRef customMetricFunc) throws IllegalArgumentException { if (!canApplyTargetEncoding(fr)) { Frame res = new Frame(Key.make(destination_key), fr.names(), fr.vecs()); DKV.put(res); return res; } Frame adaptFr = null; try { adaptFr = adaptForEncoding(fr); return applyTargetEncoding( adaptFr, false, NO_FOLD, _parms.getBlendingParameters(), _parms._noise, Key.make(destination_key) ); } finally { if (adaptFr != null) Frame.deleteTempFrameAndItsNonSharedVecs(adaptFr, fr); } } private Frame adaptForEncoding(Frame fr) { Frame adaptFr = new Frame(fr); Map<String, Integer> nameToIdx = nameToIndex(fr); for (int i=0; i<_output._names.length; i++) { String col = _output._names[i]; String[] domain = _output._domains[i]; int toAdaptIdx; if (domain != null && (toAdaptIdx = nameToIdx.getOrDefault(col, -1)) >= 0) { Vec toAdapt = adaptFr.vec(toAdaptIdx); if (!Arrays.equals(toAdapt.domain(), domain)) { Vec adapted = toAdapt.adaptTo(domain); adaptFr.replace(toAdaptIdx, adapted); } } } return adaptFr; } private boolean canApplyTargetEncoding(Frame fr) { Set<String> frColumns = new HashSet<>(Arrays.asList(fr.names())); boolean canApply = Arrays.stream(_output._input_to_encoding_column) .map(m -> Arrays.asList(m.from())) .anyMatch(frColumns::containsAll); if (!canApply) { logger.info("Frame "+fr._key+" has no columns to encode with TargetEncoder, skipping it: " + "columns="+Arrays.toString(fr.names())+", " + "target encoder columns="+Arrays.deepToString(Arrays.stream(_output._input_to_encoding_column).map(ColumnsMapping::from).toArray(String[][]::new)) ); } return canApply; } /** * Core method for applying pre-calculated encodings to the dataset. * * @param data dataset that will be used as a base for creation of encodings . * @param asTraining is true, the original dataLeakageStrategy is applied, otherwise this is forced to {@link DataLeakageHandlingStrategy#None}. * @param blendingParams this provides parameters allowing to mitigate the effect * caused by small observations of some categories when computing their encoded value. * Use null to disable blending. * @param noise amount of noise to add to the final encodings. * Use 0 to disable noise. * Use -1 to use the default noise level computed from the target. * @param resultKey key of the result frame * @return a new frame with the encoded columns. */ Frame applyTargetEncoding(Frame data, boolean asTraining, int outOfFold, BlendingParams blendingParams, double noise, Key<Frame> resultKey) { final String targetColumn = _parms._response_column; final String foldColumn = _parms._fold_column; final DataLeakageHandlingStrategy dataLeakageHandlingStrategy = asTraining ? _parms._data_leakage_handling : DataLeakageHandlingStrategy.None; final long seed = _parms._seed; assert outOfFold == NO_FOLD || dataLeakageHandlingStrategy == DataLeakageHandlingStrategy.KFold; // early check on frame requirements switch (dataLeakageHandlingStrategy) { case KFold: if (data.find(foldColumn) < 0) throw new H2OIllegalArgumentException("KFold strategy requires a fold column `"+_parms._fold_column+"` like the one used during training."); break; case LeaveOneOut: if (data.find(targetColumn) < 0) // Note: for KFold strategy we don't need targetColumn so that we can exclude values from // current fold - as everything is already precomputed and stored in encoding map. // This is not the case with LeaveOneOut when we need to subtract current row's value and for that // we need to make sure that response column is provided and is a binary categorical column. throw new H2OIllegalArgumentException("LeaveOneOut strategy requires a response column `"+_parms._response_column+"` like the one used during training."); break; } // applying defaults if (noise < 0 ) { noise = defaultNoiseLevel(data, data.find(targetColumn)); logger.warn("No noise level specified, using default noise level: "+noise); } if (resultKey == null){ resultKey = Key.make(); } EncodingStrategy strategy; switch (dataLeakageHandlingStrategy) { case KFold: strategy = new KFoldEncodingStrategy(foldColumn, outOfFold, blendingParams, noise, seed); break; case LeaveOneOut: strategy = new LeaveOneOutEncodingStrategy(targetColumn, blendingParams, noise, seed); break; case None: default: strategy = new DefaultEncodingStrategy(blendingParams, noise, seed); break; } List<Keyed> tmps = new ArrayList<>(); Frame workingFrame = null; Key<Frame> tmpKey; try { workingFrame = makeWorkingFrame(data);; tmpKey = workingFrame._key; for (ColumnsToSingleMapping columnsToEncode: _output._input_to_encoding_column) { // TODO: parallelize this, should mainly require change in naming of num/den columns String[] colGroup = columnsToEncode.from(); String columnToEncode = columnsToEncode.toSingle(); Frame encodings = _output._target_encoding_map.get(columnToEncode); assert encodings != null; // passing the interaction domain obtained during training: // - this ensures that the interaction column will have the same domain as in training (no need to call adaptTo on the new Vec). // - this improves speed when creating the interaction column (no need to extract the domain). // - unseen values/interactions are however represented as NAs in the new column, which is acceptable as TE encodes them in the same way anyway. int colIdx = addFeatureInteraction(workingFrame, colGroup, columnsToEncode.toDomain()); if (colIdx < 0) { logger.warn("Column "+Arrays.toString(colGroup)+" is missing in frame "+data._key); continue; } assert workingFrame.name(colIdx).equals(columnToEncode); // if not applying encodings to training data, then get rid of the foldColumn in encodings. if (dataLeakageHandlingStrategy != DataLeakageHandlingStrategy.KFold && encodings.find(foldColumn) >= 0) { encodings = groupEncodingsByCategory(encodings, encodings.find(columnToEncode)); tmps.add(encodings); } imputeCategoricalColumn(workingFrame, colIdx, columnToEncode + NA_POSTFIX); for (OfInt it = _output.listUsedTargetClasses().iterator(); it.hasNext(); ) { int tc = it.next(); try { workingFrame = strategy.apply(workingFrame, columnToEncode, encodings, tc); } finally { DKV.remove(tmpKey); tmpKey = workingFrame._key; } } // end for each target if (!_parms._keep_interaction_columns && colGroup.length > 1) tmps.add(workingFrame.remove(colIdx)); } // end for each columnToEncode if (!_parms._keep_original_categorical_columns) { Set<String> removed = new HashSet<>(); for (ColumnsMapping columnsToEncode: _output._input_to_encoding_column) { for (String col: columnsToEncode.from()) { if (removed.contains(col)) continue; tmps.add(workingFrame.remove(col)); removed.add(col); } } } DKV.remove(tmpKey); workingFrame._key = resultKey; reorderColumns(workingFrame); DKV.put(workingFrame); return workingFrame; } catch (Exception e) { if (workingFrame != null) workingFrame.delete(); throw e; } finally { for (Keyed tmp : tmps) tmp.remove(); } } private double defaultNoiseLevel(Frame fr, int targetIndex) { double defaultNoiseLevel = 0.01; double noiseLevel = 0.0; // When noise is not provided and there is no response column in the `data` frame -> no noise will be added to transformations if (targetIndex >= 0) { Vec targetVec = fr.vec(targetIndex); noiseLevel = targetVec.isNumeric() ? defaultNoiseLevel * (targetVec.max() - targetVec.min()) : defaultNoiseLevel; } return noiseLevel; } /** * Ideally there should be no need to deep copy columns that are not listed as input in _input_to_output_columns. * However if we keep the original columns in the output, then they are deleted in the model integration: {@link hex.ModelBuilder#trackEncoded}. * On the other side, if copied as a "ShallowVec" (extending WrappedVec) to prevent deletion of data in trackEncoded, * then we expose WrappedVec to the client it all non-integration use cases, which is strongly discouraged. * Catch-22 situation, so keeping the deepCopy for now as is occurs only for predictions, so the data are usually smaller. * @param fr * @return the working frame used to make predictions */ private Frame makeWorkingFrame(Frame fr) { return fr.deepCopy(Key.make().toString()); } /** * For model integration, we need to ensure that columns are offered to the model in a consistent order. * After TE encoding, columns are always in the following order: * <ol> * <li>non-categorical predictors present in training frame</li> * <li>TE-encoded predictors</li> * <li>remaining categorical predictors present in training frame</li> * <li>remaining predictors not present in training frame</li> * <li>non-predictors</li> * </ol> * This way, categorical encoder can later encode the remaining categorical predictors * without changing the index of TE cols: somehow necessary when integrating TE in the model Mojo. * * @param fr the frame whose columns need to be reordered. */ private void reorderColumns(Frame fr) { String[] toTheEnd = _parms.getNonPredictors(); Map<String, Integer> nameToIdx = nameToIndex(fr); List<Integer> toAppendAfterNumericals = new ArrayList<>(); String[] trainColumns = _output._names; Set<String> trainCols = new HashSet<>(Arrays.asList(trainColumns)); String[] notInTrainColumns = Arrays.stream(fr.names()) .filter(c -> !trainCols.contains(c)) .toArray(String[]::new); int[] newOrder = new int[fr.numCols()]; int offset = 0; for (String col : trainColumns) { if (nameToIdx.containsKey(col) && !ArrayUtils.contains(toTheEnd, col)) { int idx = nameToIdx.get(col); if (fr.vec(idx).isCategorical()) { toAppendAfterNumericals.add(idx); //first appending categoricals } else { newOrder[offset++] = idx; //adding all non-categoricals first } } } String[] encodedColumns = Arrays.stream(_output._input_to_output_columns) .flatMap(m -> Stream.of(m.to())) .toArray(String[]::new); Set<String> encodedCols = new HashSet<>(Arrays.asList(encodedColumns)); for (String col : encodedColumns) { // TE-encoded cols if (nameToIdx.containsKey(col)) newOrder[offset++] = nameToIdx.get(col); } for (String col : notInTrainColumns) { if (!encodedCols.contains(col)) toAppendAfterNumericals.add(nameToIdx.get(col)); // appending columns only in fr } for (String col : toTheEnd) { // then appending the trailing columns if (nameToIdx.containsKey(col)) toAppendAfterNumericals.add(nameToIdx.get(col)); } for (int idx : toAppendAfterNumericals) newOrder[offset++] = idx; fr.reOrder(newOrder); } @Override public TargetEncoderMojoWriter getMojo() { return new TargetEncoderMojoWriter(this); } @Override protected Futures remove_impl(Futures fs, boolean cascade) { if (_output._target_encoding_map != null) { for (Frame encodings : _output._target_encoding_map.values()) { encodings.delete(); } } return super.remove_impl(fs, cascade); } private static abstract class EncodingStrategy { BlendingParams _blendingParams; double _noise; long _seed; public EncodingStrategy(BlendingParams blendingParams, double noise, long seed) { _blendingParams = blendingParams; _noise = noise; _seed = seed; } public Frame apply(Frame fr, String columnToEncode, Frame encodings, int targetClass) { try { Scope.enter(); Frame appliedEncodings; int tcIdx = encodings.find(TARGETCLASS_COL); if (tcIdx < 0) { appliedEncodings = encodings; } else { appliedEncodings = filterByValue(encodings, tcIdx, targetClass); Scope.track(appliedEncodings); appliedEncodings.remove(TARGETCLASS_COL); } String encodedColumn = encodedColumnName(columnToEncode, targetClass, tcIdx < 0 ? null : encodings.vec(tcIdx)); Frame encoded = doApply(fr, columnToEncode, appliedEncodings, encodedColumn, targetClass); Scope.untrack(encoded); return encoded; } finally { Scope.exit(); } } public abstract Frame doApply(Frame fr, String columnToEncode, Frame encodings, String encodedColumn, int targetClass); protected void applyNoise(Frame frame, int columnIdx, double noiseLevel, long seed) { if (noiseLevel > 0) addNoise(frame, columnIdx, noiseLevel, seed); } /** FIXME: this method is modifying the original fr column in-place, one of the reasons why we currently need a complete deep-copy of the training frame... */ protected void imputeMissingValues(Frame fr, int columnIndex, double imputedValue) { Vec vec = fr.vec(columnIndex); assert vec.get_type() == Vec.T_NUM : "Imputation of missing value is supported only for numerical vectors."; if (vec.naCnt() > 0) { new FillNAWithDoubleValueTask(columnIndex, imputedValue).doAll(fr); if (logger.isInfoEnabled()) logger.info(String.format("Frame with id = %s was imputed with posterior value = %f ( %d rows were affected)", fr._key, imputedValue, vec.naCnt())); } } //XXX: usage of this method is confusing: // - if there was no NAs during training, we can only impute missing values on encoded column with priorMean (there's no posterior to blend with). // - if there was NAs during training, then encodings must contain entries for the NA category, so true NAs will be properly encoded at this point. // Therefore, we impute only unseen categories, which we can decide to encode with priorMean (after all we don't have posterior for this new category), // or as if these were true NAs: this is what the code below does, but it doesn't look fully justified, except maybe to reduce the leakage from priorMean. // If this is useful to reduce leakage, shouldn't we also use it in LOO + KFold strategies? protected double valueForImputation(String columnToEncode, Frame encodings, double priorMean, BlendingParams blendingParams) { assert encodings.name(0).equals(columnToEncode); int nRows = (int) encodings.numRows(); String lastDomain = encodings.domains()[0][nRows - 1]; boolean hadMissingValues = lastDomain.equals(columnToEncode + NA_POSTFIX); double numeratorNA = encodings.vec(NUMERATOR_COL).at(nRows - 1); long denominatorNA = encodings.vec(DENOMINATOR_COL).at8(nRows - 1); double posteriorNA = numeratorNA / denominatorNA; boolean useBlending = blendingParams != null; return !hadMissingValues ? priorMean // no NA during training, so no posterior, the new (unseen) cat can only be encoded using priorMean. : useBlending ? getBlendedValue(posteriorNA, priorMean, denominatorNA, blendingParams) // consider new (unseen) cat as a true NA + apply blending. : posteriorNA; // consider new (unseen) cat as a true NA + no blending. } protected void removeNumeratorAndDenominatorColumns(Frame fr) { Vec removedNumerator = fr.remove(NUMERATOR_COL); removedNumerator.remove(); Vec removedDenominator = fr.remove(DENOMINATOR_COL); removedDenominator.remove(); } } private static class KFoldEncodingStrategy extends EncodingStrategy { String _foldColumn; int _outOfFold; public KFoldEncodingStrategy(String foldColumn, int outOfFold, BlendingParams blendingParams, double noise, long seed) { super(blendingParams, noise, seed); _foldColumn = foldColumn; _outOfFold = outOfFold; } @Override public Frame doApply(Frame fr, String columnToEncode, Frame encodings, String encodedColumn, int targetClass) { Frame workingFrame = fr; int teColumnIdx = fr.find(columnToEncode); int foldColIdx; if (_outOfFold== NO_FOLD) { foldColIdx = fr.find(_foldColumn); } else { workingFrame = new Frame(fr); Vec tmpFoldCol = workingFrame.anyVec().makeCon(_outOfFold); Scope.track(tmpFoldCol); workingFrame.add(new String[] {_foldColumn+TMP_COLUMN_POSTFIX}, new Vec[]{tmpFoldCol}); foldColIdx = workingFrame.numCols()-1; } int encodingsFoldColIdx = encodings.find(_foldColumn); int encodingsTEColIdx = encodings.find(columnToEncode); long[] foldValues = getUniqueColumnValues(encodings, encodingsFoldColIdx); int maxFoldValue = (int) ArrayUtils.maxValue(foldValues); double priorMean = computePriorMean(encodings); //FIXME: we want prior for the outOfFold encodings Frame joinedFrame = mergeEncodings( workingFrame, encodings, teColumnIdx, foldColIdx, encodingsTEColIdx, encodingsFoldColIdx, maxFoldValue ); Scope.track(joinedFrame); if (_outOfFold!= NO_FOLD) { joinedFrame.remove(foldColIdx); } //XXX: the priorMean here is computed on the entire training set, regardless of the folding structure, therefore it introduces a data leakage. // Shouldn't we instead provide a priorMean per fold? // We should be able to compute those k priorMeans directly from the encodings Frame, so it doesn't require any change in the Mojo. // However, applyEncodings would also need an additional arg for the foldColumn. int encodedColIdx = applyEncodings(joinedFrame, encodedColumn, priorMean, _blendingParams); applyNoise(joinedFrame, encodedColIdx, _noise, _seed); // Cases when we can introduce NAs in the encoded column: // - if the column to encode contains categories unseen during training (including NA): // however this is very unlikely as KFold strategy is usually used when applying TE on the training frame. // - if during training, a category is present only in one fold, // then this couple (category, fold) will be missing in the encodings frame, // and mergeEncodings will put NAs for both num and den, turning into a NA in the encoded column after applyEncodings. imputeMissingValues(joinedFrame, encodedColIdx, priorMean); //XXX: same concern as above regarding priorMean. removeNumeratorAndDenominatorColumns(joinedFrame); return joinedFrame; } } private static class LeaveOneOutEncodingStrategy extends EncodingStrategy { String _targetColumn; public LeaveOneOutEncodingStrategy(String targetColumn, BlendingParams blendingParams, double noise, long seed) { super(blendingParams, noise, seed); _targetColumn = targetColumn; } @Override public Frame doApply(Frame fr, String columnToEncode, Frame encodings, String encodedColumn, int targetClass) { int teColumnIdx = fr.find(columnToEncode); int encodingsTEColIdx = encodings.find(columnToEncode); double priorMean = computePriorMean(encodings); Frame joinedFrame = mergeEncodings(fr, encodings, teColumnIdx, encodingsTEColIdx); Scope.track(joinedFrame); subtractTargetValueForLOO(joinedFrame, _targetColumn, targetClass); int encodedColIdx = applyEncodings(joinedFrame, encodedColumn, priorMean, _blendingParams); applyNoise(joinedFrame, encodedColIdx, _noise, _seed); // Cases when we can introduce NAs in the encoded column: // - only when the column to encode contains categories unseen during training (including NA). imputeMissingValues(joinedFrame, encodedColIdx, priorMean); removeNumeratorAndDenominatorColumns(joinedFrame); return joinedFrame; } } private static class DefaultEncodingStrategy extends EncodingStrategy { public DefaultEncodingStrategy(BlendingParams blendingParams, double noise, long seed) { super(blendingParams, noise, seed); } @Override public Frame doApply(Frame fr, String columnToEncode, Frame encodings, String encodedColumn, int targetClass) { int teColumnIdx = fr.find(columnToEncode); int encodingsTEColIdx = encodings.find(columnToEncode); double priorMean = computePriorMean(encodings); Frame joinedFrame = mergeEncodings(fr, encodings, teColumnIdx, encodingsTEColIdx); Scope.track(joinedFrame); int encodedColIdx = applyEncodings(joinedFrame, encodedColumn, priorMean, _blendingParams); applyNoise(joinedFrame, encodedColIdx, _noise, _seed); // Cases when we can introduce NAs in the encoded column: // - only when the column to encode contains categories unseen during training (including NA). // We impute NAs with mean computed from training set, which is a data leakage. // Note: In case of creating encoding map based on the holdout set we'd better use stratified sampling. // Maybe even choose size of holdout taking into account size of the minimal set that represents all levels. // Otherwise there are higher chances to get NA's for unseen categories. double valueForImputation = valueForImputation(columnToEncode, encodings, priorMean, _blendingParams); imputeMissingValues(joinedFrame, encodedColIdx, valueForImputation); removeNumeratorAndDenominatorColumns(joinedFrame); return joinedFrame; } } }
apache-2.0
brandt/GridSphere
src/org/gridsphere/provider/portletui/tags/DialogButtonTag.java
517
package org.gridsphere.provider.portletui.tags; import javax.servlet.jsp.JspException; /** * The <code>TableRowTag</code> represents a table row element that is conatined within a <code>TableTag</code> * and itself may contain <code>TableCellTag</code>s */ public class DialogButtonTag extends DialogTag { public int doStartTag() throws JspException { isLink = false; return super.doStartTag(); } public int doEndTag() throws JspException { return super.doEndTag(); } }
apache-2.0
csmith932/uas-schedule-generator
swac-common/src/main/java/gov/faa/ang/swac/common/geometry/kml/TrajectoryKmlRecord.java
3390
package gov.faa.ang.swac.common.geometry.kml; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import gov.faa.ang.swac.common.flightmodeling.Aircraft; import gov.faa.ang.swac.common.flightmodeling.FlightLeg; import gov.faa.ang.swac.common.geometry.GCPointAltTime; import gov.faa.ang.swac.common.geometry.kml.KmlUtilities.AltitudeMode; import gov.faa.ang.swac.common.geometry.kml.KmlUtilities.Color; import gov.faa.ang.swac.common.geometry.kml.KmlUtilities.GCClass; import gov.faa.ang.swac.datalayer.storage.fileio.TextSerializable; import gov.faa.ang.swac.datalayer.storage.fileio.WithFooter; import gov.faa.ang.swac.datalayer.storage.fileio.WithHeader; // TODO: This can be compacted to a smaller footprint if needed public class TrajectoryKmlRecord implements TextSerializable, WithHeader, WithFooter { private static final String DOCUMENT_NAME = "Trajectory Paths"; private static final String NULL = "NULL"; private final String name; private final List<GCPointAltTime> trajectory; // Need a default constructor for reflection public TrajectoryKmlRecord() { name = "NULL"; trajectory = new ArrayList<GCPointAltTime>(1); } public TrajectoryKmlRecord(String name, List<? extends GCPointAltTime> trajectory) { this.name = name; this.trajectory = new ArrayList<GCPointAltTime>(trajectory.size()); for (GCPointAltTime p : trajectory) { this.trajectory.add(new GCPointAltTime(p)); } } public TrajectoryKmlRecord(FlightLeg flightLeg) { this(getName(flightLeg), flightLeg.flightRoute()); } private static String getName(FlightLeg flightLeg) { Integer flightId = flightLeg.flightId(); Aircraft aircraft = flightLeg.aircraft(); String carrierId = NULL; String acType = NULL; if (aircraft != null) { carrierId = aircraft.carrierId(); if (aircraft.badaRecord() != null) { acType = aircraft.badaRecord().getAircraftType(); } } String dep = flightLeg.departure() == null ? NULL : flightLeg.departure().airportName(); String arr = flightLeg.arrival() == null ? NULL : flightLeg.arrival().airportName(); return flightId + ": " + carrierId + " " + acType + " " + dep + "->" + arr; } @Override public long readHeader(BufferedReader reader) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeHeader(PrintWriter writer, long numRecords) throws IOException { writer.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<kml xmlns=\"http://earth.google.com/kml/2.2\">\n" + "<Document>\n" + "\t<name>" + DOCUMENT_NAME + "</name>\n" + "\t<open>0</open>\n"); writer.write(KmlUtilities.kmlStyles(GCClass.LINE)); } @Override public void readFooter(BufferedReader reader) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeFooter(PrintWriter writer) throws IOException { writer.write( "</Document>\n" + "</kml>\n"); } @Override public void readItem(BufferedReader reader) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeItem(PrintWriter writer) throws IOException { String kml = KmlUtilities.toKml(trajectory, name, Color.RED, AltitudeMode.ABSOLUTE); if (kml != null) { writer.write(kml); } } }
apache-2.0
efsn/origin
src/main/java/org/demo/multi/controller/UserDelegate.java
3174
package org.demo.multi.controller; import org.springframework.util.StringUtils; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import template.bean.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserDelegate { private UserService userService; private String createView; private String updateView; private String deleteView; private String listView; private String redirectToListView; public ModelAndView create(HttpServletRequest request, HttpServletResponse response, User user) { if ("GET".equals(request.getMethod())) { //jump to create view ModelAndView mv = new ModelAndView(this.getCreateView()); mv.addObject(this.getCommandName(user), user); BindException errors = new BindException(user, getCommandName(user)); if (!StringUtils.hasLength(user.getUsername())) { errors.rejectValue("username", "username.not.empty", "Please enter your usename"); } if (errors.hasErrors()) { mv.addAllObjects(errors.getModel()); } return mv; } userService.create(user); return new ModelAndView(this.getRedirectToListView()); } public ModelAndView update(HttpServletRequest request, HttpServletResponse response, User user) { if ("GET".equals(request.getMethod())) { //jump to update view ModelAndView mv = new ModelAndView(this.getUpdateView()); mv.addObject(this.getCommandName(user), user); return mv; } userService.update(user); return new ModelAndView(this.getRedirectToListView()); } public ModelAndView list(HttpServletRequest request, HttpServletResponse response, User user) { ModelAndView mv = new ModelAndView(getListView()); mv.addObject("map", userService.getMap()); return mv; } protected String getCommandName(Object obj) { return "command"; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public String getCreateView() { return createView; } public void setCreateView(String createView) { this.createView = createView; } public String getUpdateView() { return updateView; } public void setUpdateView(String updateView) { this.updateView = updateView; } public String getDeleteView() { return deleteView; } public void setDeleteView(String deleteView) { this.deleteView = deleteView; } public String getListView() { return listView; } public void setListView(String listView) { this.listView = listView; } public String getRedirectToListView() { return redirectToListView; } public void setRedirectToListView(String redirectToListView) { this.redirectToListView = redirectToListView; } }
apache-2.0
rpudil/midpoint
infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ConnectorTypeUtil.java
4562
/* * Copyright (c) 2010-2013 Evolveum * * 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.evolveum.midpoint.schema.util; import javax.xml.namespace.QName; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.schema.PrismSchema; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.XmlSchemaType; import com.evolveum.prism.xml.ns._public.types_3.SchemaDefinitionType; /** * @author Radovan Semancik * */ public class ConnectorTypeUtil { public static String getConnectorHostTypeOid(ConnectorType connectorType) { if (connectorType.getConnectorHostRef() != null) { return connectorType.getConnectorHostRef().getOid(); } else if (connectorType.getConnectorHost() != null) { return connectorType.getConnectorHost().getOid(); } else { return null; } } public static Element getConnectorXsdSchema(ConnectorType connector) { XmlSchemaType xmlSchemaType = connector.getSchema(); if (xmlSchemaType == null) { return null; } return ObjectTypeUtil.findXsdElement(xmlSchemaType); } public static Element getConnectorXsdSchema(PrismObject<ConnectorType> connector) { PrismContainer<XmlSchemaType> xmlSchema = connector.findContainer(ConnectorType.F_SCHEMA); if (xmlSchema == null) { return null; } return ObjectTypeUtil.findXsdElement(xmlSchema); } public static void setConnectorXsdSchema(ConnectorType connectorType, Element xsdElement) { PrismObject<ConnectorType> connector = connectorType.asPrismObject(); setConnectorXsdSchema(connector, xsdElement); } public static void setConnectorXsdSchema(PrismObject<ConnectorType> connector, Element xsdElement) { PrismContainer<XmlSchemaType> schemaContainer; try { schemaContainer = connector.findOrCreateContainer(ConnectorType.F_SCHEMA); PrismProperty<SchemaDefinitionType> definitionProperty = schemaContainer.findOrCreateProperty(XmlSchemaType.F_DEFINITION); ObjectTypeUtil.setXsdSchemaDefinition(definitionProperty, xsdElement); } catch (SchemaException e) { // Should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } /** * Returns parsed connector schema */ public static PrismSchema parseConnectorSchema(ConnectorType connectorType, PrismContext prismContext) throws SchemaException { Element connectorSchemaElement = ConnectorTypeUtil.getConnectorXsdSchema(connectorType); if (connectorSchemaElement == null) { return null; } PrismSchema connectorSchema = PrismSchema.parse(connectorSchemaElement, true, "schema for " + connectorType, prismContext); // Make sure that the config container definition has a correct compile-time class name QName configContainerQName = new QName(connectorType.getNamespace(), ResourceType.F_CONNECTOR_CONFIGURATION.getLocalPart()); PrismContainerDefinition<ConnectorConfigurationType> configurationContainerDefintion = connectorSchema.findContainerDefinitionByElementName(configContainerQName); configurationContainerDefintion.setCompileTimeClass(ConnectorConfigurationType.class); return connectorSchema; } public static PrismContainerDefinition<ConnectorConfigurationType> findConfigurationContainerDefinition(ConnectorType connectorType, PrismSchema connectorSchema) { QName configContainerQName = new QName(connectorType.getNamespace(), ResourceType.F_CONNECTOR_CONFIGURATION.getLocalPart()); return connectorSchema.findContainerDefinitionByElementName(configContainerQName); } }
apache-2.0
AlexKushev/ConferenceOrganisation
src/main/java/conferenceOrganisation/database/connection/DatabaseConnection.java
1552
package conferenceOrganisation.database.connection; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; @Singleton @Startup public class DatabaseConnection { public Connection connection; @PostConstruct public void init() throws IOException { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("No driver!"); } Connection newConnection = null; Properties prop = new Properties(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader .getResourceAsStream("conferenceOrganisation/database/connection/config.properties"); prop.load(input); String databaseUrl = String.format("jdbc:mysql://%s:%s/%s", prop.getProperty("databaseNetworkAddress"), prop.getProperty("databasePort"), prop.getProperty("databaseName")); try { newConnection = DriverManager.getConnection(databaseUrl, prop.getProperty("databaseUserAccount"), prop.getProperty("databasePassword")); System.out.println("Connection successfuly to the database."); } catch (SQLException e) { System.out.println("Connection failed"); } this.connection = newConnection; } public Statement createStatement() throws SQLException, IOException { return connection.createStatement(); } }
apache-2.0
tallycheck/data-support
datadomain-on-jpa/src/main/java/com/taoswork/tallycheck/datadomain/onjpa/annotation/RelationType.java
2154
package com.taoswork.tallycheck.datadomain.onjpa.annotation; /** * Created by Gao Yuan on 2015/8/22. */ public enum RelationType { //One - One /** * Relation Owner * Has: @JoinColumn * Example: * * @Entity * public class Employee { * * @OneToOne * @JoinColumn(name="PSPACE_ID") * private ParkingSpace parkingSpace; * * } */ OneWay_OneToOne, TwoWay_OneToOneOwner, /** * Relation Belonging * Has: mappedBy * Example: * * @Entity * public class ParkingSpace { * * @OneToOne(mappedBy="parkingSpace") * private Employee employee; * * } */ TwoWay_OneToOneBelonging, //Many - One /** * Relation Owner * Has: @JoinColumn * Example: * * @Entity * public class Employee { * ... * @ManyToOne * @JoinColumn(name="DEPT_ID") * private Department department; * ... * } */ OneWay_ManyToOne, TwoWay_ManyToOneOwner, /** * Has "mappedBy" * @Entity * public class Department { * * @OneToMany(mappedBy="department") * private Collection<Employee> employees; * ... * } */ TwoWay_ManyToOneBelonging, TwoWay_OneToManyBelonged, //One - Many /** * Has @JoinTable * * @Entity * public class Employee { * * @OneToMany * @JoinTable(name="EMP_PHONE", * joinColumns=@JoinColumn(name="EMP_ID"), * inverseJoinColumns=@JoinColumn(name="PHONE_ID")) * private Collection<Phone> phones; * ... * } */ OneWay_OneToMany, //Many - Many /** * @Entity * public class Employee { * * @ManyToMany * private Collection<Project> projects; * * } */ TwoWay_ManyToManyOwner, OneWay_ManyToMany, /** * * @Entity * public class Project { * * @ManyToMany(mappedBy="projects") * private Collection<Employee> employees; * ... * } * */ TwoWay_ManyToManyBelonging, //None None; }
apache-2.0
masaki-yamakawa/geode
geode-dunit/src/main/java/org/apache/geode/test/dunit/internal/ProcessManager.java
14782
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.test.dunit.internal; import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_NETWORK_PARTITION_DETECTION; import static org.apache.geode.util.internal.GeodeGlossary.GEMFIRE_PREFIX; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.JavaVersion; import org.apache.commons.lang3.SystemUtils; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.InternalLocator; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.version.VersionManager; class ProcessManager implements ChildVMLauncher { private int namingPort; private Map<Integer, ProcessHolder> processes = new HashMap<>(); private File log4jConfig; private int pendingVMs; private Registry registry; private int debugPort = Integer.getInteger("dunit.debug.basePort", 0); private int suspendVM = Integer.getInteger("dunit.debug.suspendVM", -100); private VersionManager versionManager; public ProcessManager(int namingPort, Registry registry) { this.versionManager = VersionManager.getInstance(); this.namingPort = namingPort; this.registry = registry; } public synchronized void launchVM(int vmNum) throws IOException { launchVM(VersionManager.CURRENT_VERSION, vmNum, false, 0); } @Override public synchronized ProcessHolder launchVM(String version, int vmNum, boolean bouncedVM, int remoteStubPort) throws IOException { if (bouncedVM) { processes.remove(vmNum); } if (processes.containsKey(vmNum)) { throw new IllegalStateException("VM " + vmNum + " is already running."); } File workingDir = getVMDir(version, vmNum); if (!workingDir.exists()) { workingDir.mkdirs(); } else if (!bouncedVM || DUnitLauncher.MAKE_NEW_WORKING_DIRS) { try { FileUtils.deleteDirectory(workingDir); } catch (IOException e) { // This delete is occasionally failing on some platforms, maybe due to a lingering // process. Allow the process to be launched anyway. System.err.println("Unable to delete " + workingDir + ". Currently contains " + Arrays.asList(workingDir.list())); } workingDir.mkdirs(); } String[] cmd = buildJavaCommand(vmNum, namingPort, version, remoteStubPort); System.out.println("Executing " + Arrays.toString(cmd)); if (log4jConfig != null) { FileUtils.copyFileToDirectory(log4jConfig, workingDir); } // TODO - delete directory contents, preferably with commons io FileUtils try { String[] envp = null; if (!VersionManager.isCurrentVersion(version)) { envp = new String[] {"GEODE_HOME=" + versionManager.getInstall(version)}; } Process process = Runtime.getRuntime().exec(cmd, envp, workingDir); pendingVMs++; ProcessHolder holder = new ProcessHolder(process); processes.put(vmNum, holder); linkStreams(version, vmNum, holder, holder.getErrorStream(), System.err); linkStreams(version, vmNum, holder, holder.getInputStream(), System.out); return holder; } catch (RuntimeException | Error t) { t.printStackTrace(); throw t; } } public void validateVersion(String version) { if (!versionManager.isValidVersion(version)) { throw new IllegalArgumentException("Version " + version + " is not configured for use"); } } public static File getVMDir(String version, int vmNum) { return new File(DUnitLauncher.DUNIT_DIR, VM.getVMName(VersionManager.CURRENT_VERSION, vmNum)); } public synchronized void killVMs() { for (ProcessHolder process : processes.values()) { if (process != null) { process.kill(); } } } public synchronized boolean hasLiveVMs() { for (ProcessHolder process : processes.values()) { if (process != null && process.isAlive()) { return true; } } return false; } private void linkStreams(final String version, final int vmNum, final ProcessHolder holder, final InputStream in, final PrintStream out) { final String vmName = "[" + VM.getVMName(version, vmNum) + "] "; Thread ioTransport = new Thread() { @Override public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { String line = reader.readLine(); while (line != null) { if (line.length() == 0) { out.println(); } else { out.print(vmName); out.println(line); } line = reader.readLine(); } } catch (Exception e) { if (!holder.isKilled()) { out.println("Error transporting IO from child process"); e.printStackTrace(out); } } } }; ioTransport.setDaemon(true); ioTransport.start(); } private String removeModulesFromPath(String classpath, String... modules) { for (String module : modules) { classpath = removeModuleFromGradlePath(classpath, module); classpath = removeModuleFromEclipsePath(classpath, module); classpath = removeModuleFromIntelliJPath(classpath, module); } return classpath; } private String removeModuleFromEclipsePath(String classpath, String module) { String buildDir = File.separator + module + File.separator + "out" + File.separator; String mainClasses = buildDir + "production"; if (!classpath.contains(mainClasses)) { return classpath; } classpath = removeFromPath(classpath, mainClasses); return classpath; } private String removeModuleFromIntelliJPath(String p_classpath, String module) { String classpath = p_classpath; String mainClasses = File.separator + "out" + File.separator + "production" + File.separator + "org.apache.geode." + module + ".main"; if (classpath.contains(mainClasses)) { classpath = removeFromPath(classpath, mainClasses); } mainClasses = File.separator + "out" + File.separator + "production" + File.separator + "geode." + module + ".main"; if (classpath.contains(mainClasses)) { classpath = removeFromPath(classpath, mainClasses); } return classpath; } private String removeModuleFromGradlePath(String classpath, String module) { String buildDir = File.separator + module + File.separator + "build" + File.separator; String mainClasses = buildDir + "classes" + File.separator + "java" + File.separator + "main"; classpath = removeFromPath(classpath, mainClasses); String libDir = buildDir + "libs"; classpath = removeFromPath(classpath, libDir); String mainResources = buildDir + "resources" + File.separator + "main"; classpath = removeFromPath(classpath, mainResources); String generatedResources = buildDir + "generated-resources" + File.separator + "main"; classpath = removeFromPath(classpath, generatedResources); return classpath; } private String[] buildJavaCommand(int vmNum, int namingPort, String version, int remoteStubPort) { String cmd = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; String dunitClasspath = System.getProperty("java.class.path"); String separator = File.separator; String classPath; if (VersionManager.isCurrentVersion(version)) { classPath = dunitClasspath; } else { // remove current-version product classes and resources from the classpath dunitClasspath = dunitClasspath = removeModulesFromPath(dunitClasspath, "geode-common", "geode-core", "geode-cq", "geode-http-service", "geode-json", "geode-log4j", "geode-lucene", "geode-serialization", "geode-wan", "geode-gfsh"); classPath = versionManager.getClasspath(version) + File.pathSeparator + dunitClasspath; } // String tmpDir = System.getProperty("java.io.tmpdir"); String agent = getAgentString(); String jdkDebug = ""; if (debugPort > 0) { jdkDebug += ",address=" + debugPort; debugPort++; } String jdkSuspend = vmNum == suspendVM ? "y" : "n"; // ignore version ArrayList<String> cmds = new ArrayList<String>(); cmds.add(cmd); cmds.add("-classpath"); String jreLib = separator + "jre" + separator + "lib" + separator; classPath = removeFromPath(classPath, jreLib); cmds.add(classPath); cmds.add("-D" + DUnitLauncher.REMOTE_STUB_PORT_PARAM + "=" + remoteStubPort); cmds.add("-D" + DUnitLauncher.RMI_PORT_PARAM + "=" + namingPort); cmds.add("-D" + DUnitLauncher.VM_NUM_PARAM + "=" + vmNum); cmds.add("-D" + DUnitLauncher.VM_VERSION_PARAM + "=" + version); cmds.add("-D" + DUnitLauncher.WORKSPACE_DIR_PARAM + "=" + new File(".").getAbsolutePath()); if (vmNum >= 0) { // let the locator print a banner if (version.equals(VersionManager.CURRENT_VERSION)) { // enable the banner for older versions cmds.add("-D" + InternalLocator.INHIBIT_DM_BANNER + "=true"); } } else { // most distributed unit tests were written under the assumption that network partition // detection is disabled, so we turn it off in the locator. Tests for network partition // detection should create a separate locator that has it enabled cmds.add( "-D" + GEMFIRE_PREFIX + ENABLE_NETWORK_PARTITION_DETECTION + "=false"); cmds.add( "-D" + GEMFIRE_PREFIX + "allow_old_members_to_join_for_testing=true"); } if (DUnitLauncher.LOG4J != null) { cmds.add("-Dlog4j.configurationFile=" + DUnitLauncher.LOG4J); } cmds.add("-Djava.library.path=" + System.getProperty("java.library.path")); cmds.add("-Xrunjdwp:transport=dt_socket,server=y,suspend=" + jdkSuspend + jdkDebug); cmds.add("-XX:+HeapDumpOnOutOfMemoryError"); cmds.add("-Xmx512m"); cmds.add("-D" + GEMFIRE_PREFIX + "DEFAULT_MAX_OPLOG_SIZE=10"); cmds.add("-D" + GEMFIRE_PREFIX + "disallowMcastDefaults=true"); cmds.add("-D" + DistributionConfig.RESTRICT_MEMBERSHIP_PORT_RANGE + "=true"); cmds.add("-D" + GEMFIRE_PREFIX + ConfigurationProperties.VALIDATE_SERIALIZABLE_OBJECTS + "=true"); cmds.add("-ea"); cmds.add("-XX:MetaspaceSize=512m"); cmds.add("-XX:SoftRefLRUPolicyMSPerMB=1"); cmds.add(agent); if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_9)) { // needed for client stats gathering, see VMStats50 class, it's using class inspection // to call getProcessCpuTime method cmds.add("--add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED"); // needed for server side code cmds.add("--add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED"); cmds.add("--add-opens=java.base/jdk.internal.module=ALL-UNNAMED"); cmds.add("--add-opens=java.base/java.lang.module=ALL-UNNAMED"); } cmds.add(ChildVM.class.getName()); String[] rst = new String[cmds.size()]; cmds.toArray(rst); return rst; } private String removeFromPath(String classpath, String partialPath) { String[] jars = classpath.split(File.pathSeparator); StringBuilder sb = new StringBuilder(classpath.length()); Boolean firstjar = true; for (String jar : jars) { if (!jar.contains(partialPath)) { if (!firstjar) { sb.append(File.pathSeparator); } sb.append(jar); firstjar = false; } } return sb.toString(); } /** * Get the java agent passed to this process and pass it to the child VMs. This was added to * support jacoco code coverage reports */ private String getAgentString() { RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); if (runtimeBean != null) { for (String arg : runtimeBean.getInputArguments()) { if (arg.contains("-javaagent:")) { // HACK for gradle bug GRADLE-2859. Jacoco is passing a relative path // That won't work when we pass this to dunit VMs in a different // directory arg = arg.replace("-javaagent:..", "-javaagent:" + System.getProperty("user.dir") + File.separator + ".."); arg = arg.replace("destfile=..", "destfile=" + System.getProperty("user.dir") + File.separator + ".."); return arg; } } } return "-DdummyArg=true"; } synchronized void signalVMReady() { pendingVMs--; this.notifyAll(); } public synchronized boolean waitForVMs() throws InterruptedException { return waitForVMs(DUnitLauncher.STARTUP_TIMEOUT); } public synchronized boolean waitForVMs(long timeout) throws InterruptedException { long end = System.currentTimeMillis() + timeout; while (pendingVMs > 0) { long remaining = end - System.currentTimeMillis(); if (remaining <= 0) { return false; } this.wait(remaining); } return true; } @Override public RemoteDUnitVMIF getStub(int i) throws RemoteException, NotBoundException, InterruptedException { return getStub(VersionManager.CURRENT_VERSION, i); } public RemoteDUnitVMIF getStub(String version, int i) throws RemoteException, NotBoundException, InterruptedException { waitForVMs(DUnitLauncher.STARTUP_TIMEOUT); return (RemoteDUnitVMIF) registry.lookup("vm" + i); } public ProcessHolder getProcessHolder(int i) { return processes.get(i); } }
apache-2.0
jhwhetstone/cdsWebserver
networkServer/src/main/java/org/pesc/cds/web/LoggingClientHttpRequestInterceptor.java
2650
package org.pesc.cds.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; /** * Allows logging outgoing requests and the corresponding responses. * Requires the use of a {@link org.springframework.http.client.BufferingClientHttpRequestFactory} to log * the body of received responses. */ public class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { protected Logger requestLogger = LoggerFactory.getLogger("spring.web.client.MessageTracing.sent"); protected Logger responseLogger = LoggerFactory.getLogger("spring.web.client.MessageTracing.received"); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { logRequest(request, body); ClientHttpResponse response = execution.execute(request, body); logResponse(request, response); return response; } protected void logRequest(HttpRequest request, byte[] body) { if (requestLogger.isDebugEnabled()) { requestLogger.debug("===========================request begin================================================"); requestLogger.debug("URI : {}", request.getURI()); requestLogger.debug("Method : {}", request.getMethod()); requestLogger.debug("Headers : {}", request.getHeaders() ); requestLogger.debug("==========================request end================================================"); } } protected void logResponse(HttpRequest request, ClientHttpResponse response) { if (responseLogger.isDebugEnabled()) { try { responseLogger.debug("============================response begin=========================================="); responseLogger.debug("Status code : {}", response.getStatusCode()); responseLogger.debug("Status text : {}", response.getStatusText()); responseLogger.debug("Headers : {}", response.getHeaders()); responseLogger.debug("=======================response end================================================="); } catch (IOException e) { responseLogger.warn("Failed to log response for {} request to {}", request.getMethod(), request.getURI(), e); } } } }
apache-2.0
freeVM/freeVM
enhanced/buildtest/tests/vts/vm/src/test/vm/jvms/instructions/loadStore/ldc/ldc08/ldc0804/ldc0804pTest.java
887
/* Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable 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. */ /** * @author Alexander V. Esin * @version $Revision: 1.1 $ */ package org.apache.harmony.vts.test.vm.jvms.instructions.loadStore.ldc.ldc08.ldc0804; public class ldc0804pTest { public static final String str = "TestString"; }
apache-2.0
INAETICS/secure-modular-services
org.amdatu.remote.itest/src/org/amdatu/remote/itest/junit/admin/RemoteServiceAdminTest.java
15613
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.amdatu.remote.itest.junit.admin; import static org.amdatu.remote.admin.http.HttpAdminConstants.CONFIGURATION_TYPE; import static org.amdatu.remote.admin.http.HttpAdminConstants.PASSBYVALYE_INTENT; import static org.mockito.Mockito.mock; import static org.osgi.service.remoteserviceadmin.RemoteConstants.REMOTE_CONFIGS_SUPPORTED; import static org.osgi.service.remoteserviceadmin.RemoteConstants.REMOTE_INTENTS_SUPPORTED; import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_EXPORTED_INTERFACES; import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_IMPORTED; import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_IMPORTED_CONFIGS; import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_INTENTS; import java.util.Collection; import java.util.Dictionary; import java.util.Hashtable; import java.util.Map; import org.amdatu.remote.admin.itest.api.EchoImpl; import org.amdatu.remote.admin.itest.api.EchoInterface; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.remoteserviceadmin.EndpointDescription; import org.osgi.service.remoteserviceadmin.ExportReference; import org.osgi.service.remoteserviceadmin.ExportRegistration; import org.osgi.service.remoteserviceadmin.ImportReference; import org.osgi.service.remoteserviceadmin.ImportRegistration; import org.osgi.service.remoteserviceadmin.RemoteServiceAdmin; /** * Testing {@link RemoteServiceAdmin} implementations in isolation. * * @author <a href="mailto:amdatu-developers@amdatu.org">Amdatu Project Team</a> */ public class RemoteServiceAdminTest extends AbstractRemoteServiceAdminTest { /** * Test that combines several specification tests that can safely run sequentially in one framework. * This is just more efficient then starting a fresh framework for every test. * * @throws Exception */ public void testRsaSpecRequirements() throws Exception { doTestRsaPublishesSupportedIntentsAndConfigurationTypes(); doTestRsaPublishesCorrectEndpointProperties(); doTestRsaClosesExportRegistrationOnUnget(); doTestImportLocallyExportedService(); } /** * A very basic test that imports a locally exported service and tries to invoke it. */ protected void doTestImportLocallyExportedService() throws Exception { logDebug("Registering local service"); String ifaceName = EchoInterface.class.getName(); Object echoService = createInstance(EchoImpl.class.getName()); Dictionary<String, Object> localProperties = new Hashtable<String, Object>(); localProperties.put(SERVICE_EXPORTED_INTERFACES, ifaceName); BundleContext childContext = getChildBundleContext(); ServiceRegistration<?> localServiceRegistration = childContext.registerService(ifaceName, echoService, localProperties); ServiceReference<?> localServiceReference = localServiceRegistration.getReference(); logDebug("Exporting local service"); Collection<ExportRegistration> exportRegistrations = m_remoteServiceAdmin.exportService(localServiceReference, null); assertNotNull("Expected a registration for the exported service", exportRegistrations); assertEquals("Expected a registration for the exported service", 1, exportRegistrations.size()); ExportRegistration exportRegistration = exportRegistrations.iterator().next(); Collection<ExportReference> exportReferences = m_remoteServiceAdmin.getExportedServices(); assertNotNull(exportRegistrations); assertEquals(1, exportReferences.size()); ExportReference exportReference = exportReferences.iterator().next(); EndpointDescription description = exportReference.getExportedEndpoint(); logDebug("Importing remote service"); ImportRegistration importRegistration = m_remoteServiceAdmin.importService(description); assertNotNull("Expected a registration for the imported service", importRegistration); logDebug("Invoking imported remote service"); ServiceReference<?>[] serviceReferences = childContext.getServiceReferences(ifaceName, "(" + SERVICE_IMPORTED + "=true)"); assertNotNull("Expected a reference for the imported service", serviceReferences); assertEquals("Expected a reference for the imported service", 1, serviceReferences.length); EchoInterface echo = (EchoInterface) childContext.getService(serviceReferences[0]); String echoResponse = echo.echo("Amdatu"); assertNotNull("Expected a response for the imported service", echoResponse); assertEquals("Expected an echo response for the imported service", "Amdatu", echoResponse); childContext.ungetService(serviceReferences[0]); logDebug("Closing import registration"); importRegistration.close(); Collection<ImportReference> importReferences = m_remoteServiceAdmin.getImportedEndpoints(); assertEquals("Expected no references for the imported service", 0, importReferences.size()); serviceReferences = childContext.getServiceReferences(ifaceName, "(" + SERVICE_IMPORTED + "=true)"); assertNull("Expected no reference for the imported service", serviceReferences); logDebug("Closing export registration"); exportRegistration.close(); exportReferences = m_remoteServiceAdmin.getExportedServices(); assertEquals("Expected no references for the exported service", 0, exportReferences.size()); logDebug("Unregistering local service"); localServiceRegistration.unregister(); } /** * Remote Service Admin 122.5.4 - Service Factory * <br/><br/> * A Remote Service Admin service must use a Service Factory for its service object to maintain separation * between Topology Managers. All registrations obtained through a Remote Service Admin service are life * cycle bound to the Topology Manager that created it. That is, if a Topology Manager ungets its Remote * Service Admin service, all registrations obtained through this service must automatically be closed. * * @throws Exception */ protected void doTestRsaClosesExportRegistrationOnUnget() throws Exception { logDebug("Registering local service"); Dictionary<String, Object> localProperties = new Hashtable<String, Object>(); localProperties.put(SERVICE_EXPORTED_INTERFACES, EchoInterface.class.getName()); ServiceRegistration<?> localServiceRegistration = getChildBundleContext().registerService(EchoInterface.class.getName(), mock(EchoInterface.class), localProperties); ServiceReference<?> localServiceReference = localServiceRegistration.getReference(); logDebug("Exporting local service first time"); Collection<ExportRegistration> exportRegistrations = m_remoteServiceAdmin.exportService(localServiceReference, null); assertNotNull("Expected a registration for the exported service", exportRegistrations); assertEquals("Expected a registration for the exported service", 1, exportRegistrations.size()); assertEquals("Expected one exported service", 1, m_remoteServiceAdmin.getExportedServices().size()); getChildBundleContext().ungetService(m_remoteServiceAdminReference); m_remoteServiceAdmin = getChildBundleContext().getService(m_remoteServiceAdminReference); assertEquals("Expected no exported services", 0, m_remoteServiceAdmin.getExportedServices().size()); } /** * Remote Service Admin 122.5.2 * <br/><br/> * The Remote Service Admin service must ensure that service properties are according to the Remote * Services chapter for an imported service. This means that it must register the following properties: * <ul> * <li>service.imported – (*) Must be set to any value.</li> * <li>service.imported.configs – (String+) The configuration information used to import this service. * Any associated properties for this configuration types must be properly mapped to the importing * system. For example, a URL in these properties must point to a valid resource when used in the * importing framework, see Resource Containment on page 310. Multiple configuration types can be * listed if they are synonyms for exactly the same Endpoint that is used to export this service.</li> * <li>service.intents – (String+) The Remote Service Admin must set this property to convey the * combined intents of: * <ul> * <li>The exporting service, and</li> * <li>The intents that the exporting distribution provider adds, and</li> * <li>The intents that the importing distribution provider adds.</li> * </ul> * <li>Any additional properties listed in the Endpoint Description that should not be excluded. See * Endpoint Description on page 306 for more details about the properties in the Endpoint Description.</li> * </ul> */ protected void doTestRsaPublishesCorrectEndpointProperties() throws Exception { String ifaceName = EchoInterface.class.getName(); Object echoService = createInstance(EchoImpl.class.getName()); Dictionary<String, Object> localProperties = new Hashtable<String, Object>(); localProperties.put(SERVICE_EXPORTED_INTERFACES, ifaceName); localProperties.put("test.passon", "should be passed on"); localProperties.put("test.overwrite", "should be overwritten"); localProperties.put(".test.private", "should be hidden"); Map<String, Object> extraProperties = new Hashtable<String, Object>(); extraProperties.put("test.overwrite", "has been overwritten"); BundleContext childContext = getChildBundleContext(); ServiceRegistration<?> localServiceRegistration = childContext.registerService(ifaceName, echoService, localProperties); ServiceReference<?> localServiceReference = localServiceRegistration.getReference(); logDebug("Exporting local service"); Collection<ExportRegistration> exportRegistrations = m_remoteServiceAdmin.exportService(localServiceReference, extraProperties); assertNotNull("Expected a registration for the exported service", exportRegistrations); assertEquals("Expected a registration for the exported service", 1, exportRegistrations.size()); ExportRegistration exportRegistration = exportRegistrations.iterator().next(); Collection<ExportReference> exportReferences = m_remoteServiceAdmin.getExportedServices(); assertNotNull(exportRegistrations); assertEquals(1, exportReferences.size()); ExportReference exportReference = exportReferences.iterator().next(); EndpointDescription exportedEndpoint = exportReference.getExportedEndpoint(); Map<String, Object> exportProperties = exportedEndpoint.getProperties(); assertEquals("true", exportProperties.get(SERVICE_IMPORTED)); assertEquals(strings(CONFIGURATION_TYPE), strings((String[]) exportProperties.get(SERVICE_IMPORTED_CONFIGS))); assertEquals(strings(PASSBYVALYE_INTENT), strings((String[]) exportProperties.get(SERVICE_INTENTS))); assertEquals("should be passed on", exportProperties.get("test.passon")); assertEquals("has been overwritten", exportProperties.get("test.overwrite")); assertNull(exportProperties.get(".test.private")); logDebug("Importing remote service"); ImportRegistration importRegistration = m_remoteServiceAdmin.importService(exportedEndpoint); assertNotNull("Expected a registration for the imported service", importRegistration); ImportReference importReference = importRegistration.getImportReference(); EndpointDescription importedEndpoint = importReference.getImportedEndpoint(); Map<String, Object> importProperties = importedEndpoint.getProperties(); assertEquals("true", importProperties.get(SERVICE_IMPORTED)); assertEquals(strings(CONFIGURATION_TYPE), strings((String[]) importProperties.get(SERVICE_IMPORTED_CONFIGS))); assertEquals(strings(PASSBYVALYE_INTENT), strings((String[]) importProperties.get(SERVICE_INTENTS))); assertEquals("should be passed on", importProperties.get("test.passon")); assertEquals("has been overwritten", importProperties.get("test.overwrite")); assertNull(importProperties.get(".test.private")); ServiceReference<?>[] serviceReferences = childContext.getServiceReferences(ifaceName, "(" + SERVICE_IMPORTED + "=true)"); assertNotNull("Expected a reference for the imported service", serviceReferences); assertEquals("Expected a reference for the imported service", 1, serviceReferences.length); ServiceReference<?> serviceReference = serviceReferences[0]; assertEquals("true", serviceReference.getProperty(SERVICE_IMPORTED)); assertEquals(strings(CONFIGURATION_TYPE), strings((String[]) serviceReference.getProperty(SERVICE_IMPORTED_CONFIGS))); assertEquals(strings(PASSBYVALYE_INTENT), strings((String[]) serviceReference.getProperty(SERVICE_INTENTS))); assertEquals(serviceReference.getProperty("test.passon"), "should be passed on"); assertEquals(serviceReference.getProperty("test.overwrite"), "has been overwritten"); assertNull(serviceReference.getProperty(".test.private")); exportRegistration.close(); importRegistration.close(); localServiceRegistration.unregister(); } /** * Remote Services 100.5.2 / AMDATURS-8 * <br/><br/> * A bundle that uses a configuration type has an implicit dependency on the distribution provider. To * make this dependency explicit, the distribution provider must register a service with the following * properties: * <ul> * <li>remote.intents.supported – (String+) The vocabulary of the given distribution provider.</li> * <li>remote.configs.supported – (String+) The configuration types that are implemented by the distribution provider.</li> * <ul> */ protected void doTestRsaPublishesSupportedIntentsAndConfigurationTypes() throws Exception { ServiceReference<?>[] references = getChildBundleContext().getServiceReferences(RemoteServiceAdmin.class.getName(), null); assertNotNull("Expected exactly one RSA reference", references); assertEquals("Expected exactly one RSA reference", 1, references.length); assertNotNull("RSA must publish supported configs", references[0].getProperty(REMOTE_CONFIGS_SUPPORTED)); assertNotNull("RSA must publish supported intents", references[0].getProperty(REMOTE_INTENTS_SUPPORTED)); } }
apache-2.0
SergeyZhernovoy/Java-education
PartVIII/lesson4/src/main/java/ru/szhernovoy/io/Input.java
183
/** *@author Sergey Zernovoy /*@since 12/07/2016 * */ package ru.szhernovoy.io; public interface Input { String ask(String question); int ask(String question, int[] range); }
apache-2.0
wusichao/spring-cloud
consumer-one/src/main/java/com/wusc/consumerone/ConsumerOneApplication.java
592
package com.wusc.consumerone; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @SpringBootApplication @EnableEurekaClient @EnableFeignClients @EnableDiscoveryClient public class ConsumerOneApplication { public static void main(String[] args) { SpringApplication.run(ConsumerOneApplication.class, args); } }
apache-2.0
javacreed/swing-common
src/main/java/com/javacreed/api/swing/common/combobox/StringMatcher.java
171
package com.javacreed.api.swing.common.combobox; @FunctionalInterface public interface StringMatcher { int indexOf(String source, String pattern, int index); }
apache-2.0
andrewapmurphy/dependency-version-manager
common/src/test/java/com/cyndre/dvm/reporting/HashGeneratorTest.java
893
package com.cyndre.dvm.reporting; import static org.junit.Assert.*; import org.junit.Test; public class HashGeneratorTest { private static final String KEY_1 = "key1"; private static final String KEY_2 = "key2"; private static final String DATA_1 = "data1"; private static final String DATA_2 = "data2"; @Test public void testRepeatable() { final HashGenerator hashKey1 = new HashGenerator(KEY_1); final HashGenerator hashKey2 = new HashGenerator(KEY_2); final String hash1 = hashKey1.hash(DATA_1); final String hash2 = hashKey2.hash(DATA_2); assertEquals(hash1, hashKey1.hash(DATA_1)); assertNotSame(hash1, hashKey1.hash(DATA_2)); assertEquals(hash2, hashKey2.hash(DATA_2)); assertNotSame(hash2, hashKey2.hash(DATA_2)); assertNotSame(hashKey1.hash(DATA_1), hashKey2.hash(DATA_1)); assertNotSame(hashKey1.hash(DATA_2), hashKey2.hash(DATA_2)); } }
apache-2.0
streamsets/datacollector
upgrader/src/main/java/com/streamsets/pipeline/upgrader/YamlStageUpgraderLoader.java
12650
/* * Copyright 2019 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.upgrader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.streamsets.pipeline.api.Config; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.Config; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; public class YamlStageUpgraderLoader { private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(new YAMLFactory()); private final String stageName; private final URL resource; public YamlStageUpgraderLoader(String stageName, URL resource) { this.stageName = stageName; this.resource = resource; } public YamlStageUpgrader get() { try (InputStream is = resource.openStream()) { Map yaml = OBJECT_MAPPER.readValue(is, Map.class); Integer upgraderVersion = (Integer) yaml.get("upgraderVersion"); if (upgraderVersion == null || upgraderVersion != 1) { throw new StageException(Errors.YAML_UPGRADER_10, upgraderVersion); } YamlStageUpgrader upgrader = new YamlStageUpgrader(); upgrader.setStageName(stageName); upgrader.setUpgraderVersion(upgraderVersion); upgrader.setToVersionMap(parseToVersions((List) yaml.get("upgrades"))); return upgrader; } catch (Exception ex) { throw new StageException(Errors.YAML_UPGRADER_07, resource, ex); } } Map<Integer, UpgradeToVersion> parseToVersions(List list) { Map<Integer, UpgradeToVersion> toVersions = new LinkedHashMap<>(); if (list != null) { for (Map map : (List<Map>) list) { if (map.containsKey("toVersion")) { Integer toVersion = (Integer) map.get("toVersion"); List actions = (List) map.get("actions"); toVersions.put(toVersion, parseConfigActions(toVersion, actions)); } } } return toVersions; } UpgradeToVersion parseConfigActions(Integer version, List list) { UpgradeToVersion toVersion = new UpgradeToVersion(); List<UpgraderAction<?, List<Config>>> upgraderActions = new ArrayList<>(); for (Map action : (List<Map>) list) { upgraderActions.add(parseConfigAction(UpgraderAction.CONFIGS_WRAPPER, version, action)); } toVersion.setActions(upgraderActions); return toVersion; } <T> UpgraderAction<?, T> parseConfigAction( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Integer toVersion, Map map ) { UpgraderAction action; if (map.containsKey("setConfig")) { action = parseSetConfigAction(wrapper, map); } else if (map.containsKey("renameConfig")) { action = parseRenameConfigAction(wrapper, map); } else if (map.containsKey("removeConfigs")) { action = parseRemoveConfigs(wrapper, map); } else if (map.containsKey("replaceConfig")) { action = parseReplaceConfig(wrapper, map); } else if (map.containsKey("iterateListConfig")) { action = parseIterateListConfig(wrapper, toVersion, map); } else if (map.containsKey("configStringMapPut")) { action = parseConfigStringMapPutConfig(wrapper, map); } else if (map.containsKey("configStringMapRemove")) { action = parseConfigStringMapRemoveConfig(wrapper, map); } else if (map.containsKey("configStringListAdd")) { action = parseConfigStringListAddConfig(wrapper, map); } else if (map.containsKey("configStringListRemove")) { action = parseConfigStringListRemoveConfig(wrapper, map); } else if (map.containsKey("registerService")) { action = parseRegisterService(wrapper, map); } else if (map.containsKey("setConfigFromStringMap")) { action = parseSetConfigFromStringMapAction(wrapper, map); } else if (map.containsKey("setConfigFromConfigList")) { action = parseSetConfigFromConfigListAction(wrapper, map); } else if (map.containsKey("setConfigFromJoinedConfigList")) { action = parseSetConfigFromJoinedConfigListAction(wrapper, map); } else { throw new StageException(Errors.YAML_UPGRADER_08, toVersion, stageName, resource); } return action; } private RegisterServiceAction<?> parseRegisterService(Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map map) { Map registerService = (Map) map.get("registerService"); String service = (String)registerService.get("service"); String existingConfigPattern = (String) registerService.get("existingConfigsPattern"); RegisterServiceAction<?> serviceAction = new RegisterServiceAction<>(wrapper); serviceAction.setService(service); serviceAction.setExistingConfigsPattern(existingConfigPattern); return serviceAction; } SetConfigUpgraderAction parseSetConfigAction( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("setConfig"); SetConfigUpgraderAction action = new SetConfigUpgraderAction<>(wrapper); action.setName((String) map.get("name")); action.setValue(map.get("value")); action.setElseName((String) map.get("elseName")); action.setElseValue(map.get("elseValue")); action.setLookForName((String) map.get("lookForName")); action.setIfValueMatches(map.get("ifValueMatches")); return action; } RenameConfigUpgraderAction parseRenameConfigAction( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("renameConfig"); RenameConfigUpgraderAction action = new RenameConfigUpgraderAction<>(wrapper); action.setOldNamePattern((String) map.get("oldNamePattern")); action.setNewNamePattern((String) map.get("newNamePattern")); return action; } RemoveConfigUpgraderAction parseRemoveConfigs( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("removeConfigs"); RemoveConfigUpgraderAction action = new RemoveConfigUpgraderAction<>(wrapper); action.setNamePattern((String) map.get("namePattern")); return action; } ReplaceConfigUpgraderAction parseReplaceConfig( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("replaceConfig"); ReplaceConfigUpgraderAction action = new ReplaceConfigUpgraderAction<>(wrapper); action.setName((String) map.get("name")); action.setNewValue(map.get("newValue")); action.setElseNewValue(map.get("elseNewValue")); if (map.containsKey("ifOldValueMatches")) { action.setIfOldValueMatches(map.get("ifOldValueMatches")); } action.setTokenForOldValue((String) map.get("tokenForOldValue")); if (map.containsKey("newValueFromMatchIndex")) { action.setNewValueFromMatchIndex(map.get("newValueFromMatchIndex")); } return action; } StringMapConfigPutUpgraderAction parseConfigStringMapPutConfig( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("configStringMapPut"); StringMapConfigPutUpgraderAction action = new StringMapConfigPutUpgraderAction<>(wrapper); action.setName((String) map.get("name")); action.setKey((String) map.get("key")); action.setValue(map.get("value")); action.setLookForName((String) map.get("lookForName")); action.setIfValueMatches(map.get("ifValueMatches")); return action; } StringMapConfigRemoveUpgraderAction parseConfigStringMapRemoveConfig( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("configStringMapRemove"); StringMapConfigRemoveUpgraderAction action = new StringMapConfigRemoveUpgraderAction<>(wrapper); action.setName((String) map.get("name")); action.setKey((String) map.get("key")); action.setValue(map.get("value")); action.setLookForName((String) map.get("lookForName")); action.setIfValueMatches(map.get("ifValueMatches")); return action; } StringListConfigAddUpgraderAction parseConfigStringListAddConfig( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("configStringListAdd"); StringListConfigAddUpgraderAction action = new StringListConfigAddUpgraderAction<>(wrapper); action.setName((String) map.get("name")); action.setValue((String) map.get("value")); action.setLookForName((String) map.get("lookForName")); action.setIfValueMatches(map.get("ifValueMatches")); return action; } StringListConfigRemoveUpgraderAction parseConfigStringListRemoveConfig( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("configStringListRemove"); StringListConfigRemoveUpgraderAction action = new StringListConfigRemoveUpgraderAction<>(wrapper); action.setName((String) map.get("name")); action.setValue((String) map.get("value")); action.setLookForName((String) map.get("lookForName")); action.setIfValueMatches(map.get("ifValueMatches")); return action; } IterateConfigListUpgraderAction parseIterateListConfig( Function<?, UpgraderAction.ConfigsAdapter> wrapper, int toVersion, Map<String, Object> map ) { if (wrapper != UpgraderAction.CONFIGS_WRAPPER) { throw new StageException(Errors.YAML_UPGRADER_11, toVersion, stageName, resource); } map = (Map) map.get("iterateListConfig"); String name = (String) map.get("name"); IterateConfigListUpgraderAction iterateAction = new IterateConfigListUpgraderAction(); iterateAction.setName(name); List actions = (List) map.get("actions"); List<UpgraderAction<?, Map<String, Object>>> upgraderActions = new ArrayList<>(); for (Map action : (List<Map>) actions) { upgraderActions.add(parseConfigAction(UpgraderAction.MAP_WRAPPER, toVersion, action)); } iterateAction.setActions(upgraderActions); return iterateAction; } SetConfigFromStringMapUpgraderAction parseSetConfigFromStringMapAction( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("setConfigFromStringMap"); String name = (String) map.get("name"); String mapName = (String) map.get("mapName"); String key = (String) map.get("key"); SetConfigFromStringMapUpgraderAction action = new SetConfigFromStringMapUpgraderAction(wrapper); action.setName(name); action.setMapName(mapName); action.setKey(key); return action; } SetConfigFromConfigListAction parseSetConfigFromConfigListAction( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("setConfigFromConfigList"); String name = (String) map.get("name"); String listName = (String) map.get("listName"); String elementName = (String) map.get("elementName"); boolean deleteFieldInList = (Boolean) map.get("deleteFieldInList"); boolean elementMustExist = (Boolean) map.get("elementMustExist"); SetConfigFromConfigListAction action = new SetConfigFromConfigListAction(wrapper); action.setName(name); action.setListName(listName); action.setElementName(elementName); action.setDeleteFieldInList(deleteFieldInList); action.setElementMustExist(elementMustExist); return action; } SetConfigFromJoinedConfigListAction parseSetConfigFromJoinedConfigListAction( Function<?, UpgraderAction.ConfigsAdapter> wrapper, Map<String, Object> map ) { map = (Map) map.get("setConfigFromJoinedConfigList"); String name = (String) map.get("name"); String listName = (String) map.get("listName"); String delimiter = (String) map.get("delimiter"); SetConfigFromJoinedConfigListAction action = new SetConfigFromJoinedConfigListAction(wrapper); action.setName(name); action.setListName(listName); action.setDelimiter(delimiter); return action; } }
apache-2.0
citlab/Intercloud
intercloud-webapp/src/main/java/de/tu_berlin/cit/intercloud/webapp/nav/AbstractNavPanel.java
1531
package de.tu_berlin.cit.intercloud.webapp.nav; import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import java.util.ArrayList; import java.util.List; public abstract class AbstractNavPanel extends Panel { private final List<NavItem> navItems = new ArrayList<>(); public AbstractNavPanel(String id, String listViewId) { super(id); add(new ListView<NavItem>(listViewId, navItems) { @Override protected void populateItem(ListItem<NavItem> listItem) { populateNavItem(listItem); } }); } protected abstract void populateNavItem(ListItem<NavItem> listItem); public void addNavItem(NavItem navItem) { navItems.add(navItem); } protected void setActive(Component c, Class<? extends Page> page) { if (this.getPage().getClass().equals(page)) { c.add(new AttributeAppender("class", Model.of(" active"))); } } protected BookmarkablePageLink<Page> newNavLink(String id, NavItem navItem) { BookmarkablePageLink<Page> link = new BookmarkablePageLink<>(id, navItem.getPage()); link.setBody(Model.of(navItem.getLabel())); return link; } }
apache-2.0
tcrossland/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/container/impl/deployment/DiscoverBpmPlatformPluginsStep.java
1843
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.container.impl.deployment; import org.camunda.bpm.container.impl.RuntimeContainerDelegateImpl; import org.camunda.bpm.container.impl.jmx.services.JmxManagedBpmPlatformPlugins; import org.camunda.bpm.container.impl.plugin.BpmPlatformPlugins; import org.camunda.bpm.container.impl.spi.DeploymentOperation; import org.camunda.bpm.container.impl.spi.DeploymentOperationStep; import org.camunda.bpm.container.impl.spi.PlatformServiceContainer; import org.camunda.bpm.container.impl.spi.ServiceTypes; import org.camunda.bpm.engine.impl.util.ClassLoaderUtil; /** * @author Thorben Lindhauer * */ public class DiscoverBpmPlatformPluginsStep extends DeploymentOperationStep { public String getName() { return "Discover BPM Platform Plugins"; } public void performOperationStep(DeploymentOperation operationContext) { PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); BpmPlatformPlugins plugins = BpmPlatformPlugins.load(ClassLoaderUtil.getContextClassloader()); JmxManagedBpmPlatformPlugins jmxManagedPlugins = new JmxManagedBpmPlatformPlugins(plugins); serviceContainer.startService(ServiceTypes.BPM_PLATFORM, RuntimeContainerDelegateImpl.SERVICE_NAME_PLATFORM_PLUGINS, jmxManagedPlugins); } }
apache-2.0
yqhok1/coolweather
app/src/main/java/com/example/yqhok/coolweather/base/adapter/BaseFragmentPagerAdapter.java
1363
package com.example.yqhok.coolweather.base.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.view.ViewGroup; import java.util.List; /** * Created by yqhok on 2017-02-22. */ public class BaseFragmentPagerAdapter extends FragmentPagerAdapter { private List<Fragment> fragmentList; private List<String> titleList; public BaseFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) { super(fm); this.fragmentList = fragmentList; } public BaseFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> titleList) { super(fm); this.fragmentList = fragmentList; this.titleList = titleList; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); } @Override public CharSequence getPageTitle(int position) { if (titleList != null) { return titleList.get(position); } else { return ""; } } }
apache-2.0
googlemaps/android-on-demand-rides-deliveries-samples
java/driver/src/main/java/com/google/mapsplatform/transportation/sample/driver/dialog/VehicleDialogFragment.java
2785
/* Copyright 2020 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mapsplatform.transportation.sample.driver.dialog; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import com.google.mapsplatform.transportation.sample.driver.R; /** A dialog to specify vehicle settings. */ public class VehicleDialogFragment extends DialogFragment { /** Listener interface for dialog result callbacks. */ public interface OnDialogResultListener { /** * Runs when a dialog action button is clicked. * * @param vehicleId the vehicle id input value. */ void onResult(String vehicleId); } private static final String TAG = VehicleDialogFragment.class.getName(); /** Initial vehicle id. */ @Nullable private final String vehicleId; /** Optional callback to be run when an action button is clicked. */ private final OnDialogResultListener listener; private VehicleDialogFragment(@Nullable String vehicleId, OnDialogResultListener listener) { this.vehicleId = vehicleId; this.listener = listener; } @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { LayoutInflater inflater = requireActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.vehicle_info_dialog, null); EditText editText = view.findViewById(R.id.vehicle_id); editText.setText(vehicleId); return new AlertDialog.Builder(getActivity()) .setView(view) .setPositiveButton( R.string.save_label, (dialog, id) -> { String newVehicleId = editText.getText().toString(); if (!TextUtils.isEmpty(newVehicleId)) { listener.onResult(newVehicleId); } }) .setNegativeButton(R.string.cancel_label, (dialog, id) -> {}) .create(); } public static VehicleDialogFragment newInstance( @Nullable String vehicleId, OnDialogResultListener listener) { return new VehicleDialogFragment(vehicleId, listener); } }
apache-2.0
arturkirakosian/java
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupDeletionTests.java
387
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; public class GroupDeletionTests extends TestBase{ @Test public void testGroupDeletion() { app.getNavigationHelper().gotoGroupPage(); app.getGroupHelper().selectGroup(); app.getGroupHelper().deletSelectedGroups(); app.getGroupHelper().returnToGroupPage(); } }
apache-2.0
nvapp/nv-android-libs
src/com/nvapp/service/LocInfo.java
752
package com.nvapp.service; import java.io.Serializable; public class LocInfo implements Serializable { /** * UID */ private static final long serialVersionUID = -8301117934624389177L; private double lat; private double lng; private String address; public LocInfo(double lat, double lng, String address) { this.lat = lat; this.lng = lng; this.address = address; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
apache-2.0
dog-gateway/jamod-rtu-over-tcp
src/net/wimpi/modbus/io/ModbusSerialTransaction.java
8065
/*** * Copyright 2002-2010 jamod development team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***/ package net.wimpi.modbus.io; import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusException; import net.wimpi.modbus.ModbusIOException; import net.wimpi.modbus.ModbusSlaveException; import net.wimpi.modbus.msg.ExceptionResponse; import net.wimpi.modbus.msg.ModbusRequest; import net.wimpi.modbus.msg.ModbusResponse; import net.wimpi.modbus.net.SerialConnection; import net.wimpi.modbus.util.AtomicCounter; import net.wimpi.modbus.util.Mutex; /** * Class implementing the <tt>ModbusTransaction</tt> interface. * * @author Dieter Wimberger * @version @version@ (@date@) */ public class ModbusSerialTransaction implements ModbusTransaction { // class attributes private static AtomicCounter c_TransactionID = new AtomicCounter( Modbus.DEFAULT_TRANSACTION_ID); // instance attributes and associations private ModbusTransport m_IO; private ModbusRequest m_Request; private ModbusResponse m_Response; private boolean m_ValidityCheck = Modbus.DEFAULT_VALIDITYCHECK; private int m_Retries = Modbus.DEFAULT_RETRIES; private int m_TransDelayMS = Modbus.DEFAULT_TRANSMIT_DELAY; private SerialConnection m_SerialCon; private Mutex m_TransactionLock = new Mutex(); /** * Constructs a new <tt>ModbusSerialTransaction</tt> instance. */ public ModbusSerialTransaction() { }// constructor /** * Constructs a new <tt>ModbusSerialTransaction</tt> instance with a given * <tt>ModbusRequest</tt> to be send when the transaction is executed. * <p/> * * @param request * a <tt>ModbusRequest</tt> instance. */ public ModbusSerialTransaction(ModbusRequest request) { setRequest(request); }// constructor /** * Constructs a new <tt>ModbusSerialTransaction</tt> instance with a given * <tt>ModbusRequest</tt> to be send when the transaction is executed. * <p/> * * @param con * a <tt>TCPMasterConnection</tt> instance. */ public ModbusSerialTransaction(SerialConnection con) { setSerialConnection(con); }// constructor /** * Sets the port on which this <tt>ModbusTransaction</tt> should be * executed. * <p> * <p/> * * @param con * a <tt>SerialConnection</tt>. */ public void setSerialConnection(SerialConnection con) { m_SerialCon = con; m_IO = con.getModbusTransport(); }// setConnection public int getTransactionID() { return c_TransactionID.get(); }// getTransactionID public void setRequest(ModbusRequest req) { m_Request = req; // m_Response = req.getResponse(); }// setRequest public ModbusRequest getRequest() { return m_Request; }// getRequest public ModbusResponse getResponse() { return m_Response; }// getResponse public void setCheckingValidity(boolean b) { m_ValidityCheck = b; }// setCheckingValidity public boolean isCheckingValidity() { return m_ValidityCheck; }// isCheckingValidity public int getRetries() { return m_Retries; }// getRetries public void setRetries(int num) { m_Retries = num; }// setRetries /** * Get the TransDelayMS value. * * @return the TransDelayMS value. */ public int getTransDelayMS() { return m_TransDelayMS; } /** * Set the TransDelayMS value. * * @param newTransDelayMS * The new TransDelayMS value. */ public void setTransDelayMS(int newTransDelayMS) { this.m_TransDelayMS = newTransDelayMS; } public void execute() throws ModbusIOException, ModbusSlaveException, ModbusException { // 1. assert executeability assertExecutable(); try { // 2. Lock transaction /** * Note: The way this explicit synchronization is implemented at the * moment, there is no ordering of pending threads. The Mutex will * simply call notify() and the JVM will handle the rest. */ m_TransactionLock.acquire(); // 3. write request, and read response, // while holding the lock on the IO object synchronized (m_IO) { int tries = 0; boolean finished = false; // toggle the id m_Request.setTransactionID(c_TransactionID.increment()); do { try { // write request message m_IO.writeMessage(m_Request); // read response message m_Response = m_IO.readResponse(); finished = true; } catch (ModbusIOException e) { if (++tries >= m_Retries) { throw e; } else { if (m_TransDelayMS > 0) { try { Thread.sleep(m_TransDelayMS); } catch (InterruptedException ex) { System.err.println("InterruptedException: " + ex.getMessage()); } } } System.err.println("execute try " + tries + " error: " + e.getMessage()); } } while (!finished); } // 4. deal with exceptions if (m_Response instanceof ExceptionResponse) { throw new ModbusSlaveException( ((ExceptionResponse) m_Response).getExceptionCode()); } if (isCheckingValidity()) { checkValidity(); } } catch (InterruptedException ex) { throw new ModbusIOException( "Thread acquiring lock was interrupted."); } finally { m_TransactionLock.release(); } }// execute /** * Asserts if this <tt>ModbusTCPTransaction</tt> is executable. * * @throws ModbusException * if the transaction cannot be asserted. */ private void assertExecutable() throws ModbusException { if (m_Request == null || m_SerialCon == null) { throw new ModbusException( "Assertion failed, transaction not executable"); } }// assertExecuteable /** * Checks the validity of the transaction, by checking if the values of the * response correspond to the values of the request. * * @throws ModbusException * if the transaction is not valid. */ protected void checkValidity() throws ModbusException { }// checkValidity }// class ModbusSerialTransaction
apache-2.0
OnPositive/aml
examples/org.aml.example.ramlannotations/src/main/java/org/aml/example/simple/Vehicle.java
257
package org.aml.example.simple; public class Vehicle { @FieldConfig(caption="Name of vehicle",order=1) protected String name; @FieldConfig(caption="Maximum Speed of vehicle",order=2) protected double speed; @Hidden protected VehicleKind kind; }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-framework/krad-it/src/test/java/org/kuali/rice/krad/test/KRADTestConstants.java
1525
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.krad.test; /** * Provides centralized storage of constants that occur throughout the tests * * @author Kuali Rice Team (rice.collab@kuali.org) */ public final class KRADTestConstants { public static final String TEST_NAMESPACE_CODE = "TEST"; public static final class TestConstants { private static final String HOST = "localhost"; private static final String PORT = "8080"; public static final String BASE_PATH = "http://" + HOST + ":" + PORT + "/"; public static final String MESSAGE = "JUNIT test entry. If this exist after the tests are not cleaning up correctly. Created by class"; private TestConstants() { throw new UnsupportedOperationException("do not call"); } } private KRADTestConstants() { throw new UnsupportedOperationException("do not call"); } }
apache-2.0
inps/trsm
trsm/src/main/java/cn/inps/trsm/RedisSession.java
3235
package cn.inps.trsm; import java.io.IOException; import java.security.Principal; import java.util.HashMap; import org.apache.catalina.Manager; import org.apache.catalina.session.StandardSession; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * * @author * */ public class RedisSession extends StandardSession { private final Log log = LogFactory.getLog(RedisSession.class); protected static Boolean manualDirtyTrackingSupportEnabled = false; public static void setManualDirtyTrackingSupportEnabled(Boolean enabled) { manualDirtyTrackingSupportEnabled = enabled; } protected static String manualDirtyTrackingAttributeKey = "__changed__"; public static void setManualDirtyTrackingAttributeKey(String key) { manualDirtyTrackingAttributeKey = key; } protected HashMap<String, Object> changedAttributes; protected Boolean dirty; public RedisSession(Manager manager) { super(manager); resetDirtyTracking(); } public Boolean isDirty() { return dirty || !changedAttributes.isEmpty(); } public HashMap<String, Object> getChangedAttributes() { return changedAttributes; } public void resetDirtyTracking() { changedAttributes = new HashMap<>(); dirty = false; } @Override public void setAttribute(String key, Object value) { if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) { dirty = true; return; } Object oldValue = getAttribute(key); super.setAttribute(key, value); if ((value != null || oldValue != null) && (value == null && oldValue != null || oldValue == null && value != null || !value.getClass().isInstance(oldValue) || !value.equals(oldValue))) { if (this.manager instanceof RedisSessionManager && ((RedisSessionManager) this.manager).getSaveOnChange()) { try { ((RedisSessionManager) this.manager).save(this, true); } catch (IOException ex) { log.error("Error saving session on setAttribute (triggered by saveOnChange=true): " + ex.getMessage()); } } else { changedAttributes.put(key, value); } } } @Override public void removeAttribute(String name) { super.removeAttribute(name); if (this.manager instanceof RedisSessionManager && ((RedisSessionManager) this.manager).getSaveOnChange()) { try { ((RedisSessionManager) this.manager).save(this, true); } catch (IOException ex) { log.error("Error saving session on setAttribute (triggered by saveOnChange=true): " + ex.getMessage()); } } else { dirty = true; } } @Override public void setId(String id) { // Specifically do not call super(): it's implementation does unexpected // things // like calling manager.remove(session.id) and manager.add(session). this.id = id; } @Override public void setPrincipal(Principal principal) { dirty = true; super.setPrincipal(principal); } @Override public void writeObjectData(java.io.ObjectOutputStream out) throws IOException { super.writeObjectData(out); out.writeLong(this.getCreationTime()); } @Override public void readObjectData(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectData(in); this.setCreationTime(in.readLong()); } }
apache-2.0
herickson/terremark-api
src/main/java/com/terremark/api/ServerLicenseUsageReferences.java
2009
package com.terremark.api; 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.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ServerLicenseUsageReferences complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ServerLicenseUsageReferences"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Server" type="{}ServerLicenseUsageReference" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ServerLicenseUsageReferences", propOrder = { "servers" }) public class ServerLicenseUsageReferences extends ToStringGenerator { @XmlElement(name = "Server", nillable = true) protected List<ServerLicenseUsageReference> servers; /** * Gets the value of the servers 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 servers property. * * <p> * For example, to add a new item, do as follows: * <pre> * getServers().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ServerLicenseUsageReference } * * */ public List<ServerLicenseUsageReference> getServers() { if (servers == null) { servers = new ArrayList<ServerLicenseUsageReference>(); } return this.servers; } }
apache-2.0
ceylon/ceylon
compiler-java/test/src/org/eclipse/ceylon/compiler/java/test/bc/BcTests.java
10395
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.eclipse.ceylon.compiler.java.test.bc; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import junit.framework.Assert; import org.eclipse.ceylon.common.Versions; import org.eclipse.ceylon.compiler.java.test.CompilerError; import org.eclipse.ceylon.compiler.java.test.CompilerTests; import org.eclipse.ceylon.compiler.java.test.CompilerTests.ModuleWithArtifact; import org.eclipse.ceylon.compiler.java.util.Util; import org.eclipse.ceylon.javax.tools.JavaCompiler; import org.eclipse.ceylon.javax.tools.JavaFileObject; import org.eclipse.ceylon.javax.tools.StandardJavaFileManager; import org.eclipse.ceylon.javax.tools.ToolProvider; import org.eclipse.ceylon.javax.tools.JavaCompiler.CompilationTask; import org.junit.Ignore; import org.junit.Test; public class BcTests extends CompilerTests { private final String providerModuleSrc = "provider/module.ceylon"; private final String providerPackageSrc = "provider/package.ceylon"; private final String clientModuleSrc = "client/module.ceylon"; private final String clientModuleName = "org.eclipse.ceylon.compiler.java.test.bc.client"; private final String providerModuleName = "org.eclipse.ceylon.compiler.java.test.bc.provider"; /** * Checks that we can still compile a client after a change * @param ceylon */ protected void source(String ceylon) { String providerPreSrc = "provider/" + ceylon + "_pre.ceylon"; String providerPostSrc = "provider/" + ceylon + "_post.ceylon"; String clientSrc = "client/" + ceylon + "_client.ceylon"; // Compile provider compile(providerPreSrc, providerModuleSrc, providerPackageSrc); // Compile client compile(clientSrc, clientModuleSrc); // New version of provider compile(providerPostSrc, providerModuleSrc, providerPackageSrc); // Check the client still compilers compile(clientSrc, clientModuleSrc); } /** * Checks that we can still link an existing client after a change * @param ceylon */ protected void binary(String main, String ceylon) { String providerPreSrc = "provider/" + ceylon + "_pre.ceylon"; String providerPostSrc = "provider/" + ceylon + "_post.ceylon"; String clientSrc = "client/" + ceylon + "_client.ceylon"; // Compile provider compile(providerPreSrc, providerModuleSrc, providerPackageSrc); // Compile client compile(clientSrc, clientModuleSrc); // New version of provider compile(providerPostSrc, providerModuleSrc, providerPackageSrc); // Now try running the client ModuleWithArtifact clientModule = new ModuleWithArtifact(clientModuleName, "0.1"); ModuleWithArtifact providerModule = new ModuleWithArtifact(providerModuleName, "0.1"); run(clientModuleName + "." + main, clientModule, providerModule); } @Test public void testClassMethAddDefaultedParam() { source("ClassMethAddDefaultedParam"); binary("classMethAddDefaultedParam", "ClassMethAddDefaultedParam"); } @Test public void testFunctionAddDefaultedParam() { source("FunctionAddDefaultedParam"); binary("functionAddDefaultedParam_client", "FunctionAddDefaultedParam"); } @Test public void testClassInitAddDefaultedParam() { source("ClassInitAddDefaultedParam"); binary("classInitAddDefaultedParam", "ClassInitAddDefaultedParam"); } @Test public void testBinaryVersionIncompatible(){ compile("JavaOldVersion.java"); assertErrors("CeylonNewVersion", new CompilerError(-1, "Ceylon class org.eclipse.ceylon.compiler.java.test.bc.JavaOldVersion was compiled by an incompatible version of the Ceylon compiler\n The class was compiled using 0.0.\n This compiler supports "+Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+".\n Please try to recompile your module using a compatible compiler.\n Binary compatibility will only be supported after Ceylon 1.2.")); } // tests before we renamed module_.class to $module_.class @Test public void testBinaryVersionIncompatibleModule1() throws IOException { CompilationTask compiler = compileJava("binaryVersionOld/module_.java"); Assert.assertTrue(compiler.call()); // so now make a jar containing the java module File jarFolder = new File(destDir, "org/eclipse/ceylon/compiler/java/test/bc/binaryVersionOld/1/"); jarFolder.mkdirs(); File jarFile = new File(jarFolder, "org.eclipse.ceylon.compiler.java.test.bc.binaryVersionOld-1.jar"); // now jar it up JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile)); ZipEntry entry = new ZipEntry("org/eclipse/ceylon/compiler/java/test/bc/binaryVersionOld/module_.class"); outputStream.putNextEntry(entry); File javaClass = new File(destDir, "org/eclipse/ceylon/compiler/java/test/bc/binaryVersionOld/module_.class"); FileInputStream inputStream = new FileInputStream(javaClass); Util.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); assertErrors("binaryVersion/module", new CompilerError(21, "version '1' of module 'org.eclipse.ceylon.compiler.java.test.bc.binaryVersionOld' was compiled by" + " an incompatible version of the compiler" +" (binary version 0.0 of module is not compatible with binary version " +Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+" of this compiler)")); } // tests after we renamed module_.class to $module_.class @Test public void testBinaryVersionIncompatibleModule2() throws IOException { CompilationTask compiler = compileJava("binaryVersionOld2/$module_.java"); Assert.assertTrue(compiler.call()); // so now make a jar containing the java module File jarFolder = new File(destDir, "org/eclipse/ceylon/compiler/java/test/bc/binaryVersionOld2/1/"); jarFolder.mkdirs(); File jarFile = new File(jarFolder, "org.eclipse.ceylon.compiler.java.test.bc.binaryVersionOld2-1.jar"); // now jar it up JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile)); ZipEntry entry = new ZipEntry("org/eclipse/ceylon/compiler/java/test/bc/binaryVersionOld2/$module_.class"); outputStream.putNextEntry(entry); File javaClass = new File(destDir, "org/eclipse/ceylon/compiler/java/test/bc/binaryVersionOld2/$module_.class"); FileInputStream inputStream = new FileInputStream(javaClass); Util.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); assertErrors("binaryVersion2/module", new CompilerError(21, "version '1' of module 'org.eclipse.ceylon.compiler.java.test.bc.binaryVersionOld2' was compiled by" + " an incompatible version of the compiler" +" (binary version 0.0 of module is not compatible with binary version " +Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+" of this compiler)")); } private CompilationTask compileJava(String... sourcePaths) { java.util.List<File> sourceFiles = new ArrayList<File>(sourcePaths.length); for(String file : sourcePaths){ sourceFiles.add(new File(getPackagePath(), file)); } JavaCompiler runCompiler = ToolProvider.getSystemJavaCompiler(); assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!", runCompiler); StandardJavaFileManager runFileManager = runCompiler.getStandardFileManager(null, null, null); // make sure the destination repo exists new File(destDir).mkdirs(); List<String> options = new LinkedList<String>(); options.addAll(Arrays.asList("-sourcepath", getSourcePath(), "-d", destDir, "-cp", getClassPathAsPath())); Iterable<? extends JavaFileObject> compilationUnits1 = runFileManager.getJavaFileObjectsFromFiles(sourceFiles); return runCompiler.getTask(null, runFileManager, null, options, null, compilationUnits1); } @Test @Ignore("Till 1.2.3") public void bug6068() { compareWithJavaSource("refinedreturn/Bug6068"); compareWithJavaSource("refinedreturn/Bug6068_client"); run("org.eclipse.ceylon.compiler.java.test.bc.refinedreturn.bug6068", new ModuleWithArtifact("org.eclipse.ceylon.compiler.java.test.bc.refinedreturn", "1"), new ModuleWithArtifact("ceylon.collection", "1.2.3", System.getProperty("user.home")+"/.ceylon/repo", "car")); } }
apache-2.0
beanvalidation/beanvalidation-spec
spec-examples/src/test/java/org/beanvalidation/specexamples/validationapi/NonEmpty.java
1900
/* * Jakarta Bean Validation: constrain once, validate everywhere. * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.beanvalidation.specexamples.validationapi; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.Payload; import jakarta.validation.ReportAsSingleViolation; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; //tag::include[] @Documented @NotNull @Size(min = 1) @ReportAsSingleViolation @Constraint(validatedBy = NonEmpty.NonEmptyValidator.class) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) public @interface NonEmpty { String message() default "{com.acme.constraint.NonEmpty.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Documented @interface List { NonEmpty[] value(); } class NonEmptyValidator implements ConstraintValidator<NonEmpty, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { return true; } } } // end::include[]
apache-2.0
ThorbenLindhauer/activiti-engine-ppi
modules/activiti-engine/src/main/java/de/unipotsdam/hpi/thorben/ppi/measure/instance/DataMeasure.java
3563
/* Copyright 2012 Thorben Lindhauer * * 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 de.unipotsdam.hpi.thorben.ppi.measure.instance; import java.util.HashMap; import java.util.List; import java.util.Map; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.repository.ProcessDefinition; import de.unipotsdam.hpi.thorben.ppi.measure.instance.entity.DataMeasureInstance; import de.unipotsdam.hpi.thorben.ppi.measure.instance.entity.command.GetDataMeasureInstanceCommand; import de.unipotsdam.hpi.thorben.ppi.measure.instance.entity.command.InsertDataInstanceCommand; import de.unipotsdam.hpi.thorben.ppi.measure.query.DataMeasureInstanceQuery; public class DataMeasure extends BaseMeasure<DataMeasureInstance> { private String dataObjectName; private String dataFieldName; private Map<String, DataMeasureInstance> instancesCache = new HashMap<String, DataMeasureInstance>(); public DataMeasure(String id, ProcessDefinition processDefinition) { super(id, processDefinition); } public void updateDataValue(String processInstanceId, Object value) { DataMeasureInstance dataMeasureInstance = findCachedDataMeasureInstance(processInstanceId); dataMeasureInstance.setValue(value.toString()); } /** * Finds a data measure instance (or creates one) and ensures that it is in Activiti's cache. * * It is also added to a local cache in this DataMeasure, as the select commands do not access the Activiti cache. * Otherwise a DataMeasureInstance that was already created before, but not committed, could not be found. * @param processInstanceId * @return */ private DataMeasureInstance findCachedDataMeasureInstance(String processInstanceId) { CommandContext commandContext = Context.getCommandContext(); DataMeasureInstance dataMeasureValue = new GetDataMeasureInstanceCommand(id, processInstanceId).execute(commandContext); if (dataMeasureValue == null) { dataMeasureValue = instancesCache.get(processInstanceId); } if (dataMeasureValue == null) { dataMeasureValue = new DataMeasureInstance(); dataMeasureValue.setMeasureId(id); dataMeasureValue.setProcessInstanceId(processInstanceId); new InsertDataInstanceCommand(dataMeasureValue).execute(commandContext); } instancesCache.put(processInstanceId, dataMeasureValue); return dataMeasureValue; } @Override public List<DataMeasureInstance> getAllValues() { CommandContext context = Context.getCommandContext(); DataMeasureInstanceQuery query = context.getBaseMeasureManager() .createNewDataMeasureValueQuery() .processDefinitionId(processDefinition.getId()).measureId(id); return query.list(); } public String getDataObjectName() { return dataObjectName; } public void setDataObjectName(String dataObjectName) { this.dataObjectName = dataObjectName; } public String getDataFieldName() { return dataFieldName; } public void setDataFieldName(String dataFieldName) { this.dataFieldName = dataFieldName; } }
apache-2.0
wso2/analytics-is
modules/integration/tests-kubernetes-integration/src/test/java/org/sp/tests/routing/EchoService.java
1362
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.sp.tests.routing; import org.sp.tests.base.SPBaseTest; import org.testng.annotations.Test; /** * EchoService class */ public class EchoService extends SPBaseTest { @Test public void getPostToEcho() throws Exception { String serviceURL = spURL + "/echo"; // // StringRequestEntity requestEntity = new StringRequestEntity("{ \"Hello\":\"DAS\" };", "application/json", // "UTF-8"); // // HttpClient client = new HttpClient(); // PostMethod post = new PostMethod(serviceURL); // // post.setRequestEntity(requestEntity); // // int statuscode = client.executeMethod(post); // assertEquals(statuscode, 201); } }
apache-2.0
gawkermedia/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201601/cm/ConversionTrackingError.java
1778
package com.google.api.ads.adwords.jaxws.v201601.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * An error that can occur during calls to the ConversionTypeService. * * * <p>Java class for ConversionTrackingError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ConversionTrackingError"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201601}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://adwords.google.com/api/adwords/cm/v201601}ConversionTrackingError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ConversionTrackingError", propOrder = { "reason" }) public class ConversionTrackingError extends ApiError { @XmlSchemaType(name = "string") protected ConversionTrackingErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link ConversionTrackingErrorReason } * */ public ConversionTrackingErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link ConversionTrackingErrorReason } * */ public void setReason(ConversionTrackingErrorReason value) { this.reason = value; } }
apache-2.0
jbosschina/cluster
infinispan/helloworld/src/main/java/com/kylin/infinispan/helloworld/embedded/HelloWorldDefaultCache.java
1834
package com.kylin.infinispan.helloworld.embedded; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.manager.DefaultCacheManager; import com.kylin.infinispan.common.User; public class HelloWorldDefaultCache { public static void main(String[] args) throws InterruptedException { DefaultCacheManager cacheManager = new DefaultCacheManager(); Cache<Object, Object> cache = cacheManager.getCache(); Cache<Object, Object> cache01 = cacheManager.getCache("0001"); Cache<Object, Object> cache02 = cacheManager.getCache("0002"); Cache<Object, Object> cache03 = cacheManager.getCache("0003"); System.out.println("name = " + cache.getName() + ", version = " + cache.getVersion() + ", status = " + cache.getStatus()); System.out.println("name = " + cache01.getName() + ", version = " + cache01.getVersion() + ", status = " + cache01.getStatus()); System.out.println("name = " + cache02.getName() + ", version = " + cache02.getVersion() + ", status = " + cache02.getStatus()); System.out.println("name = " + cache03.getName() + ", version = " + cache03.getVersion() + ", status = " + cache03.getStatus()); cache.put("key", new User(1, "Kylin Soong", "IT")); System.out.println(cache.size()); System.out.println(cache.containsKey("key")); System.out.println(cache.get("key")); Object obj = cache.remove("key"); System.out.println(obj); System.out.println(cache.size()); cache.put("key", new User(1, "Kylin Soong", "Software Engineer")); cache.put("key", new User(2, "Kobe Bryant", " Basketball Player")); System.out.println(cache.get("key")); cache.put("key", new User(1, "Kylin Soong", "Software Engineer"), 5, TimeUnit.SECONDS); System.out.println(cache.get("key")); Thread.sleep(5 * 1000); System.out.println(cache.get("key")); } }
apache-2.0