text
stringlengths
7
1.01M
// Copyright 2017 The Bazel Authors. 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.google.devtools.build.lib.analysis.test; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.devtools.build.lib.packages.TestTimeout; import com.google.devtools.build.lib.packages.TestTimeout.TestTimeoutConverter; import com.google.devtools.common.options.OptionsParsingException; import java.time.Duration; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * A test for {@link TestTimeoutConverter}. */ @RunWith(JUnit4.class) public class TestTimeoutConverterTest { private Map<TestTimeout, Duration> timeouts; protected void setTimeouts(String option) throws OptionsParsingException { timeouts = new TestTimeoutConverter().convert(option); } protected void assertTimeout(TestTimeout timeout, int expected) { assertThat(timeouts).containsEntry(timeout, Duration.ofSeconds(expected)); } protected void assertDefaultTimeout(TestTimeout timeout) { assertTimeout(timeout, timeout.getTimeoutSeconds()); } protected void assertFailure(String option) { try { setTimeouts(option); fail("Incorrectly parsed '" + option + "'"); } catch (OptionsParsingException e) { // expected; } } @Test public void testDefaultTimeout() throws Exception { setTimeouts("-1"); assertDefaultTimeout(TestTimeout.SHORT); assertDefaultTimeout(TestTimeout.MODERATE); assertDefaultTimeout(TestTimeout.LONG); assertDefaultTimeout(TestTimeout.ETERNAL); } @Test public void testUniversalTimeout() throws Exception { setTimeouts("1"); assertTimeout(TestTimeout.SHORT, 1); assertTimeout(TestTimeout.MODERATE, 1); assertTimeout(TestTimeout.LONG, 1); assertTimeout(TestTimeout.ETERNAL, 1); setTimeouts("2,"); // comma at the end is ignored. assertTimeout(TestTimeout.SHORT, 2); assertTimeout(TestTimeout.MODERATE, 2); assertTimeout(TestTimeout.LONG, 2); assertTimeout(TestTimeout.ETERNAL, 2); } @Test public void testSeparateTimeouts() throws Exception { setTimeouts("1,0,-1,3"); assertTimeout(TestTimeout.SHORT, 1); assertDefaultTimeout(TestTimeout.MODERATE); assertDefaultTimeout(TestTimeout.LONG); assertTimeout(TestTimeout.ETERNAL, 3); setTimeouts("0,-1,3,20"); assertDefaultTimeout(TestTimeout.SHORT); assertDefaultTimeout(TestTimeout.MODERATE); assertTimeout(TestTimeout.LONG, 3); assertTimeout(TestTimeout.ETERNAL, 20); } @Test public void testIncorrectStrings() throws Exception { assertFailure(""); assertFailure("1a"); assertFailure("1 2 3 4"); assertFailure("1:2:3:4"); assertFailure("1,2,3"); assertFailure("1,2,3,4,"); assertFailure("1,2,,3,4"); assertFailure("1,2,3 4"); assertFailure("1,2,3,4,5"); } }
/* * Copyright (c) 2014-2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts; import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.REGISTRY_KEY_PROPERTY__KEY_VALUE; import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.SEQUENCE__NAME; import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.SEQUENCE__REFERRING_SEQUENCE_TYPE; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils.SEQUENCE_RESOURCE_DIR; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils.SYNAPSE_CONFIG_DIR; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EditPartConstants.SEQUENCE_MEDIATOR_ICON_PATH; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.Shape; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.edit.command.SetCommand; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.Tool; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.LayoutEditPolicy; import org.eclipse.gef.editpolicies.NonResizableEditPolicy; import org.eclipse.gef.palette.PaletteContainer; import org.eclipse.gef.palette.PaletteDrawer; import org.eclipse.gef.palette.ToolEntry; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator; import org.eclipse.gmf.runtime.diagram.ui.internal.services.palette.PaletteToolEntry; import org.eclipse.gmf.runtime.diagram.ui.tools.UnspecifiedTypeCreationTool; import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.SetValueCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure; import org.eclipse.gmf.runtime.notation.Node; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; //import org.wso2.developerstudio.eclipse.artifact.sequence.validators.SequenceTemplate; import org.wso2.developerstudio.eclipse.esb.core.ESBMavenConstants; import org.wso2.developerstudio.eclipse.esb.core.utils.ESBMediaTypeConstants; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact; import org.wso2.developerstudio.eclipse.esb.project.utils.ESBProjectUtils; import org.wso2.developerstudio.eclipse.general.project.artifact.GeneralProjectArtifact; import org.wso2.developerstudio.eclipse.general.project.artifact.RegistryArtifact; import org.wso2.developerstudio.eclipse.general.project.artifact.bean.RegistryElement; import org.wso2.developerstudio.eclipse.general.project.artifact.bean.RegistryItem; import org.wso2.developerstudio.eclipse.gmf.esb.ArtifactType; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.KeyType; import org.wso2.developerstudio.eclipse.gmf.esb.ProxyService; import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty; import org.wso2.developerstudio.eclipse.gmf.esb.Sequence; import org.eclipse.ui.part.FileEditorInput; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediatorOutputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EsbGraphicalShapeWithLabel; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.FixedBorderItemLocator; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.FixedSizedAbstractMediator; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.OpenSeparatelyEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.SequenceStorage; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.editpolicy.FeedbackIndicateDragDropEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.utils.OpenEditorUtils; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.SequenceCanonicalEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.SequenceItemSemanticEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbDiagramEditor; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbEditorInput; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.Messages; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.maven.util.MavenUtils; import org.wso2.developerstudio.eclipse.platform.core.templates.ArtifactTemplate; import org.wso2.developerstudio.eclipse.platform.core.templates.ArtifactTemplateHandler; import org.wso2.developerstudio.eclipse.platform.core.utils.CSProviderConstants; import org.wso2.developerstudio.eclipse.platform.core.utils.DeveloperStudioProviderUtils; import org.wso2.developerstudio.eclipse.platform.ui.editor.Openable; import org.wso2.developerstudio.eclipse.platform.ui.startup.ESBGraphicalEditor; import org.wso2.developerstudio.eclipse.utils.file.FileUtils; /** * @generated NOT */ public class SequenceEditPart extends FixedSizedAbstractMediator { private static IDeveloperStudioLog log = Logger.getLog("org.wso2.developerstudio.eclipse.gmf.esb.diagram"); //$NON-NLS-1$ private EsbDiagramEditor mainDiagramEditorRef; /** * @generated */ public static final int VISUAL_ID = 3503; /** * @generated */ protected IFigure contentPane; public static SequenceStorage sequenceStorage = new SequenceStorage(); private static Integer sequenceCount = 0; private SequenceEditPart currentSequence; private String value; public static ArrayList<String> definedSequenceNames = new ArrayList<String>(); private float inputCount = 0, outputCount = 0; private Button recieveCheckBox; //private boolean checked; private SequenceEditPart sequenceEditPart; private SequencesInfo info; /** * @generated NOT */ public SequenceEditPart(View view) { super(view); sequenceEditPart = this; info = new SequencesInfo(); } /** * @generated NOT */ protected void createDefaultEditPolicies() { installEditPolicy(EditPolicyRoles.CREATION_ROLE, new CreationEditPolicy()); super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new SequenceItemSemanticEditPolicy()); installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new DragDropEditPolicy()); installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new FeedbackIndicateDragDropEditPolicy()); installEditPolicy(EditPolicyRoles.CANONICAL_ROLE, new SequenceCanonicalEditPolicy()); installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy()); // For handle Double click Event. installEditPolicy(EditPolicyRoles.OPEN_ROLE, new OpenSeparatelyEditPolicy()); // XXX need an SCR to runtime to have another abstract superclass that // would let children add reasonable editpolicies // removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE); } /** * @generated */ protected LayoutEditPolicy createLayoutEditPolicy() { org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() { protected EditPolicy createChildEditPolicy(EditPart child) { View childView = (View) child.getModel(); switch (EsbVisualIDRegistry.getVisualID(childView)) { case SequenceInputConnectorEditPart.VISUAL_ID: case SequenceOutputConnectorEditPart.VISUAL_ID: return new BorderItemSelectionEditPolicy(); } EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (result == null) { result = new NonResizableEditPolicy(); } return result; } protected Command getMoveChildrenCommand(Request request) { return null; } protected Command getCreateCommand(CreateRequest request) { return null; } }; return lep; } public void notifyChanged(Notification notification) { super.notifyChanged(notification); Object notifier = ((ENotificationImpl) notification).getNotifier(); if (notifier instanceof Sequence) { if (notification.getFeature() instanceof EReference) { if ("staticReferenceKey".equals(((EReference) notification.getFeature()).getName())) { //$NON-NLS-1$ String keyValue = ((RegistryKeyProperty) notification.getNewValue()).getKeyValue(); setValue((Sequence) notifier, SEQUENCE__NAME, keyValue); } } else if (notification.getFeature() instanceof EAttribute) { if ("name".equals(((EAttribute) notification.getFeature()).getName())) { //$NON-NLS-1$ String name = (String) notification.getNewValue(); if ("{XPath}".equals(name)) { //$NON-NLS-1$ setValue((Sequence) notifier, SEQUENCE__REFERRING_SEQUENCE_TYPE, KeyType.DYNAMIC); } else { setValue((Sequence) notifier, SEQUENCE__REFERRING_SEQUENCE_TYPE, KeyType.STATIC); RegistryKeyProperty registryKeyProperty = ((Sequence) notifier).getStaticReferenceKey(); setValue(registryKeyProperty, REGISTRY_KEY_PROPERTY__KEY_VALUE, name); } } else if ("referringSequenceType".equals(((EAttribute) notification.getFeature()).getName())) { //$NON-NLS-1$ KeyType type = (KeyType) notification.getNewValue(); if (KeyType.DYNAMIC == type) { setValue((Sequence) notifier, SEQUENCE__NAME, "{XPath}"); //$NON-NLS-1$ } else { if ("{XPath}".equals(((Sequence) notifier).getName())) { //$NON-NLS-1$ setValue((Sequence) notifier, SEQUENCE__NAME, ""); //$NON-NLS-1$ } } } } } } private void setValue(EObject owner, EStructuralFeature feature, Object value) { SetCommand setCommand = new SetCommand(getEditingDomain(), owner, feature, value); if (setCommand.canExecute()) { getEditingDomain().getCommandStack().execute(setCommand); } } /** * @generated NOT */ protected IFigure createNodeShape() { return primaryShape = new SequenceFigure() { public void setBounds(org.eclipse.draw2d.geometry.Rectangle rect) { super.setBounds(rect); if (this.getBounds().getLocation().x != 0 && this.getBounds().getLocation().y != 0) { connectToMostSuitableElement(); reAllocate(rect); } }; }; } /** * @generated */ public SequenceFigure getPrimaryShape() { return (SequenceFigure) primaryShape; } /** * @generated NOT */ protected boolean addFixedChild(EditPart childEditPart) { if (childEditPart instanceof SequenceNameEditPart) { ((SequenceNameEditPart) childEditPart).setLabel(getPrimaryShape().getSequenceLabelFigure()); return true; } if (childEditPart instanceof SequenceInputConnectorEditPart) { IFigure borderItemFigure = ((SequenceInputConnectorEditPart) childEditPart).getFigure(); BorderItemLocator locator = new FixedBorderItemLocator(getMainFigure(), borderItemFigure, PositionConstants.WEST, 0.5); getBorderedFigure().getBorderItemContainer().add(borderItemFigure, locator); return true; } if (childEditPart instanceof SequenceOutputConnectorEditPart) { IFigure borderItemFigure = ((SequenceOutputConnectorEditPart) childEditPart).getFigure(); BorderItemLocator locator = new FixedBorderItemLocator(getMainFigure(), borderItemFigure, PositionConstants.EAST, 0.5); getBorderedFigure().getBorderItemContainer().add(borderItemFigure, locator); return true; } return false; } /*public IFigure getFigure() { IFigure figure = super.getFigure(); figure.setMaximumSize(new Dimension(75, 75)); return figure; }*/ /*protected NodeFigure createNodePlate() { DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(75, 75); result.setMinimumSize(new Dimension(75, 75)); return result; }*/ /** * @generated */ protected boolean removeFixedChild(EditPart childEditPart) { if (childEditPart instanceof SequenceNameEditPart) { return true; } if (childEditPart instanceof SequenceInputConnectorEditPart) { getBorderedFigure().getBorderItemContainer().remove( ((SequenceInputConnectorEditPart) childEditPart).getFigure()); return true; } if (childEditPart instanceof SequenceOutputConnectorEditPart) { getBorderedFigure().getBorderItemContainer().remove( ((SequenceOutputConnectorEditPart) childEditPart).getFigure()); return true; } return false; } /** * @generated */ protected void addChildVisual(EditPart childEditPart, int index) { if (addFixedChild(childEditPart)) { return; } super.addChildVisual(childEditPart, -1); } /** * @generated */ protected void removeChildVisual(EditPart childEditPart) { if (removeFixedChild(childEditPart)) { return; } super.removeChildVisual(childEditPart); } /** * @generated */ protected IFigure getContentPaneFor(IGraphicalEditPart editPart) { if (editPart instanceof IBorderItemEditPart) { return getBorderedFigure().getBorderItemContainer(); } return getContentPane(); } /** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model so * you may safely remove <i>generated</i> tag and modify it. * * @generated NOT */ protected NodeFigure createMainFigure() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new ToolbarLayout(true)); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; } /** * Default implementation treats passed figure as content pane. Respects * layout one may have set for generated figure. * * @param nodeShape * instance of generated figure class * @generated */ protected IFigure setupContentPane(IFigure nodeShape) { if (nodeShape.getLayoutManager() == null) { ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout(); layout.setSpacing(5); nodeShape.setLayoutManager(layout); } return nodeShape; // use nodeShape itself as contentPane } /** * @generated */ public IFigure getContentPane() { if (contentPane != null) { return contentPane; } return super.getContentPane(); } /** * {@inheritDoc} */ protected void addBorderItem(IFigure borderItemContainer, IBorderItemEditPart borderItemEditPart) { IFigure borderItemFigure = borderItemEditPart.getFigure(); if (borderItemEditPart instanceof SequenceInputConnectorEditPart) { borderItemContainer.add(borderItemFigure, new FixedBorderItemLocator(getMainFigure(), borderItemFigure, PositionConstants.WEST, 0.5)); } else if (borderItemEditPart instanceof SequenceOutputConnectorEditPart) { borderItemContainer.add(borderItemFigure, new FixedBorderItemLocator(getMainFigure(), borderItemFigure, PositionConstants.EAST, 0.5)); } else { super.addBorderItem(borderItemContainer, borderItemEditPart); } } /** * @generated */ protected void setForegroundColor(Color color) { if (primaryShape != null) { primaryShape.setForegroundColor(color); } } /** * @generated */ protected void setBackgroundColor(Color color) { if (primaryShape != null) { primaryShape.setBackgroundColor(color); } } /** * @generated */ protected void setLineWidth(int width) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineWidth(width); } } /** * @generated */ protected void setLineType(int style) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineStyle(style); } } /** * @generated */ public EditPart getPrimaryChildEditPart() { return getChildBySemanticHint(EsbVisualIDRegistry.getType(SequenceNameEditPart.VISUAL_ID)); } public IProject getActiveProject() { IEditorPart editorPart = null; IProject activeProject = null; IEditorReference editorReferences[] = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getEditorReferences(); for (int i = 0; i < editorReferences.length; i++) { IEditorPart editor = editorReferences[i].getEditor(false); if (editor != null) { editorPart = editor.getSite().getWorkbenchWindow().getActivePage().getActiveEditor(); } if (editorPart != null) { EsbEditorInput input = (EsbEditorInput) editorPart.getEditorInput(); IFile file = input.getXmlResource(); activeProject = file.getProject(); } } return activeProject; } private String getMavenGroupID(IProject project) { String groupID = "com.example"; //$NON-NLS-1$ try { MavenProject mavenProject = MavenUtils.getMavenProject(project.getFile("pom.xml").getLocation().toFile()); //$NON-NLS-1$ groupID = mavenProject.getGroupId() + ".sequence"; //$NON-NLS-1$ } catch (Exception e) { //ignore. Then group id would be default. } return groupID; } private ESBArtifact createArtifact(String name, String groupId, String version, String path, String type) { ESBArtifact artifact = new ESBArtifact(); artifact.setName(name); artifact.setVersion(version); artifact.setType(type); artifact.setServerRole("EnterpriseServiceBus"); //$NON-NLS-1$ artifact.setGroupId(groupId); artifact.setFile(path); return artifact; } public void openWithSeparateEditor() throws Exception { IProject activeProject = EditorUtils.getActiveProjectSafemode(); String name = ((Sequence) ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) getModel()).getElement()).getName(); //if (sequenceStorage.sequences.get(name) == null) { if (!name.equals("")) { //$NON-NLS-1$ /* * Tool group creations in the Tool pallete. */ /* if ((getEditDomain().getPaletteViewer().getPaletteRoot().getChildren().size() - 2) != ToolPalleteDetails.SEQUENCE) { getEditDomain().getPaletteViewer().getPaletteRoot().add(createSequenceGroup()); } if (!definedSequenceNames.contains(name)) { ((PaletteContainer) getEditDomain().getPaletteViewer().getPaletteRoot() .getChildren().get(ToolPalleteDetails.SEQUENCE)) .add(createSequence4CreationTool(name)); definedSequenceNames.add(name); }*/ } /* * File creations. */ createAndOpenFile(name, "sequence_" + name + ".esb_diagram", "sequence_" + name + ".esb", activeProject); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //EditorUtils.updateToolpalette(); } public boolean createAndOpenFile(String name, String fileURI1, String fileURI2, IProject currentProject) throws Exception { IFile file = currentProject.getFile(SEQUENCE_RESOURCE_DIR + "/" + fileURI1); //$NON-NLS-1$ if (((Sequence) ((Node) sequenceEditPart.getModel()).getElement()).isReceiveSequence()) { info.setRecieveSequence(true); info.setAssociatedProxy(((ProxyService) ((Node) EditorUtils.getProxy(sequenceEditPart.getParent()) .getModel()).getElement()).getName()); } if (!file.exists()) { IFile fileTobeOpened = null; boolean registryProject = false; if(currentProject.hasNature("org.wso2.developerstudio.eclipse.general.project.nature")){ //$NON-NLS-1$ fileTobeOpened = currentProject.getFile(name + ".xml"); //$NON-NLS-1$ registryProject = true; }else{ fileTobeOpened = currentProject.getFile(SYNAPSE_CONFIG_DIR + "/sequences/" + name + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ } if (fileTobeOpened.exists()) { OpenEditorUtils oeUtils = new OpenEditorUtils(); oeUtils.openSeparateEditor(fileTobeOpened); } else { if(registryProject){ addSequenceToRegistryArtifactXML(name, currentProject); }else{ addSequenceToArtifactXML(name); updatePom(); } String path = fileTobeOpened.getParent().getFullPath() + "/"; //$NON-NLS-1$ ArtifactTemplate sequenceArtifactTemplate = getSequenceTemplates()[0]; String source = FileUtils.getContentAsString(sequenceArtifactTemplate.getTemplateDataStream()); source = MessageFormat.format(source, name); fileTobeOpened .create(new ByteArrayInputStream(source.getBytes()), true, new NullProgressMonitor()); Openable openable = ESBGraphicalEditor.getOpenable(); openable.editorOpen(fileTobeOpened.getName(), ArtifactType.SEQUENCE.getLiteral(), path, source); } return true; } else { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(file.getName()); try { page.openEditor(new FileEditorInput(file), desc.getId()); } catch (PartInitException e) { log.error("Cannot init editor", e); //$NON-NLS-1$ } return true; } } private void updatePom() throws IOException, XmlPullParserException { File mavenProjectPomLocation = getActiveProject().getFile("pom.xml").getLocation().toFile(); //$NON-NLS-1$ MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation); // Skip changing the pom file if group ID and artifact ID are matched if (MavenUtils.checkOldPluginEntry(mavenProject, "org.wso2.maven", "wso2-esb-sequence-plugin")) { //$NON-NLS-1$ //$NON-NLS-2$ return; } Plugin plugin = MavenUtils.createPluginEntry(mavenProject, "org.wso2.maven", "wso2-esb-sequence-plugin", //$NON-NLS-1$ //$NON-NLS-2$ ESBMavenConstants.WSO2_ESB_SEQUENCE_VERSION, true); PluginExecution pluginExecution = new PluginExecution(); pluginExecution.addGoal("pom-gen"); //$NON-NLS-1$ pluginExecution.setPhase("process-resources"); //$NON-NLS-1$ pluginExecution.setId("sequence"); //$NON-NLS-1$ Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(); Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation"); //$NON-NLS-1$ artifactLocationNode.setValue("."); //$NON-NLS-1$ Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList"); //$NON-NLS-1$ typeListNode.setValue("${artifact.types}"); //$NON-NLS-1$ pluginExecution.setConfiguration(configurationNode); plugin.addExecution(pluginExecution); MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation); } private PaletteContainer createSequenceGroup() { PaletteDrawer paletteContainer = new PaletteDrawer("Sequences"); //$NON-NLS-1$ paletteContainer.setId("Sequences"); //$NON-NLS-1$ return paletteContainer; } private ToolEntry createSequence4CreationTool(String name) { ArrayList<IElementType> types = new ArrayList<IElementType>(2); types.add(EsbElementTypes.Sequence_3503); /*types.add(EsbElementTypes.Sequence_3187); types.add(EsbElementTypes.Sequence_3254); types.add(EsbElementTypes.Sequence_3375);*/ NodeToolEntry entry = new NodeToolEntry(name, "", types); //$NON-NLS-1$ entry.setId("createSequence4CreationTool"); //$NON-NLS-1$ entry.setSmallIcon(EsbElementTypes.getImageDescriptor(EsbElementTypes.Sequence_3503)); entry.setLargeIcon(entry.getSmallIcon()); return entry; } public void createDialogBox() throws Exception { final EObject diagram = ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) getModel()) .getDiagram().getChildren().get(0)).getElement().eContainer(); final EObject sequence = (Sequence) ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) getModel()).getElement(); // For validation: user should not enter "" value for name. if (((Sequence) sequence).getName().trim().equals("")) { //$NON-NLS-1$ IInputValidator validator = new IInputValidator() { public String isValid(String str) { if (str.trim().isEmpty()) { return "Sequence name cannot be empty"; //$NON-NLS-1$ } else if (str.indexOf(0x20) != -1) { return "Sequence name cannot contain spaces"; //$NON-NLS-1$ } return null; } }; //String defaultName = "Sequence_" + (((EsbDiagram) diagram).getTest() + 1); String defaultName = calculateDefaultName(); final InputDialog sequenceNameInput = new InputDialog(new Shell(), "Enter Sequence Name", "Sequence Name", //$NON-NLS-1$ //$NON-NLS-2$ defaultName, validator) { protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); /* recieveCheckBox = new Button(composite, SWT.CHECK); recieveCheckBox.setText("Use this sequence as a Recieving sequence."); recieveCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { checked = recieveCheckBox.getSelection(); } public void widgetDefaultSelected(SelectionEvent arg0) { } });*/ return composite; } }; int open = sequenceNameInput.open(); if (open == Dialog.OK) { Display.getDefault().asyncExec(new Runnable() { public void run() { String sequenceName = sequenceNameInput.getValue(); TransactionalEditingDomain editingDomain = getEditingDomain(); /* SetRequest setRequestSequenceCount = new SetRequest(editingDomain, diagram, EsbPackage.eINSTANCE.getEsbDiagram_Test(), ((EsbDiagram) diagram) .getTest() + 1); SetValueCommand operationSequenceCount = new SetValueCommand( setRequestSequenceCount) { public boolean canUndo() { return true; } public boolean canRedo() { return true; } }; ICommandProxy commandSequenceCount = new ICommandProxy( operationSequenceCount); if (commandSequenceCount.canExecute()) { getEditDomain().getCommandStack().execute(commandSequenceCount); }*/ SetRequest setRequest = new SetRequest(editingDomain, sequence, EsbPackage.eINSTANCE .getSequence_Name(), sequenceName); SetValueCommand operation = new SetValueCommand(setRequest) { public boolean canUndo() { return true; } public boolean canRedo() { return true; } }; getEditDomain().getCommandStack().execute(new ICommandProxy(operation)); /* if (checked) { info.setRecieveSequence(true); info.setAssociatedProxy(((ProxyService) ((Node) EditorUtils.getProxy( sequenceEditPart.getParent()).getModel()).getElement()) .getName()); }*/ /* IProject activeProject = getActiveProject(); ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact(); try { esbProjectArtifact.fromFile(activeProject.getFile("artifact.xml") .getLocation().toFile()); esbProjectArtifact.addESBArtifact(createArtifact(sequenceName, getMavenGroupID(activeProject), "1.0.0", "src/main/synapse-config/sequences/" + sequenceName + ".xml", "synapse/sequence")); esbProjectArtifact.toFile(); } catch (Exception e) { log.error("Error while updating Artifact.xml"); }*/ try { openWithSeparateEditor(); } catch (Exception e) { log.error("Cannot open sequence file ", e); //$NON-NLS-1$ MessageDialog.openError(Display.getCurrent().getActiveShell(), "Cannot open sequence file ", //$NON-NLS-1$ e.getLocalizedMessage()); } } }); } } else { openWithSeparateEditor(); } } public String calculateDefaultName() { IProject activeProject = getActiveProject(); String finalName = "Sequence_1"; //$NON-NLS-1$ int i = 1; try { while (ESBProjectUtils.artifactExists(activeProject, finalName)) { finalName = finalName.replaceAll("\\d+$", ""); //$NON-NLS-1$ //$NON-NLS-2$ i++; finalName = finalName.concat(i + ""); //$NON-NLS-1$ } } catch (Exception e) { finalName = finalName.concat("_").concat(RandomStringUtils.randomAlphabetic(5)).concat("_" + i); //$NON-NLS-1$ //$NON-NLS-2$ } return finalName; } private void addSequenceToArtifactXML(String sequenceName) { IProject activeProject = getActiveProject(); ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact(); try { esbProjectArtifact.fromFile(activeProject.getFile("artifact.xml").getLocation().toFile()); //$NON-NLS-1$ esbProjectArtifact.addESBArtifact(createArtifact(sequenceName, getMavenGroupID(activeProject), "1.0.0", //$NON-NLS-1$ "src/main/synapse-config/sequences/" + sequenceName + ".xml", "synapse/sequence")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ esbProjectArtifact.toFile(); } catch (Exception e) { log.error("Error while updating Artifact.xml",e); //$NON-NLS-1$ } } private void addSequenceToRegistryArtifactXML(String sequenceName, IProject currentProject) { GeneralProjectArtifact generalProjectArtifact = new GeneralProjectArtifact(); try { generalProjectArtifact.fromFile(currentProject.getFile("artifact.xml").getLocation().toFile()); //$NON-NLS-1$ File pomLocation = currentProject.getFile("pom.xml").getLocation().toFile(); //$NON-NLS-1$ MavenProject mavenProject = MavenUtils.getMavenProject(pomLocation); RegistryArtifact artifact = new RegistryArtifact(); artifact.setName(sequenceName); artifact.setVersion(mavenProject.getVersion()); artifact.setType("registry/resource"); //$NON-NLS-1$ artifact.setServerRole("GovernanceRegistry"); //$NON-NLS-1$ artifact.setGroupId(mavenProject.getGroupId()+".resource"); //$NON-NLS-1$ RegistryElement item = new RegistryItem(); ((RegistryItem) item).setFile(sequenceName + ".xml"); //$NON-NLS-1$ ((RegistryItem) item).setPath("/_system/governance/sequences"); //$NON-NLS-1$ ((RegistryItem) item).setMediaType("application/vnd.wso2.sequence"); //$NON-NLS-1$ artifact.addRegistryElement(item); generalProjectArtifact.addArtifact(artifact); generalProjectArtifact.toFile(); } catch (Exception e) { log.error("Error while updating Artifact.xml", e); //$NON-NLS-1$ } } /** * @generated NOT */ public class SequenceFigure extends EsbGraphicalShapeWithLabel { /** * @generated */ private WrappingLabel fSequenceLabelFigure; /** * @generated NOT */ public SequenceFigure() { /* * GridLayout layoutThis = new GridLayout(); layoutThis.numColumns = * 1; layoutThis.makeColumnsEqualWidth = true; * this.setLayoutManager(layoutThis); * * this.setCornerDimensions(new Dimension(getMapMode().DPtoLP(8), * getMapMode().DPtoLP(8))); */ this.setBackgroundColor(THIS_BACK); createContents(); /* * this.addMouseListener(new MouseListener() { * * public void mouseReleased(MouseEvent me) { // TODO Auto-generated * method stub System.out.println("Released"); } * * public void mousePressed(MouseEvent me) { * //openWithSeparateEditor(); * * /*final EObject diagram = * ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) * ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) getModel()) * .getDiagram().getChildren().get(0)).getElement() .eContainer(); * String name = ((Sequence) * ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) getModel()) * .getElement()).getName(); if (sequenceStorage.sequences.get(name) * == null) { * * TransactionalEditingDomain editingDomain = getEditingDomain(); * SetRequest setRequest = new SetRequest(editingDomain, diagram, * EsbPackage.eINSTANCE .getEsbDiagram_Test(), ((EsbDiagram) * diagram).getTest() + 1); SetValueCommand operation = new * SetValueCommand( setRequest) { * * public boolean canUndo() { return true; } * * public boolean canRedo() { return true; } }; * * getEditDomain().getCommandStack().execute( new * ICommandProxy(operation)); * * sequenceStorage.sequences.put(name, ((EsbDiagram) * diagram).getTest()); * * * // * Tool group creations in the Tool pallete. * * * if ((getEditDomain().getPaletteViewer() * .getPaletteRoot().getChildren().size() - 1) != * ToolPalleteDetails.SEQUENCE) { * getEditDomain().getPaletteViewer().getPaletteRoot() * .add(createSequenceGroup()); } * * ((PaletteContainer) getEditDomain().getPaletteViewer() * .getPaletteRoot().getChildren() * .get(ToolPalleteDetails.SEQUENCE)) * .add(createSequence4CreationTool(name)); * * } * * * // * File creations. * * SequenceFileCreator sequenceFileCreator = new * SequenceFileCreator(); * sequenceFileCreator.createFiles("sequence_" + name + * ".sequence_diagram", "sequence_" + name + ".sequence"); * * * /* IFile file = * ResourcesPlugin.getWorkspace().getRoot().getProject ("testing") * .getFile("sequence"+sequenceStorage.sequences. * get(currentSequence).toString()+".sequence_diagram"); * * if(!file.exists()){ * * createFiles(); try { file.create(null, IResource.NONE, null); } * catch (CoreException e1) { // TODO Auto-generated catch block * e1.printStackTrace(); } } file = * ResourcesPlugin.getWorkspace().getRoot().getProject("testing" ) * .getFile("sequence"+sequenceStorage.sequences.get( * currentSequence).toString()+".sequence_diagram"); * * IWorkbenchPage page = PlatformUI.getWorkbench() * .getActiveWorkbenchWindow().getActivePage(); //System.out. * println("xxxxxxxxxx"+sequenceStorage.sequences * .get(currentSequence * )+" "+page.getActiveEditor().getEditorInput ().getName()); * HashMap map = new HashMap(); map.put(IMarker.LINE_NUMBER, new * Integer(5)); map.put(IWorkbenchPage.EDITOR_ID_ATTR, * "org.wso2.developerstudio.eclipse.gmf.esb.sequence.diagram.part.EsbDiagramEditorID" * ); IMarker marker; try { marker = * file.createMarker(IMarker.TEXT); * * marker.setAttributes(map); // page.openEditor(marker); //2.1 API * IDE.openEditor(page, marker); // 3.0 API marker.delete(); } catch * (CoreException e) { // TODO Auto-generated catch block * e.printStackTrace(); } * * * } * * public void mouseDoubleClicked(MouseEvent me) { // TODO * Auto-generated method stub System.out.println("DoubleClicked"); * * } * * }); */ } private PaletteContainer createSequenceGroup() { PaletteDrawer paletteContainer = new PaletteDrawer("Sequences"); //$NON-NLS-1$ paletteContainer.setId("Sequences"); //$NON-NLS-1$ return paletteContainer; } private ToolEntry createSequence4CreationTool(String name) { NodeToolEntry entry = new NodeToolEntry(name, "", //$NON-NLS-1$ Collections.singletonList(EsbElementTypes.Sequence_3503)); entry.setId("createSequence4CreationTool"); //$NON-NLS-1$ entry.setSmallIcon(EsbElementTypes.getImageDescriptor(EsbElementTypes.Sequence_3503)); entry.setLargeIcon(entry.getSmallIcon()); return entry; } /** * @generated NOT */ private void createContents() { /*fSequenceLabelFigure = new WrappingLabel(); fSequenceLabelFigure.setText(""); fSequenceLabelFigure.setAlignment(PositionConstants.TOP | PositionConstants.CENTER); fSequenceLabelFigure.setFont(new Font(null, new FontData("Courier", 8, SWT.BOLD))); this.getPropertyValueRectangle1().add(fSequenceLabelFigure);*/ fSequenceLabelFigure = getPropertyNameLabel(); } /* *//** * @generated NOT */ /* * protected void fillShape(Graphics graphics) { // Backup the graphics * colors Color bgColor = graphics.getBackgroundColor(); Color fgColor = * graphics.getForegroundColor(); // Set the graphics color * graphics.setBackgroundColor(getBackgroundColor()); * graphics.setForegroundColor(ColorConstants.white); // Restore the * original colors graphics.fillGradient(getBounds(), true); * graphics.setBackgroundColor(bgColor); * graphics.setForegroundColor(fgColor); } */ /** * @generated */ public WrappingLabel getSequenceLabelFigure() { return fSequenceLabelFigure; } public String getIconPath() { return SEQUENCE_MEDIATOR_ICON_PATH; } public String getNodeName() { return Messages.SequenceEditPart_NodeName; } public IFigure getToolTip() { if (StringUtils.isEmpty(toolTipMessage)) { return new Label(Messages.SequenceEditPart_ToolTip); } else { return new Label(toolTipMessage); } } } /** * @generated */ static final Color THIS_BACK = new Color(null, 255, 255, 255); /* * This will be used for arrange the connectors to the right side of the figure. */ public void moveConnectorsRightSide() { for (int i = 0; i < this.getChildren().size(); ++i) { if (this.getChildren().get(i) instanceof AbstractMediatorInputConnectorEditPart) { IFigure inputConnector = ((AbstractMediatorInputConnectorEditPart) this.getChildren().get(i)) .getFigure(); NodeFigure figureInput = ((AbstractMediatorInputConnectorEditPart) this.getChildren().get(i)) .getNodeFigureInput(); figureInput.removeAll(); figureInput.add(((AbstractMediatorInputConnectorEditPart) this.getChildren().get(i)) .getPrimaryShapeReverse()); BorderItemLocator inputLocator = new FixedBorderItemLocator(this.getMainFigure(), inputConnector, PositionConstants.EAST, 0.30); this.getBorderedFigure().getBorderItemContainer().remove(inputConnector); this.getBorderedFigure().getBorderItemContainer().add(inputConnector, inputLocator); } } for (int i = 0; i < this.getChildren().size(); ++i) { if (this.getChildren().get(i) instanceof AbstractMediatorOutputConnectorEditPart) { IFigure outputConnector = ((AbstractMediatorOutputConnectorEditPart) this.getChildren().get(i)) .getFigure(); NodeFigure figureOutput = ((AbstractMediatorOutputConnectorEditPart) this.getChildren().get(i)) .getNodeFigureOutput(); figureOutput.removeAll(); Figure emptyFigure = new Figure(); figureOutput.add(emptyFigure); /* figureOutput.add(((AbstractMediatorOutputConnectorEditPart) this.getChildren().get( i)).getPrimaryShapeForward());*/ BorderItemLocator outputLocator = new FixedBorderItemLocator(this.getMainFigure(), outputConnector, PositionConstants.EAST, 0.70); this.getBorderedFigure().getBorderItemContainer().remove(outputConnector); this.getBorderedFigure().getBorderItemContainer().add(outputConnector, outputLocator); } } } public static class NodeToolEntry extends PaletteToolEntry { private final List<IElementType> elementTypes; private NodeToolEntry(String title, String description, List<IElementType> elementTypes) { // super(title, description, null, null); super(null, title, null); this.setDescription(description); this.elementTypes = elementTypes; } public Tool createTool() { Tool tool = new UnspecifiedTypeCreationTool(elementTypes); tool.setProperties(getToolProperties()); return tool; } } public class SequencesInfo { private String associatedProxy; private boolean recieveSequence; public void setAssociatedProxy(String associatedProxy) { this.associatedProxy = associatedProxy; } public String getAssociatedProxy() { return associatedProxy; } public void setRecieveSequence(boolean recieveSequence) { this.recieveSequence = recieveSequence; } public boolean isRecieveSequence() { return recieveSequence; } } private ArtifactTemplate[] getSequenceTemplates() { Map<String,List<String>> filters=new HashMap<String,List<String>> (); DeveloperStudioProviderUtils.addFilter(filters,CSProviderConstants.FILTER_MEDIA_TYPE, ESBMediaTypeConstants.MEDIA_TYPE_SEQUENCE); return ArtifactTemplateHandler.getArtifactTemplates(filters); } }
package com.sap.core.extensions.businesspartners; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.jwt.Jwt; import com.sap.cloud.security.xsuaa.XsuaaServiceConfiguration; import com.sap.cloud.security.xsuaa.token.TokenAuthenticationConverter; @Configuration @EnableWebSecurity class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private XsuaaServiceConfiguration xsuaaServiceConfiguration; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)// .and()// .authorizeRequests().anyRequest().authenticated()// .and()// .oauth2ResourceServer().jwt().jwtAuthenticationConverter(getJwtAuthoritiesConverter()); } Converter<Jwt, AbstractAuthenticationToken> getJwtAuthoritiesConverter() { TokenAuthenticationConverter converter = new TokenAuthenticationConverter(xsuaaServiceConfiguration); converter.setLocalScopeAsAuthorities(true); return converter; } }
/** * The MIT License * Copyright (c) 2010 JmxTrans team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.googlecode.jmxtrans.model; public final class QueryFixtures { private QueryFixtures() {} public static Query dummyQuery() { return Query.builder() .setObj("myQuery:key=val") .build(); } public static Query queryWithAllTypeNames() { return Query.builder() .setObj("myQuery:key=val") .setUseAllTypeNames(true) .build(); } public static Query queryAllowingDottedKeys() { return Query.builder() .setObj("myQuery:key=val") .setAllowDottedKeys(true) .build(); } public static Query queryUsingDomainAsKey() { return Query.builder() .setObj("myQuery:key=val") .setUseObjDomainAsKey(true) .build(); } }
package pl.coderstrust.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${spring.security.user.name}") private String userName; @Value("${spring.security.user.password}") private String userPassword; @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .disable() .csrf() .disable() .authorizeRequests() .anyRequest() .hasRole("USER") .anyRequest() .authenticated() .and() .httpBasic() .and() .formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(userName) .password(passwordEncoder() .encode(userPassword)) .roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
/* * Copyright (c) 2020, Fraunhofer AISEC. 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 de.fraunhofer.aisec.cpg.graph.declarations; import de.fraunhofer.aisec.cpg.graph.DeclarationHolder; import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; import org.neo4j.ogm.annotation.Relationship; /** * This represents a sequence of one or more declaration(s). The purpose of this node is primarily * to bridge between a single declaration and a list of declarations in the front-end handlers. It * will be converted into a list-structure and all its children will be added to the parent, i.e. * the translation unit. It should not end up in the final graph. */ public class DeclarationSequence extends Declaration implements DeclarationHolder { @Relationship(value = "CHILDREN", direction = "OUTGOING") private final List<PropertyEdge<Declaration>> children = new ArrayList<>(); public List<PropertyEdge<Declaration>> getChildrenPropertyEdge() { return this.children; } public List<Declaration> getChildren() { List<Declaration> target = new ArrayList<>(); for (PropertyEdge<Declaration> propertyEdge : this.children) { target.add(propertyEdge.getEnd()); } return Collections.unmodifiableList(target); } public void addDeclaration(@NonNull Declaration declaration) { if (declaration instanceof DeclarationSequence) { for (Declaration declarationChild : ((DeclarationSequence) declaration).getChildren()) { addIfNotContains(this.children, declarationChild); } } addIfNotContains(this.children, declaration); } public List<Declaration> asList() { return getChildren(); } public boolean isSingle() { return children.size() == 1; } public Declaration first() { return children.get(0).getEnd(); } @NotNull public List<Declaration> getDeclarations() { return getChildren(); } }
package com.github.tinosteinort.flda.fixedlengthstring.writer; public class FloatAttributeWriter extends NumberAttributeWriter<Float> { @Override protected String nullSafeConvertToString(final Float value) { return String.valueOf(value); } }
package org.projectbyte.factions.event.movement; import org.bukkit.entity.Player; import org.projectbyte.factions.event.FactionEvent; import org.projectbyte.factions.structure.claim.Claim; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public class PlayerEnterClaimEvent extends FactionEvent { /** * The Player that had entered the Claim */ private Player player; /** * The Claim that the Player had entered */ private Claim claimEntered; }
package indi.yume.tools.avocado.model.tuple; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * Created by yume on 16/3/8. */ @Data @EqualsAndHashCode @AllArgsConstructor(staticName = "of") @NoArgsConstructor public class Tuple4<T1, T2, T3, T4> { private T1 data1; private T2 data2; private T3 data3; private T4 data4; }
package threshold; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rabbitmq.client.Channel; import com.rabbitmq.client.QueueingConsumer; import common.AMQPCommon; public class AMQPConsumer { //actual response times int lower = 0; int upper = 0; public void execute(String mode) throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("trade.request.q", true, consumer); if (mode.equalsIgnoreCase("stable")) {lower = 300; upper = 1200;} if (mode.equalsIgnoreCase("better")) {lower = 300; upper = 800;} if (mode.equalsIgnoreCase("worse")) {lower = 800; upper = 1900;} if (mode.equalsIgnoreCase("erratic")) {lower = 200; upper = 5000;} while (true) { QueueingConsumer.Delivery message = consumer.nextDelivery(); String msg = new String(message.getBody()); System.out.println("trade order received: " + msg); int response = lower + (int) (Math.random() * (upper-lower)); System.out.println("trade placed, duration = " + response); String newMsg = "response"; byte[] bmsg = newMsg.getBytes(); Thread.sleep(response); channel.basicPublish("", "trade.response.q", null, bmsg); } } public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("specify mode (worse, better, stable, erratic)"); } else { new AMQPConsumer().execute(args[0]); } } }
/* * 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.rules; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import static org.junit.Assume.assumeNoException; import com.facebook.buck.jvm.java.JavaBinary; import com.facebook.buck.jvm.java.JavaLibraryBuilder; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.testutil.TargetGraphFactory; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.concurrent.MostExecutors; import com.google.common.util.concurrent.MoreExecutors; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.Matchers; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class BuildRuleResolverTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @FunctionalInterface private interface BuildRuleResolverFactory { BuildRuleResolver create(TargetGraph graph, TargetNodeToBuildRuleTransformer transformer); default BuildRuleResolver create(TargetGraph graph) { return create(graph, new DefaultTargetNodeToBuildRuleTransformer()); } } private static ForkJoinPool pool = new ForkJoinPool(4); @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { return Arrays.asList( new Object[][] { { SingleThreadedBuildRuleResolver.class, (BuildRuleResolverFactory) SingleThreadedBuildRuleResolver::new, MoreExecutors.newDirectExecutorService(), }, { MultiThreadedBuildRuleResolver.class, (BuildRuleResolverFactory) (graph, transformer) -> new MultiThreadedBuildRuleResolver(pool, graph, transformer, null), pool, }, }); } @Parameterized.Parameter(0) public Class<? extends BuildRuleResolver> classUnderTest; @Parameterized.Parameter(1) public BuildRuleResolverFactory buildRuleResolverFactory; @Parameterized.Parameter(2) public ExecutorService executorService; @AfterClass public static void afterClass() { pool.shutdownNow(); } @Test public void testBuildAndAddToIndexRejectsDuplicateBuildTarget() throws Exception { BuildRuleResolver buildRuleResolver = buildRuleResolverFactory.create(TargetGraph.EMPTY); BuildTarget target = BuildTargetFactory.newInstance("//foo:bar"); buildRuleResolver.addToIndex(new FakeBuildRule(target)); // A BuildRuleResolver should allow only one entry for a BuildTarget. try { buildRuleResolver.addToIndex(new FakeBuildRule(target)); fail("Should throw IllegalStateException."); } catch (IllegalStateException e) { assertEquals( "A build rule for this target has already been created: " + target, e.getMessage()); } } @Test public void testRequireNonExistingBuildRule() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:bar"); TargetNode<?, ?> library = JavaLibraryBuilder.createBuilder(target).build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(library); BuildRuleResolver resolver = buildRuleResolverFactory.create(targetGraph); BuildRule rule = resolver.requireRule(target); assertThat(rule, is(notNullValue())); assertThat(rule.getBuildTarget(), is(equalTo(target))); } @Test public void testRequireExistingBuildRule() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:bar"); JavaLibraryBuilder builder = JavaLibraryBuilder.createBuilder(target); TargetNode<?, ?> library = builder.build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(library); BuildRuleResolver resolver = buildRuleResolverFactory.create(targetGraph); BuildRule existing = resolver.requireRule(target); assertThat(resolver.getRuleOptional(target).isPresent(), is(true)); BuildRule rule = resolver.requireRule(target); assertThat(rule, is(notNullValue())); assertThat(rule.getBuildTarget(), is(equalTo(target))); assertThat(rule, is(equalTo(existing))); } @Test public void getRuleWithTypeMissingRule() throws Exception { BuildRuleResolver resolver = buildRuleResolverFactory.create(TargetGraph.EMPTY); expectedException.expect(HumanReadableException.class); expectedException.expectMessage(Matchers.containsString("could not be resolved")); resolver.getRuleWithType(BuildTargetFactory.newInstance("//:non-existent"), BuildRule.class); } @Test public void getRuleWithTypeWrongType() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:bar"); JavaLibraryBuilder builder = JavaLibraryBuilder.createBuilder(target); TargetNode<?, ?> library = builder.build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(library); BuildRuleResolver resolver = buildRuleResolverFactory.create(targetGraph); resolver.requireRule(target); expectedException.expect(HumanReadableException.class); expectedException.expectMessage(Matchers.containsString("not of expected type")); resolver.getRuleWithType(BuildTargetFactory.newInstance("//foo:bar"), JavaBinary.class); } @Test public void computeIfAbsentComputesOnlyIfAbsent() throws Exception { BuildRuleResolver resolver = buildRuleResolverFactory.create(TargetGraph.EMPTY); BuildTarget target = BuildTargetFactory.newInstance("//:target"); AtomicInteger supplierInvoked = new AtomicInteger(0); BuildRule buildRule = new NoopBuildRuleWithDeclaredAndExtraDeps( target, new FakeProjectFilesystem(), TestBuildRuleParams.create()); BuildRule returnedBuildRule = executorService .submit( () -> resolver.computeIfAbsent( target, passedTarget -> { assertEquals(passedTarget, target); supplierInvoked.incrementAndGet(); return buildRule; })) .get(); assertEquals("supplier was called once", supplierInvoked.get(), 1); assertSame("returned the same build rule that was generated", returnedBuildRule, buildRule); assertSame("the rule can be retrieved again", resolver.getRule(target), buildRule); returnedBuildRule = executorService .submit( () -> resolver.computeIfAbsent( target, passedTarget -> { assertEquals(passedTarget, target); supplierInvoked.incrementAndGet(); return buildRule; })) .get(); assertEquals("supplier is not called again", supplierInvoked.get(), 1); assertSame("recorded rule is still returned", returnedBuildRule, buildRule); } @Test public void accessingSameTargetWithinSameThreadActsAsIfItDoesNotExist() { BuildTarget target = BuildTargetFactory.newInstance("//foo:bar"); TargetNode<?, ?> library = JavaLibraryBuilder.createBuilder(target).build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(library); BuildRuleResolver resolver = buildRuleResolverFactory.create( targetGraph, new TargetNodeToBuildRuleTransformer() { @Override public <T, U extends Description<T>> BuildRule transform( TargetGraph targetGraph, BuildRuleResolver ruleResolver, TargetNode<T, U> targetNode) { Assert.assertFalse(ruleResolver.getRuleOptional(target).isPresent()); return ruleResolver.computeIfAbsent(target, FakeBuildRule::new); } }); resolver.requireRule(target); } @Test public void accessingTargetBeingBuildInDifferentThreadsWaitsForItsCompletion() throws Exception { Assume.assumeTrue(classUnderTest == MultiThreadedBuildRuleResolver.class); BuildTarget target1 = BuildTargetFactory.newInstance("//foo:bar1"); TargetNode<?, ?> library1 = JavaLibraryBuilder.createBuilder(target1).build(); BuildTarget target2 = BuildTargetFactory.newInstance("//foo:bar2"); TargetNode<?, ?> library2 = JavaLibraryBuilder.createBuilder(target2).build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(library1, library2); CountDownLatch jobsStarted = new CountDownLatch(2); CountDownLatch target1Finish = new CountDownLatch(1); ConcurrentHashMap<BuildTarget, Boolean> transformCalls = new ConcurrentHashMap<>(); BuildRuleResolver resolver = buildRuleResolverFactory.create( targetGraph, new TargetNodeToBuildRuleTransformer() { @Override public <T, U extends Description<T>> BuildRule transform( TargetGraph targetGraph, BuildRuleResolver ruleResolver, TargetNode<T, U> targetNode) { Boolean existing = transformCalls.put(targetNode.getBuildTarget(), true); assertEquals("Should only be called once for each build target", null, existing); try { if (targetNode.getBuildTarget().equals(target1)) { jobsStarted.countDown(); target1Finish.await(); } else if (targetNode.getBuildTarget().equals(target2)) { jobsStarted.countDown(); // There's a race condition here where target1 is allowed to proceed before we // start waiting. This will result in a false-negative if this test would fail. ruleResolver.requireRule(target1); } else { throw new AssertionError("only 2 targets should be specified in this test."); } } catch (InterruptedException e) { throw new RuntimeException(e); } return new FakeBuildRule(targetNode.getBuildTarget()); } }); Future<BuildRule> first = executorService.submit(() -> resolver.requireRule(target1)); Future<BuildRule> second = executorService.submit(() -> resolver.requireRule(target2)); jobsStarted.await(); // wait for both jobs to start. Thread.sleep(10); // Insert a small delay to reduce the chances of race condition. target1Finish.countDown(); first.get(); second.get(); assertEquals("transform() should be called exactly twice", 2, transformCalls.size()); } @Test(timeout = 5000) public void deadLockOnDependencyTest() throws ExecutionException, InterruptedException { Assume.assumeTrue(classUnderTest == MultiThreadedBuildRuleResolver.class); /** * create a graph of the following * * <pre>foo:bar0 foo:bar1 foo:bar2 foo:bar3 * \ \ / / * foo:bar4 * </pre> * * <p>such that when the ThreadPool has all 4 threads executing bar0,...bar3, we block waiting * completion of bar4, but have no additional threads for bar4 * * <p>proper behaviour is to use one of the threads blocked on bar0,...bar3 to execute bar4. */ BuildTarget target4 = BuildTargetFactory.newInstance("//foo:bar4"); TargetNode<?, ?> library4 = JavaLibraryBuilder.createBuilder(target4).build(); BuildTarget target3 = BuildTargetFactory.newInstance("//foo:bar3"); TargetNode<?, ?> library3 = JavaLibraryBuilder.createBuilder(target3).addExportedDep(target4).build(); BuildTarget target2 = BuildTargetFactory.newInstance("//foo:bar2"); TargetNode<?, ?> library2 = JavaLibraryBuilder.createBuilder(target2).addExportedDep(target4).build(); BuildTarget target1 = BuildTargetFactory.newInstance("//foo:bar1"); TargetNode<?, ?> library1 = JavaLibraryBuilder.createBuilder(target1).addExportedDep(target4).build(); BuildTarget target0 = BuildTargetFactory.newInstance("//foo:bar0"); TargetNode<?, ?> library0 = JavaLibraryBuilder.createBuilder(target0).addExportedDep(target4).build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(library0, library1, library2, library3, library4); // Ensure the race condition occurs, where we have all of foo:bar0...foo:bar3 // running, but not called requireRule(foo:bar4) yet. CountDownLatch jobsStarted = new CountDownLatch(4); // run this with ThreadLimited FJP like our actual parallel implementation ForkJoinPool forkJoinPool = MostExecutors.forkJoinPoolWithThreadLimit(4, 0); try { BuildRuleResolver resolver = new MultiThreadedBuildRuleResolver( forkJoinPool, targetGraph, new TargetNodeToBuildRuleTransformer() { @Override public <T, U extends Description<T>> BuildRule transform( TargetGraph targetGraph, BuildRuleResolver ruleResolver, TargetNode<T, U> targetNode) { jobsStarted.countDown(); if (!targetNode.getExtraDeps().isEmpty()) { try { // this waits until all of bar0,...bar3 has executed up to this point before // requiring bar4, to create the situation where all 4 threads in ForkJoinPool // are blocked waiting for one dependency that has yet to be executed. jobsStarted.await(); } catch (InterruptedException e) { // stop the test if we've been interrupted assumeNoException(e); } targetNode.getExtraDeps().stream().forEach(ruleResolver::requireRule); } return new FakeBuildRule(targetNode.getBuildTarget()); } }, null); // mimic our actual parallel action graph construction, in which we call requireRule with // threads // outside the ForkJoinPool, which will then fork tasks to the ForkJoinPool. CompletableFuture first = CompletableFuture.runAsync(() -> resolver.requireRule(target0)); CompletableFuture second = CompletableFuture.runAsync(() -> resolver.requireRule(target1)); CompletableFuture third = CompletableFuture.runAsync(() -> resolver.requireRule(target2)); CompletableFuture fourth = CompletableFuture.runAsync(() -> resolver.requireRule(target3)); CompletableFuture.allOf(first, second, third, fourth).get(); } finally { forkJoinPool.shutdownNow(); } } }
/* * Copyright (c) 2019, Oracle and/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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.eclipse.imagen; import java.awt.RenderingHints; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.renderable.ParameterBlock; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Hashtable; import java.util.Observable; import java.util.Observer; import java.util.Vector; import org.eclipse.imagen.remote.SerializableState; import org.eclipse.imagen.remote.SerializerFactory; /** * This is a utility class that can be used by <code>OperationNode</code>s * to consolidate common functionality. An instance of this class may be * used as a member field of the <code>OperationNode</code> and some of the * <code>OperationNode</code>'s work delegated to it. * * @since JAI 1.1 */ public class OperationNodeSupport implements Serializable { // Constants supporting compare(). private static final int PB_EQUAL = 0x0; private static final int PB_SOURCES_DIFFER = 0x1; private static final int PB_PARAMETERS_DIFFER = 0x2; private static final int PB_DIFFER = PB_SOURCES_DIFFER | PB_PARAMETERS_DIFFER; // The OperationRegistryMode. private String registryModeName; // Critical attributes. private String opName; private transient OperationRegistry registry; private transient ParameterBlock pb; private transient RenderingHints hints; // Event helper. private PropertyChangeSupportJAI eventManager; /** * This instance variable is lazily constructed only when one of the * PropertySource methods or one of the local property environment * mutators is accessed. PropertyEnvironment is a package scope class. */ private transient PropertyEnvironment propertySource = null; /** * Stores local property environment modifications sequentially as * a PropertyGenerator, a String, or a CopyDirective depending * on which local property environment mutator method was invoked. */ private Vector localPropEnv = new Vector(); /** * <code>Map</code> of <code>ParamObserver</code>s of instances of * <code>DeferredData</code> in the parameter <code>Vector</code>. */ private Hashtable paramObservers = new Hashtable(); /** * Compare the contents of two <code>ParameterBlock</code>s. */ private static int compare(ParameterBlock pb1, ParameterBlock pb2) { if(pb1 == null && pb2 == null) { return PB_EQUAL; } if((pb1 == null && pb2 != null) || (pb1 != null && pb2 == null)) { return PB_DIFFER; } int result = PB_EQUAL; if(!equals(pb1.getSources(), pb2.getSources())) { result |= PB_SOURCES_DIFFER; } if(!equals(pb1.getParameters(), pb2.getParameters())) { result |= PB_PARAMETERS_DIFFER; } return result; } private static boolean equals(ParameterBlock pb1, ParameterBlock pb2) { return pb1 == null ? pb2 == null : equals(pb1.getSources(), pb2.getSources()) && equals(pb1.getParameters(), pb2.getParameters()); } private static boolean equals(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } /** * Constructs an <code>OperationNodeSupport</code> instance. * All parameters except <code>opName</code> may be <code>null</code>. * If non-<code>null</code> the <code>PropertyChangeSupportJAI</code> * should have been created with the node as its event source (note * that this cannot be verified). * * <p> The <code>ParameterBlock</code> may include * <code>DeferredData</code> parameters. These will not be evaluated * until their values are actually required, i.e., when the node is * rendered. Any <code>Observable</code> events generated by such * <code>DeferredData</code> parameters will be trapped by the node, * converted to a <code>PropertyChangeEventJAI</code> named "parameters", * and forwarded to any listeners registered with the supplied. * <code>eventManager</code>. The old and new values of the event object * so generated will be the previous and current values, respectively, of * the data object wrapped by the <code>DeferredData</code> parameter, * and thus will be instances of the class returned by the * <code>getDataClass()</code> method of the <code>DeferredData</code> * parameter. * * @param registryModeName The name of the registry mode concerned. * @param opName The operation name to set. * @param registry The <code>OperationRegistry</code> to set; * it may be <code>null</code> in which case the registry * will be set to the default JAI registry. * @param pb The <code>ParameterBlock</code> to set; * it may be <code>null</code>. * @param hints The new <code>RenderingHints</code> to be set; * it may be <code>null</code>. * @param eventManager The event helper object. The property change * event source of this object should be the * <code>OperationNode</code> which is using the constructed * <code>OperationNodeSupport</code> instance. If <code>null</code> * no events will be fired. * * @throws IllegalArgumentException if <code>registryModeName</code> * or <code>opName</code> is <code>null</code>. */ public OperationNodeSupport(String registryModeName, String opName, OperationRegistry registry, ParameterBlock pb, RenderingHints hints, PropertyChangeSupportJAI eventManager) { if(registryModeName == null || opName == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } // Set instance variables. this.registryModeName = registryModeName; this.opName = opName; if (registry == null) this.registry = JAI.getDefaultInstance().getOperationRegistry(); else this.registry = registry; this.pb = pb; this.hints = hints; this.eventManager = eventManager; // Set any DeferredData Observers. if(pb != null) { updateObserverMap(pb.getParameters()); } } /** * Class representing a copy-from-source directive set via * <code>copyPropertyFromSource()</code>. */ private class CopyDirective implements Serializable { /** The name of the property. */ private String name; /** The index of the source from which to copy the property. */ private int index; /** * Constructor. * * @param name The name of the property. * @param index The index of the source from which to copy the * property. */ CopyDirective(String name, int index) { if(name == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } this.name = name; this.index = index; } String getName() { return name; } int getIndex() { return index; } } /** * Class which is an <code>Observer</code> of a <code>DeferredData</code> * parameter. */ private class ParamObserver implements Observer { /** The index of the associated parameter. */ final int paramIndex; /** The <code>DeferredData</code> object to observe. */ final DeferredData dd; /** * Constructor. * * @param paramIndex The index of the associated parameter. * @param dd The <code>DeferredData</code> object to observe. */ ParamObserver(int paramIndex, DeferredData dd) { if(dd == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } else if(paramIndex < 0 || (pb != null && (paramIndex >= ((ParameterBlock)pb).getNumParameters()))) { throw new ArrayIndexOutOfBoundsException(); } this.paramIndex = paramIndex; this.dd = dd; // Add this object as an Observer of the Deferred Data. dd.addObserver(this); } /** * Implementation of <code>Observer</code>. An update from the * observed <code>DeferredData</code> causes an event to be fired * if the <code>DeferredData</code> had been previously evaluated * and there are event listeners. */ public synchronized void update(Observable o, Object arg) { if(!(o == dd)) { return; } // Do nothing unless the DeferredData was already evaluated. if(arg != null && eventManager != null) { Vector params = pb.getParameters(); Vector oldParams = (Vector)params.clone(); Vector newParams = (Vector)params.clone(); oldParams.set(paramIndex, arg); newParams.set(paramIndex, dd.getData()); fireEvent("Parameters", oldParams, newParams); } } } /** * Updates the <code>Map</code> of <code>Observer</code>s of * <code>DeferredData</code> instances in the parameter * <code>Vector</code>. */ private void updateObserverMap(Vector parameters) { if(parameters == null) { return; } int numParameters = parameters.size(); for(int i = 0; i < numParameters; i++) { Object parameter = parameters.get(i); Integer index = new Integer(i); // Replace or remove ParamObserver as needed. Object oldObs; if(parameter instanceof DeferredData) { Observer obs = new ParamObserver(i, (DeferredData)parameter); oldObs = paramObservers.put(index, obs); } else { oldObs = paramObservers.remove(index); } // Unregister Observer from the associated DeferredData. if(oldObs != null) { ParamObserver obs = (ParamObserver)oldObs; obs.dd.deleteObserver(obs); } } } /** * Returns the name of <code>RegistryMode</code> corresponding to * this <code>OperationNode</code>. This value shoud be immutable * for a given node. The value is returned by reference. */ public String getRegistryModeName() { return registryModeName; } /** * Returns the name of the operation the associated node represents. * The value is returned by reference. */ public String getOperationName() { return opName; } /** * Sets the name of the operation the associated node represents. * The value is set by reference. * * <p> If the operation name changes as a result of calling this * method according to a case-insensitive * comparison by <code>equals()</code> of the old and new names, * a <code>PropertyChangeEventJAI<code> named "OperationName" * will be fired by the event helper object with old and new values * set to the old and new values of the operation name, respectively. * * @param opName The new operation name to be set. * * @throws IllegalArgumentException if <code>opName</code> is * <code>null</code>. */ public void setOperationName(String opName) { if(opName == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } if(opName.equalsIgnoreCase(this.opName)) return; String oldOpName = this.opName; this.opName = opName; fireEvent("OperationName", oldOpName, opName); resetPropertyEnvironment(false); } /** * Returns the <code>OperationRegistry</code> used by the associated * node. The value is returned by reference. */ public OperationRegistry getRegistry() { return registry; } /** * Sets the <code>OperationRegistry</code> that is used by the associated * node. If the specified registry is <code>null</code>, the * registry will be set to the default JAI registry. The value is * set by reference. * * <p> If the registry changes according to a direct comparison * of the old and new registry references, * a <code>PropertyChangeEventJAI<code> named "OperationRegistry" * will be fired by the event helper object with old and new values * set to the old and new values of the registry, respectively. * * @param registry The new <code>OperationRegistry</code> to be set; * it may be <code>null</code>. */ public void setRegistry(OperationRegistry registry) { if(registry == null) { registry = JAI.getDefaultInstance().getOperationRegistry(); } if(registry != this.registry) { OperationRegistry oldRegistry = this.registry; this.registry = registry; fireEvent("OperationRegistry", oldRegistry, registry); resetPropertyEnvironment(false); } } /** * Returns the <code>ParameterBlock</code> of the associated node * by reference. Nodes desirous of maintaining a consistent state * for their <code>ParameterBlock</code> may prefer to clone the * value returned by this method. */ public ParameterBlock getParameterBlock() { return pb; } /** * Sets the <code>ParameterBlock</code> of the associated node by * reference. If the specified <code>ParameterBlock</code> is * <code>null</code>, it is assumed that the associated node has * neither input sources nor parameters. Nodes desirous of maintaining * a consistent state for their <code>ParameterBlock</code> may prefer * to clone any user-supplied <code>ParameterBlock</code> before passing * it to this method. * * <p> This method does not validate the content of the supplied * <code>ParameterBlock</code>. The caller should ensure that * the sources and parameters in the <code>ParameterBlock</code> * are suitable for the operation the associated node represents; otherwise * some form of error or exception may occur at the time of rendering. * * <p> If the <code>ParameterBlock</code> changes according to a * comparison of the sources and parameters <code>Vector</code>s of the * old and new <code>ParameterBlock</code>s using <code>equals()</code>, * a <code>PropertyChangeEventJAI<code> named "ParameterBlock" * will be fired by the event helper object with old and new values * set to the old and new values of the <code>ParameterBlock</code>, * respectively. A <code>PropertyChangeEventJAI<code> named "Sources" or * "Parameters" will instead be fired if it can be determined that the * <code>ParameterBlock</code> modification has affected only the sources * or parameters of the node, respectively. * * <p> The <code>ParameterBlock</code> may include * <code>DeferredData</code> parameters. These will not be evaluated * until their values are actually required, i.e., when the node is * rendered. Any <code>Observable</code> events generated by such * <code>DeferredData</code> parameters will be trapped by the node, * converted to a <code>PropertyChangeEventJAI</code> named "parameters", * and forwarded to any listeners registered with the supplied. * <code>eventManager</code>. The old and new values of the event object * so generated will be the previous and current values, respectively, of * the data object wrapped by the <code>DeferredData</code> parameter, * and thus will be instances of the class returned by the * <code>getDataClass()</code> method of the <code>DeferredData</code> * parameter. * * @param pb The new <code>ParameterBlock</code> to be set; * it may be <code>null</code>. */ public void setParameterBlock(ParameterBlock pb) { int comparison = compare(this.pb, pb); if(comparison == PB_EQUAL) { return; } ParameterBlock oldPB = this.pb; this.pb = pb; // Set any DeferredData Observers. if(pb != null) { updateObserverMap(pb.getParameters()); } if(comparison == PB_SOURCES_DIFFER) { // Sources have changed. fireEvent("Sources", oldPB.getSources(), pb.getSources()); } else if(comparison == PB_PARAMETERS_DIFFER) { // Parameters have changed. fireEvent("Parameters", oldPB.getParameters(), pb.getParameters()); } else { // Sources and parameters have changed. fireEvent("ParameterBlock", oldPB, pb); } resetPropertyEnvironment(false); } /** * Returns the <code>RenderingHints</code> of the associated node * by reference. Nodes desirous of maintaining a consistent state * for their <code>RenderingHints</code> may prefer to clone the * value returned by this method. */ public RenderingHints getRenderingHints() { return hints; } /** * Sets the <code>RenderingHints</code> of the associated node. It is * legal for nodes to ignore <code>RenderingHints</code> set on them by * this mechanism. Nodes desirous of maintaining * a consistent state for their <code>RenderingHints</code> may prefer * to clone any user-supplied <code>RenderingHints</code> before passing * it to this method. * * <p> If the <code>RenderingHints</code> changes according to a * comparison by <code>equals()</code> of the old and new hints, * a <code>PropertyChangeEventJAI<code> named "RenderingHints" * will be fired by the event helper object with old and new values * set to the old and new values of the <code>RenderingHints</code>, * respectively. * * @param hints The new <code>RenderingHints</code> to be set; * it may be <code>null</code>. */ public void setRenderingHints(RenderingHints hints) { if(equals(this.hints, hints)) { return; } RenderingHints oldHints = this.hints; this.hints = hints; fireEvent("RenderingHints", oldHints, hints); resetPropertyEnvironment(false); } /** * Adds a <code>PropertyGenerator</code> to the node. The property values * emitted by this property generator override any previous definitions. * * @param pg A <code>PropertyGenerator</code> to be added to the * associated node's property environment. * * @throws IllegalArgumentException if * <code>pg</code> is <code>null</code>. */ public void addPropertyGenerator(PropertyGenerator pg) { if(pg == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } localPropEnv.add(pg); if(propertySource != null) { propertySource.addPropertyGenerator(pg); } } /** * Forces a property to be copied from the specified source node. * By default, a property is copied from the first source node that * that emits it. The result of specifying an invalid source is * undefined. * * @param propertyName the name of the property to be copied. * @param sourceIndex the index of the source to copy the property from. * @throws IllegalArgumentException if propertyName is null. */ public void copyPropertyFromSource(String propertyName, int sourceIndex) { if(propertyName == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } localPropEnv.add(new CopyDirective(propertyName, sourceIndex)); if(propertySource != null) { propertySource.copyPropertyFromSource(propertyName, sourceIndex); } } /** * Removes a named property from the property environment of the * associated node. Unless the property is stored locally either due * to having been set explicitly or to having been cached for property * synchronization purposes, subsequent calls to * <code>getProperty(name)</code> will return * <code>java.awt.Image.UndefinedProperty</code>, and <code>name</code> * will not appear on the list of properties emitted by * <code>getPropertyNames()</code>. * * @param name A <code>String</code> naming the property to be suppressed. * * @throws IllegalArgumentException if * <code>name</code> is <code>null</code>. */ public void suppressProperty(String name) { if(name == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } localPropEnv.add(name); if(propertySource != null) { propertySource.suppressProperty(name); } } /** * Constructs and returns a <code>PropertySource</code> suitable for * use by the specified <code>OperationNode</code>. If the registry mode * identified by <code>getRegistryModeName()</code> supports properties, * i.e., the statement * <pre> * Registry.getMode(getRegistryModeName()).arePropertiesSupported() * </pre> * evaluates to <code>true</code>, then the <code>PropertySource</code> * will include the global property environment as managed by the * <code>OperationRegistry</code> for the corresponding operation. * Prior and subsequent modifications to the local property environment * made via this object will be reflected in the returned * <code>PropertySource</code>. * * @param opNode the <code>OperationNode</code> requesting its * <code>PropertySource</code>. * @param defaultPS a <code>PropertySource</code> to be used to derive * property values if and only if they would otherwise be * derived by inheritance from a source rather than from a * a <code>PropertyGenerator</code> or a copy-from-source * directive. * * @throws IllegalArgumentException if opNode is null. * * @return A <code>PropertySource</code> including the local and, if * applicable, the global property environment for the operation. * * @see RegistryMode * @see OperationRegistry#getPropertySource(OperationNode op) */ public PropertySource getPropertySource(OperationNode opNode, PropertySource defaultPS) { if ( opNode == null ) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } if(propertySource == null) { synchronized(this) { RegistryMode regMode = RegistryMode.getMode(registryModeName); if(regMode != null && regMode.arePropertiesSupported()) { // Get the global property environment. propertySource = (PropertyEnvironment)registry.getPropertySource(opNode); } else { // This mode does not support properties so we create // a default environment to permit property inheritance // from the sources. The PropertyGenerators, // copy-from-source directives, and suppressed properties // are null. propertySource = new PropertyEnvironment(pb != null ? pb.getSources() : null, null, null, null, opNode); } // Update from the local environment. updatePropertyEnvironment(propertySource); } } // Add the specified default source. propertySource.setDefaultPropertySource(defaultPS); return propertySource; } /** * Resets the property environment. The list of local property * environment modifications made directly on this object is reset * if and only if the parameter is <code>true</code>. * * @param resetLocalEnvironment Whether to clear the list of property * environment changes made directly on this object. */ public void resetPropertyEnvironment(boolean resetLocalEnvironment) { propertySource = null; if(resetLocalEnvironment) { localPropEnv.clear(); } } // Add items from local environment cache. private void updatePropertyEnvironment(PropertyEnvironment pe) { if(pe != null) { // "pe" should never null but check anyway. synchronized(this) { // Add items from the local environment. int size = localPropEnv.size(); for(int i = 0; i < size; i++) { Object element = localPropEnv.get(i); if(element instanceof String) { // suppressed property pe.suppressProperty((String)element); } else if(element instanceof CopyDirective) { CopyDirective cd = (CopyDirective)element; pe.copyPropertyFromSource(cd.getName(), cd.getIndex()); } else if(element instanceof PropertyGenerator) { pe.addPropertyGenerator((PropertyGenerator)element); } } } } } private void fireEvent(String propName, Object oldVal, Object newVal) { if(eventManager != null) { Object eventSource = eventManager.getPropertyChangeEventSource(); PropertyChangeEventJAI evt = new PropertyChangeEventJAI(eventSource, propName, oldVal, newVal); eventManager.firePropertyChange(evt); } } // Note that at present in RenderedOp and RenderableOp the only // non-serializable classes handled are RenderedImage, Raster, and // RenderingHints. How should this best be handled? Should an OpNode // be forced to implement for example // // void writePB(ParameterBlock pb, ObjectOutputStream out) // void ParameterBlock readPB(ObjectInputStream in) // // perhaps in a SerializableOperationNode? // Or does this require a more generic approach using Proxy? /** * Serializes the <code>OperationNodeSupport</code>. */ private void writeObject(ObjectOutputStream out) throws IOException { ParameterBlock pbClone = pb; boolean pbCloned = false; // Wrap RenderedImage sources in RenderedImageStates. for (int index = 0; index < pbClone.getNumSources(); index++) { Object source = pbClone.getSource(index); if (source != null && !(source instanceof Serializable)) { if (!pbCloned) { pbClone = (ParameterBlock)pb.clone(); pbCloned = true; } if (source instanceof RenderedImage) { SerializableState serializableImage = SerializerFactory.getState(source, null); pbClone.setSource(serializableImage, index); } else { throw new RuntimeException(source.getClass().getName() + JaiI18N.getString("OperationNodeSupport0")); } } } // Wrap RenderedImage parameters in RenderedImageState objects; // wrap Raster parameters in RasterState objects; // check other parameters for serializability. for (int index = 0; index < pbClone.getNumParameters(); index++) { Object parameter = pbClone.getObjectParameter(index); if (parameter != null && !(parameter instanceof Serializable)) { if (!pbCloned) { pbClone = (ParameterBlock)pb.clone(); pbCloned = true; } if (parameter instanceof Raster) { pbClone.set(SerializerFactory.getState(parameter, null), index); } else if (parameter instanceof RenderedImage) { RenderedImage ri = (RenderedImage)parameter; RenderingHints hints = new RenderingHints(null); hints.put(JAI.KEY_SERIALIZE_DEEP_COPY, new Boolean(true)); pbClone.set(SerializerFactory.getState(ri, hints), index); } else { throw new RuntimeException(parameter.getClass().getName() + JaiI18N.getString("OperationNodeSupport1")); } } } // Serialize the object. // Write non-static and non-transient fields. out.defaultWriteObject(); // Write ParameterBlock. out.writeObject(pbClone); // Write RenderingHints. out.writeObject(SerializerFactory.getState(hints, null)); } /** * Deserializes the <code>OperationNodeSupport</code>. */ private synchronized void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // Read non-static and non-transient fields. in.defaultReadObject(); // Read ParameterBlock. pb = (ParameterBlock)in.readObject(); // Read RenderingHints. SerializableState ss = (SerializableState)in.readObject(); hints = (RenderingHints)ss.getObject(); // Wrap any RenderedImageState sources in PlanarImage objects. for (int index = 0; index < pb.getNumSources(); index++) { Object source = pb.getSource(index); if (source instanceof SerializableState) { ss = (SerializableState)source; PlanarImage pi = PlanarImage.wrapRenderedImage((RenderedImage)ss.getObject()); pb.setSource(pi, index); } } // Extract Raster and PlanarImage parameters from RasterState and // RenderedImageState wrappers, respectively. for (int index = 0; index < pb.getNumParameters(); index++) { Object parameter = pb.getObjectParameter(index); if (parameter instanceof SerializableState) { Object object = ((SerializableState)parameter).getObject(); if (object instanceof Raster) pb.set(object, index); else if (object instanceof RenderedImage) pb.set(PlanarImage.wrapRenderedImage((RenderedImage)object), index); else pb.set(object, index); } } registry = JAI.getDefaultInstance().getOperationRegistry(); } }
/** * MIT License * * Copyright (c) 2017-2018 nuls.io * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.nuls.core.h2.utils; import java.util.ArrayList; import java.util.List; /** * dao查询接口,封装查询语句工具类 * @author zoro * */ public class Searchable { /** * 查询连接符,如:= != like */ private List<Condition> operators; public Searchable() { operators = new ArrayList<Condition>(); } public Searchable(List<Condition> operators) { this.operators = operators; } /** * 添加查询条件 * @param c */ public void addCondition(Condition c) { this.operators.add(c); } public void addCondition(String key , SearchOperator operator, Object value) { this.addCondition(new Condition(key,operator,value)); } /** * 根据key删除某个条件 * @param key */ public void removeCondition(String key) { Condition c = null; for(int i=0; i<operators.size(); i++) { c = operators.get(i); if(c.getKey().equals(key)) { operators.remove(i); break; } } } /** * 根据key获取一个Condition * @param key * @return */ public Condition getCondition(String key) { Condition c = null; for(int i=0; i<operators.size(); i++) { c = operators.get(i); if(c.getKey().equals(key)) { return c; } } return null; } public void removeAll() { operators = new ArrayList<Condition>(); } public List<Condition> getOperators() { return operators; } public void setOperators(List<Condition> operators) { this.operators = operators; } }
package me.saket.dank.ui.preferences; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import androidx.annotation.StringRes; import me.saket.dank.R; import me.saket.dank.ui.webview.ChromeCustomTabsForwardingActivity; import me.saket.dank.ui.webview.WebViewActivity; import me.saket.dank.utils.Intents; public enum DefaultWebBrowser { DANK_INTERNAL_BROWSER(R.string.userprefs_externallinks_internal_browser) { @Override public Intent intentForUrl(Context context, String url, Rect expandFromRect) { return WebViewActivity.intent(context, url, expandFromRect); } }, CHROME_CUSTOM_TABS(R.string.userprefs_externallinks_chrome_custom_tabs) { @Override public Intent intentForUrl(Context context, String url, Rect expandFromRect) { return ChromeCustomTabsForwardingActivity.intent(context, url); } }, DEVICE_DEFAULT(R.string.userprefs_externallinks_default_web_browser) { @Override public Intent intentForUrl(Context context, String url, Rect expandFromRect) { return Intents.createForOpeningUrl(url); } }; @StringRes public final int displayName; DefaultWebBrowser(@StringRes int displayName) { this.displayName = displayName; } public Intent intentForUrl(Context context, String url, Rect expandFromRect) { throw new AbstractMethodError(); } }
/* * Copyright 2016 IKS Gesellschaft fuer Informations- und Kommunikationssysteme mbH * * 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. */ /** * All classes that make a connection do its job are located in this package. */ package com.iksgmbh.sql.pojomemodb.connection;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.dimm.vsm.mail; import de.dimm.vsm.Utilities.VariableResolver; import de.dimm.vsm.fsengine.GenericEntityManager; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; /** * * @author Administrator */ public abstract class NotificationServer { final HashMap<String, Notification> notificationMap; final List<NotificationEntry> notificationEntries; public NotificationServer() { notificationMap = new HashMap<String, Notification>(); notificationEntries = new ArrayList<NotificationEntry>(); } protected NotificationEntry getNotificationEntry(String key) { for (int i = 0; i < notificationEntries.size(); i++) { NotificationEntry notificationEntry = notificationEntries.get(i); if (notificationEntry.getKey().equals(key)) return notificationEntry; } return null; } protected boolean existsNotification( Notification no ) { return notificationMap.containsKey(no.getKey()); } protected void addNotification(Notification no) { notificationMap.put( no.getKey(), no); } protected void removeNotification(Notification no) { notificationMap.remove( no.getKey()); } protected void clear() { notificationMap.clear(); } public void fire( String key, String extraText, VariableResolver vr ) { // FIRE ALL MATCHING NOTIFICATIONS (COULD BE MORE THE SAME NOTIFICATIONENTRY WITH DIFFERENT GROUPS) synchronized(notificationMap) { Collection<Notification> collno = notificationMap.values(); for (Notification no : collno) { if (no.getEntry().getKey().equals(key)) { no.fire(extraText, vr); } } } } public void release( String key ) { synchronized(notificationMap) { Collection<Notification> collno = notificationMap.values(); for (Notification no : collno) { if (no.getEntry().getKey().equals(key)) { no.release(); } } } } public abstract void loadNotifications(GenericEntityManager em) throws IOException; public void addNotificationEntry( NotificationEntry e ) { if (!notificationEntries.contains(e)) { notificationEntries.add(e); } } public List<NotificationEntry> listNotificationEntries() { return notificationEntries; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.fontys.prj2.group99.myprojectname.services; import nl.fontys.prj2.group99.myprojectname.dataservices.DAOlite; import nl.fontys.prj2.group99.myprojectname.dataservices.PostgresDAOlite; import nl.fontys.prj2.group99.myprojectname.model.SimplePresident; import java.util.ArrayList; import java.util.List; /** * The type President service. */ public class PresidentService { private DAOlite<SimplePresident> db = new PostgresDAOlite("localhost"); /** * Gets president by id. * * @param id the id of the president * @return the president by id */ public SimplePresident getPresidentById(Integer id) { // get presidents from the real database! Note, no null check! SimplePresident president = db.get(id); return president; } /** * Gets all presidents. This is now "hardcoded" and without the database! * Think of how to change it for your purpose. * * @return the all presidents */ public List<SimplePresident> getAllPresidents() { // usage without database SimplePresident p1 = new SimplePresident("Superman", 1900); SimplePresident p2 = new SimplePresident("Spiderman", 1988); List<SimplePresident> presidents = new ArrayList<>(); presidents.add(p1); presidents.add(p2); return presidents; } }
package cgeo.geocaching.maps.mapsforge.v6.caches; import cgeo.geocaching.enumerations.CoordinatesType; import cgeo.geocaching.utils.TextUtils; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import java.util.Comparator; import org.apache.commons.lang3.StringUtils; public class GeoitemRef implements Parcelable { public static final Comparator<? super GeoitemRef> NAME_COMPARATOR = (Comparator<GeoitemRef>) (left, right) -> TextUtils.COLLATOR.compare(left.getName(), right.getName()); private final String itemCode; private final CoordinatesType type; private final String geocode; private final int id; private final String name; private final int markerId; public GeoitemRef(final String itemCode, final CoordinatesType type, final String geocode, final int id, final String name, final int markerId) { this.itemCode = itemCode; this.type = type; this.geocode = geocode; this.id = id; this.name = name; this.markerId = markerId; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof GeoitemRef)) { return false; } return StringUtils.equalsIgnoreCase(this.itemCode, ((GeoitemRef) o).itemCode); } @Override public int hashCode() { return StringUtils.defaultString(itemCode).hashCode(); } @Override @NonNull public String toString() { if (StringUtils.isEmpty(name)) { return itemCode; } return String.format("%s: %s", itemCode, name); } public String getItemCode() { return itemCode; } public CoordinatesType getType() { return type; } public String getGeocode() { return geocode; } public int getId() { return id; } public String getName() { return name; } public int getMarkerId() { return markerId; } // Parcelable functions public static final Parcelable.Creator<GeoitemRef> CREATOR = new Parcelable.Creator<GeoitemRef>() { @Override public GeoitemRef createFromParcel(final Parcel in) { final String itemCode = in.readString(); final CoordinatesType type = CoordinatesType.values()[in.readInt()]; final String geocode = in.readString(); final int id = in.readInt(); final String name = in.readString(); final int markerId = in.readInt(); return new GeoitemRef(itemCode, type, geocode, id, name, markerId); } @Override public GeoitemRef[] newArray(final int size) { return new GeoitemRef[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel parcel, final int flags) { parcel.writeString(itemCode); parcel.writeInt(type.ordinal()); parcel.writeString(geocode); parcel.writeInt(id); parcel.writeString(name); parcel.writeInt(markerId); } }
package com.turndapage.wear.watchface.watchfacedarko.fragment; import android.app.Activity; import android.app.Fragment; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.wear.widget.SwipeDismissFrameLayout; import android.support.wearable.complications.ComplicationHelperActivity; import android.support.wearable.complications.ComplicationProviderInfo; import android.support.wearable.complications.ProviderChooserIntent; import android.support.wearable.complications.ProviderInfoRetriever; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import com.turndapage.wear.watchface.watchfacedarko.R; import com.turndapage.wear.watchface.watchfacedarko.model.WatchFaceComplication; import com.turndapage.wear.watchface.watchfacedarko.service.AbstractKotlinWatchFace; import net.vrallev.android.cat.Cat; import java.util.concurrent.Executors; import static android.app.Activity.RESULT_OK; public class ComplicationSelectionFragment extends Fragment implements View.OnClickListener { private ComplicationSelectionFragment complicationSelectionFragment; private SwipeDismissFrameLayout swipeDismissFrameLayout; private ImageButton complication1Icon; private ImageButton complication2Icon; private ImageButton complication3Icon; private int complication1Id; private int complication2Id; private int complication3Id; // Selected complication id by user. private int mSelectedComplicationId; // ComponentName associated with watch face service (service that renders watch face). Used // to retrieve complication information. private ComponentName mWatchFaceComponentName; private AbstractKotlinWatchFace abstractKotlinWatchFace; public static final int COMPLICATION_CONFIG_REQUEST_CODE = 1001; // Required to retrieve complication data from watch face for preview. private ProviderInfoRetriever mProviderInfoRetriever; public enum ComplicationLocation { COMPLICATION1, COMPLICATION2, COMPLICATION3 } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.complication_selection, container, false); complication1Id = 101; complication2Id = 102; complication3Id = 103; swipeDismissFrameLayout = view.findViewById(R.id.swipe_dismiss); complicationSelectionFragment = this; swipeDismissFrameLayout.addCallback(new SwipeDismissFrameLayout.Callback() { @Override public void onDismissed(SwipeDismissFrameLayout layout) { dismissThis(); } }); complication1Icon = view.findViewById(R.id.complication1Icon); complication2Icon = view.findViewById(R.id.complication2Icon); complication3Icon = view.findViewById(R.id.complication3Icon); complication1Icon.setOnClickListener(this); complication2Icon.setOnClickListener(this); complication3Icon.setOnClickListener(this); final ImageView complication1 = view.findViewById(R.id.complication1); final ImageView complication2 = view.findViewById(R.id.complication2); final ImageView complication3 = view.findViewById(R.id.complication3); final ImageView background = view.findViewById(R.id.preview); background.post(new Runnable() { @Override public void run() { float width = background.getMeasuredWidth(); updateComplicationPositions(complication1, complication1Icon, width, abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceComplication1()); updateComplicationPositions(complication2, complication2Icon, width, abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceComplication2()); updateComplicationPositions(complication3, complication3Icon, width, abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceComplication3()); } }); background.setImageResource(abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceBackgroundImage().getBackgroundImageResource()); mProviderInfoRetriever = new ProviderInfoRetriever(getContext(), Executors.newCachedThreadPool()); mProviderInfoRetriever.init(); final int[] complicationIds = { complication1Id, complication2Id, complication3Id }; mProviderInfoRetriever.retrieveProviderInfo(new ProviderInfoRetriever.OnProviderInfoReceivedCallback() { @Override public void onProviderInfoReceived(int watchFaceComplicationId, @Nullable ComplicationProviderInfo info) { updateComplicationViews(watchFaceComplicationId, info); } },mWatchFaceComponentName, complicationIds ); return view; } private void updateComplicationPositions(ImageView imageView, ImageButton imageButton, float width, WatchFaceComplication watchFaceComplication) { float complicationRadius = (imageView.getMeasuredWidth() / 2); float leftMargin1 = (watchFaceComplication.getXPos() * width) - complicationRadius; float topMargin1 = (watchFaceComplication.getYPos() * width) - complicationRadius; RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int)(complicationRadius * 2), (int)(complicationRadius * 2)); params1.leftMargin = (int)leftMargin1; params1.topMargin = (int)topMargin1; Cat.d("Width: " + width + " Radius: " + complicationRadius + " leftMargin: " + leftMargin1 + " topMargin: " + topMargin1); imageView.setLayoutParams(params1); imageButton.setLayoutParams(params1); } public void setComponentName(ComponentName componentName) { mWatchFaceComponentName = componentName; try { abstractKotlinWatchFace = (AbstractKotlinWatchFace)Class.forName(componentName.getClassName()).newInstance(); }catch (ClassNotFoundException | IllegalAccessException | java.lang.InstantiationException ex) { ex.printStackTrace(); dismissThis(); } } @Override public void onClick(View view) { //Cat.d("Clicked Complication"); if(view.equals(complication1Icon)) { launchComplicationHelperActivity(getActivity(), ComplicationLocation.COMPLICATION1); } else if(view.equals(complication2Icon)) { launchComplicationHelperActivity(getActivity(), ComplicationLocation.COMPLICATION2); } else if(view.equals(complication3Icon)) { launchComplicationHelperActivity(getActivity(), ComplicationLocation.COMPLICATION3); } } // Verifies the watch face supports the complication location, then launches the helper // class, so user can choose their complication data provider. private void launchComplicationHelperActivity( Activity currentActivity, ComplicationLocation complicationLocation) { int[] supportedTypes = new int[]{}; switch (complicationLocation) { case COMPLICATION1: mSelectedComplicationId = 101; supportedTypes = abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceComplication1().getSupportedTypes(); break; case COMPLICATION2: mSelectedComplicationId = 102; supportedTypes = abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceComplication2().getSupportedTypes(); break; case COMPLICATION3: mSelectedComplicationId = 103; supportedTypes = abstractKotlinWatchFace.getWatchFaceStyle().getWatchFaceComplication3().getSupportedTypes(); break; } startActivityForResult( ComplicationHelperActivity.createProviderChooserHelperIntent( currentActivity, mWatchFaceComponentName, mSelectedComplicationId, supportedTypes), COMPLICATION_CONFIG_REQUEST_CODE); Cat.d("Launched Activity"); } public void updateComplicationViews( int watchFaceComplicationId, ComplicationProviderInfo complicationProviderInfo) { Cat.d("updateComplicationViews(): id: " + watchFaceComplicationId); Cat.d("\tinfo: " + complicationProviderInfo); if (watchFaceComplicationId == complication1Id) { if (complicationProviderInfo != null) { complication1Icon.setImageIcon(complicationProviderInfo.providerIcon); } else { complication1Icon.setImageResource(R.drawable.add); } } else if (watchFaceComplicationId == complication2Id) { if (complicationProviderInfo != null) { complication2Icon.setImageIcon(complicationProviderInfo.providerIcon); } else { complication2Icon.setImageResource(R.drawable.add); } } else if (watchFaceComplicationId == complication3Id) { if(complicationProviderInfo != null) { complication3Icon.setImageIcon(complicationProviderInfo.providerIcon); } else { complication3Icon.setImageResource(R.drawable.add); } } } public void updateSelectedComplication(ComplicationProviderInfo complicationProviderInfo) { // Checks if id is valid. if (mSelectedComplicationId >= 0) { updateComplicationViews(mSelectedComplicationId, complicationProviderInfo); } } public void dismissThis() { swipeDismissFrameLayout.setVisibility(View.GONE); getActivity().getFragmentManager().beginTransaction().remove(complicationSelectionFragment) .commitAllowingStateLoss(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Cat.d("Got result"); if (requestCode == COMPLICATION_CONFIG_REQUEST_CODE && resultCode == RESULT_OK) { ComplicationProviderInfo complicationProviderInfo = data.getParcelableExtra(ProviderChooserIntent.EXTRA_PROVIDER_INFO); Cat.d("Provider: " + complicationProviderInfo); updateSelectedComplication(complicationProviderInfo); } } @Override public void onDestroy() { super.onDestroy(); mProviderInfoRetriever.release(); } }
package com.peralex.utilities.ui.table; import java.awt.Component; import java.awt.Dimension; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; /** * A collection of few useful functions for JTable * * @author David Lee * @author Noel Grandin */ public class TableLib { /** not meant to be instantiated */ private TableLib() { } /** * Set the visible no of rows for a JTable (i.e. the number of rows before it starts scrolling). This is very useful * to prevent tables in JScrollPanes from demanding excessive amounts of vertical space. * * Note: Kudos to Santhosh Kumar for this method. */ public static void setVisibleRowCount(JTable table, int rows) { int height = 0; for (int row = 0; row < rows; row++) { height += table.getRowHeight(row); } table.setPreferredScrollableViewportSize(new Dimension(table .getPreferredScrollableViewportSize().width, height)); } /** * @see #resizeColumnToFitContent(javax.swing.JTable, int[], int) */ public static void resizeColumnToFitContent(final JTable table, final int padding) { resizeColumnToFitContent(table, null, padding); } public static void disableAllTypesOfSelection(JTable oTable) { oTable.setRowSelectionAllowed(false); oTable.setColumnSelectionAllowed(false); oTable.setCellSelectionEnabled(false); } public static void setRowHeight(JTable table, double ratioRelativeToCurrentFont) { final int newHeight = (int) (table.getFontMetrics(table.getFont()).getHeight() * ratioRelativeToCurrentFont); table.setRowHeight(newHeight); } public static void configurePreferredScrollableViewportSize(JTable table, int visibleRowCount) { table.setPreferredScrollableViewportSize(getPreferredScrollableViewportSize(table, visibleRowCount)); } public static Dimension getPreferredScrollableViewportSize(JTable table, int visibleRowCount) { final int width = table.getPreferredSize().width; final int height = table.getFontMetrics(table.getFont()).getHeight(); final Dimension minimalSize = new Dimension(width, height * visibleRowCount); return minimalSize; } /** * lock the width of a column by setting the min, max, and preferred sizes */ public static void lockColumnWidth(JTable oUnitsTable, int columnIdx, int width_px) { oUnitsTable.getColumnModel().getColumn(columnIdx).setPreferredWidth(width_px); oUnitsTable.getColumnModel().getColumn(columnIdx).setMinWidth(width_px); oUnitsTable.getColumnModel().getColumn(columnIdx).setMaxWidth(width_px); } /** * This will resize the columns to fit their content. If the width is potentially too wide, you can limit it by * specified the preferred max width for that column. * * Remember to call setAutoResizeMode( JTable.AUTO_RESIZE_OFF ) on the JTable object, otherwise the adjusted width * will be overriden. * * @param table * @param preferredMaxWidth If this is null, it will use the width calculated from the content. * @param padding extra space for each column, if desired */ public static void resizeColumnToFitContent(JTable table, int[] preferredMaxWidth, int padding) { final TableColumnModel columns = table.getColumnModel(); final int[] maxColumnWidth = TableWidthFinder.computeMaxColumnWidth(table); for (int i = 0; i < maxColumnWidth.length; i++) { final int preferredWidth = preferredMaxWidth == null ? Integer.MAX_VALUE : preferredMaxWidth[i]; final int maxContentWidth = maxColumnWidth[i] + padding; columns.getColumn(i).setPreferredWidth(Math.min(maxContentWidth, preferredWidth)); } } private static class TableWidthFinder { public static int[] computeMaxColumnWidth(JTable table) { final int[] headerWidth = getHeaderWidth(table); return updateMaxWidthTable(table, headerWidth); } private static int[] getHeaderWidth(JTable table) { TableCellRenderer defaultHeaderRenderer = table.getTableHeader().getDefaultRenderer(); final TableColumnModel columns = table.getColumnModel(); final int columnCount = columns.getColumnCount(); final int[] headerWidth = new int[columnCount]; for (int columnId = 0; columnId < columnCount; columnId++) { TableColumn column = columns.getColumn(columnId); final Object value = column.getHeaderValue(); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = defaultHeaderRenderer; } Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, columnId); headerWidth[columnId] = (int) c.getPreferredSize().getWidth(); } return headerWidth; } private static int[] updateMaxWidthTable(JTable table, int[] colWidth) { TableModel data = table.getModel(); for (int row = 0; row < data.getRowCount(); row++) { updateMaxWidthTable(table, data, row, colWidth); } return colWidth; } private static void updateMaxWidthTable(JTable table, TableModel data, int row, int[] colWidth) { for (int col = 0; col < data.getColumnCount(); col++) { final TableCellRenderer cellRenderer = table.getCellRenderer(row, col); final Component c = table.prepareRenderer(cellRenderer, row, col); colWidth[col] = Math.max(colWidth[col], c.getPreferredSize().width); } } } }
package org.heimdall.shield_library.utility; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class SystemUtil { private static Logger logger = LoggerFactory.getLogger(SystemUtil.class); public static boolean isWindows() { return System.getProperty("os.name").toLowerCase().startsWith("windows"); } /** * 获取进程的标识符 * @return 进程标识符 */ public static Long processIdentity() { String name = ManagementFactory.getRuntimeMXBean().getName(); return Long.valueOf(name.split("@")[0]); } /** * 获取可执行程序所在的目录 * 参考:https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file * * @return 可执行程序所在目录 * @throws Exception */ public static String binaryDirectory(Class clazz) throws Exception { boolean isWindows = SystemUtil.isWindows(); String location = clazz.getProtectionDomain().getCodeSource().getLocation().toString(); if(location.startsWith("file:/")) { location = isWindows ? location.substring(6) : location.substring(5); } if(location.startsWith("jar:file:/")) { location = isWindows ? location.substring(10) : location.substring(9); } if (location.contains(".jar")) { Integer idx = location.lastIndexOf(".jar"); location = location.substring(0, idx + 4); location = new File(location).getParent(); } else { //location = location.replaceAll("/classes", ""); } if (!location.endsWith("/")) { location = location + "/"; } return URLDecoder.decode(location, "UTF-8"); } public static List<String> listFile(File fileObj, String pattern) throws Exception { if (!fileObj.isDirectory()) { throw new Exception("非法参数,必须传入文件夹路径"); } File[] fileArray = fileObj.listFiles(); List<String> resultList = new ArrayList<>(); for (File fileItem : fileArray) { if (fileItem.isFile() && fileItem.getAbsolutePath().contains(pattern)) { resultList.add(fileItem.getAbsolutePath()); } else if (fileItem.isDirectory()) { resultList.addAll(listFile(fileItem, pattern)); } } return resultList; } /** * 参考AOSP的做法,使Java虚拟机立即垃圾回收 */ public static void manualFullGC() throws Exception { Runtime.getRuntime().gc(); Thread.sleep(500L); Runtime.getRuntime().runFinalization(); } /** * 运行系统命令及Shell脚本 */ public static String runCommand(String content, ProcessBuilder processBuilder) throws Exception { if(StringUtils.isBlank(content)) { throw new Exception("运行内容不可为空"); } if(processBuilder == null) { processBuilder = new ProcessBuilder(); } boolean isWindows = SystemUtil.isWindows(); List<String> commandList = new ArrayList<String>(); if(isWindows) { commandList.add("cmd.exe"); commandList.add("/c"); commandList.add("\"" + content + "\""); processBuilder.command(commandList); } else { commandList.add("bash"); commandList.add("-c"); commandList.add(content); Integer arraySize = commandList.size(); String[] commandArray = new String[arraySize]; processBuilder.command(commandList.toArray(commandArray)); } Process process = processBuilder.start(); String scriptResult = ""; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), isWindows ? "GBK" : "UTF-8")); while((scriptResult = bufferedReader.readLine()) != null) { stringBuilder.append(scriptResult); stringBuilder.append(System.lineSeparator()); } Integer exitCode = process.waitFor(); scriptResult = stringBuilder.toString(); scriptResult = StringUtils.chomp(scriptResult); if(exitCode.equals(0)) { logger.info("系统命令[" + content + "]运行成功,执行结果:" + scriptResult); } else { logger.error("系统命令[" + content + "]运行出错,出错详情:" + exitCode); } return scriptResult; } /** * 获取主板序列号,用于唯一标识主机 * 使用主板的 SMBIOS UUID,是微软官方和很多授权方式比较推荐的做法 * 此序列号不会因重装系统而改变,且 Linux、Windows 下获取到的值一致 * 参考:https://bbs.csdn.net/topics/392161316 * 参考:https://blog.csdn.net/weixin_43586563/article/details/109765086 * 参考:https://stackoverflow.com/questions/10152762/best-way-to-get-machine-id-on-linux# * * @return * @throws Exception */ public static String systemUUID() throws Exception { String systemUUID = ""; try { if(isWindows()) { String lineSeparator = System.lineSeparator(); ProcessBuilder processBuilder = new ProcessBuilder(); String[] lineArray = runCommand("wmic csproduct get UUID", processBuilder).split(lineSeparator); systemUUID = lineArray.length >= 2 ? StringUtils.trim(lineArray[1]) : ""; } else { byte[] plainBytes = Files.readAllBytes(Paths.get("/sys/class/dmi/id/product_uuid")); systemUUID = StringUtils.trim(new String(plainBytes, StandardCharsets.UTF_8)); } } catch (Exception exception) { logger.error("获取主板UUID出错,详情:" + exception.toString()); throw exception; } return StringUtils.upperCase(systemUUID); } /** * 根据在线网站,获取本机的出口IP */ public static String publicAddress() throws Exception { ProcessBuilder processBuilder = new ProcessBuilder(); return runCommand("curl http://ip.cip.cc/", processBuilder); } }
/* * (c) 2016-2021 Swirlds, Inc. * * This software is owned by Swirlds, Inc., which retains title to the software. This software is protected by various * intellectual property laws throughout the world, including copyright and patent laws. This software is licensed and * not sold. You must use this software only in accordance with the terms of the Hashgraph Open Review license at * * https://github.com/hashgraph/swirlds-open-review/raw/master/LICENSE.md * * SWIRLDS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THIS SOFTWARE, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * OR NON-INFRINGEMENT. */ package com.swirlds.platform; import com.swirlds.common.CommonUtils; import javax.swing.JPanel; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Maintain all the metadata about the state hierarchy, which has 4 levels: (app, swirld, member, state). * This includes the list of every app installed locally. For each app, it includes the list of all known * swirlds running on it. For each swirld, it maintains the list of all known members stored locally. For * each member it maintains the list of all states stored locally. Each app, swirld, member, and state also * stores its name, and its parent in the hierarchy. */ class StateHierarchy { /** list of the known apps, each of which may have some members, swirlds, and states */ List<InfoApp> apps = new ArrayList<>(); /** * Create the state hierarchy, by finding all .jar files in data/apps/ and also adding in a virtual one * named fromAppName if that parameter is non-null. * * @param fromAppName * the name of the virtual data/apps/*.jar file, or null if none. * @param fromAppMain * the class of the virtual SwirldMain, or null if none. */ public StateHierarchy(final String fromAppName, final Class<?> fromAppMain) { final File appsDirPath = CommonUtils.canonicalFile("data", "apps"); final File[] appFiles = appsDirPath .listFiles((dir, name) -> name.endsWith(".jar")); final List<String> names = new ArrayList<>(); if (fromAppName != null) { // if there's a virtual jar, list it first names.add(fromAppName); final File[] toDelete = appsDirPath .listFiles((dir, name) -> name.equals(fromAppName)); if (toDelete != null) { for (File file : toDelete) { file.delete(); // deletes if the virtual file also really exists. Else does nothing. } } } if (appFiles != null) { for (File app : appFiles) { names.add(getMainClass(app.getAbsolutePath())); } } names.sort(null); for (String name : names) { name = name.substring(0, name.length() - 4); apps.add(new InfoApp(name)); } } private static String getMainClass(final String appJarPath) { String mainClassname; try (final JarFile jarFile = new JarFile(appJarPath)) { final Manifest manifest = jarFile.getManifest(); final Attributes attributes = manifest .getMainAttributes(); mainClassname = attributes.getValue("Main-Class"); return mainClassname; } catch (Exception ex) { CommonUtils.tellUserConsolePopup("ERROR", "ERROR: Couldn't load app " + appJarPath); return null; } } /** * Get the InfoApp for an app stored locally, given the name of the jar file (without the ".jar"). * * @param name * name the jar file, without the ".jar" at the end * @return the InfoApp for that app */ InfoApp getInfoApp(String name) { for (InfoApp app : apps) { if (name.equals(app.name)) { return app; } } return null; } /** * The class that all 4 levels of the hierarchy inherit from: InfoApp, InfoSwirld, InfoMember, * InfoState. This holds information common to all of them, such as the name, and the GUI component that * represents it in the browser window. */ static class InfoEntity { /** name of this entity */ String name; /** the JPanel that shows this entity in the browser window (Swirlds tab), or null if none */ JPanel panel; } /** * Metadata about an app that is installed locally. */ static class InfoApp extends InfoEntity { List<InfoSwirld> swirlds = new ArrayList<InfoSwirld>(); // children public InfoApp(String name) { this.name = name; } } /** * Metadata about a swirld running on an app. */ static class InfoSwirld extends InfoEntity { InfoApp app; // parent List<InfoMember> members = new ArrayList<InfoMember>(); // children Reference swirldId; public InfoSwirld(InfoApp app, byte[] swirldIdBytes) { this.app = app; this.swirldId = new Reference(swirldIdBytes); name = "Swirld " + swirldId.to62Prefix(); app.swirlds.add(this); } } /** * Metadata about a member in a swirld running on an app. */ static class InfoMember extends InfoEntity { InfoSwirld swirld; // parent List<InfoState> states = new ArrayList<InfoState>(); // children long memberId; AbstractPlatform platform; public InfoMember(InfoSwirld swirld, long memberId, AbstractPlatform platform) { this.swirld = swirld; this.memberId = memberId; this.platform = platform; this.name = platform.getAddress().getNickname() + " - "// + platform.getAddress().getSelfName(); swirld.members.add(this); } } /** * Metadata about a state stored by a member in a swirld running on an app. */ static class InfoState extends InfoEntity { InfoMember member; public InfoState(InfoMember member, String name) { this.member = member; this.name = name; member.states.add(this); } } }
/* * Copyright (c) 2018 by Gerrit Grunwald * * 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 eu.hansolo.fx.charts.data; import eu.hansolo.fx.charts.Symbol; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.LongProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleLongProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.paint.Color; import java.time.Instant; import java.time.ZonedDateTime; import java.util.HashMap; public class ChartItemBuilder<B extends ChartItemBuilder<B>> { private HashMap<String, Property> properties = new HashMap<>(); // ******************** Constructors ************************************** protected ChartItemBuilder() {} // ******************** Methods ******************************************* public static final ChartItemBuilder create() { return new ChartItemBuilder(); } public final B index(final int INDEX) { properties.put("index", new SimpleIntegerProperty(INDEX)); return (B)this; } public final B name(final String NAME) { properties.put("name", new SimpleStringProperty(NAME)); return (B)this; } public final B unit(final String UNIT) { properties.put("unit", new SimpleStringProperty(UNIT)); return (B)this; } public final B description(final String DESCRIPTION) { properties.put("description", new SimpleStringProperty(DESCRIPTION)); return (B)this; } public final B value(final double VALUE) { properties.put("value", new SimpleDoubleProperty(VALUE)); return (B)this; } public final B fill(final Color COLOR) { properties.put("fill", new SimpleObjectProperty(COLOR)); return (B)this; } public final B stroke(final Color COLOR) { properties.put("stroke", new SimpleObjectProperty(COLOR)); return (B)this; } public final B textFill(final Color COLOR) { properties.put("textFill", new SimpleObjectProperty(COLOR)); return (B)this; } public final B timestamp(final ZonedDateTime DATE_TIME) { properties.put("timestampDateTime", new SimpleObjectProperty<>(DATE_TIME)); return (B)this; } public final B timestamp(final Instant TIMESTAMP) { properties.put("timestamp", new SimpleObjectProperty<>(TIMESTAMP)); return (B)this; } public final B symbol(final Symbol SYMBOL) { properties.put("symbol", new SimpleObjectProperty<>(SYMBOL)); return (B)this; } public final B animated(final boolean AUTO) { properties.put("animated", new SimpleBooleanProperty(AUTO)); return (B)this; } public final B x(final double X) { properties.put("x", new SimpleDoubleProperty(X)); return (B)this; } public final B y(final double Y) { properties.put("y", new SimpleDoubleProperty(Y)); return (B)this; } public final B isEmpty() { properties.put("isEmpty", new SimpleBooleanProperty(true)); return (B)this; } public final B animationDuration(final long DURATION) { properties.put("animationDuration", new SimpleLongProperty(DURATION)); return (B)this; } public final ChartItem build() { final ChartItem ITEM = new ChartItem(); for (String key : properties.keySet()) { if ("index".equals(key)) { ITEM.setIndex(((IntegerProperty) properties.get(key)).get()); } else if ("name".equals(key)) { ITEM.setName(((StringProperty) properties.get(key)).get()); } else if ("value".equals(key)) { ITEM.setValue(((DoubleProperty) properties.get(key)).get()); } else if ("unit".equals(key)) { ITEM.setUnit(((StringProperty) properties.get(key)).get()); } else if ("description".equals(key)) { ITEM.setDescription(((StringProperty) properties.get(key)).get()); } else if("fill".equals(key)) { ITEM.setFill(((ObjectProperty<Color>) properties.get(key)).get()); } else if("stroke".equals(key)) { ITEM.setStroke(((ObjectProperty<Color>) properties.get(key)).get()); } else if("textFill".equals(key)) { ITEM.setTextFill(((ObjectProperty<Color>) properties.get(key)).get()); } else if("timestamp".equals(key)) { ITEM.setTimestamp(((ObjectProperty<Instant>) properties.get(key)).get()); } else if ("timestampDateTime".equals(key)) { ITEM.setTimestamp(((ObjectProperty<ZonedDateTime>) properties.get(key)).get()); } else if("symbol".equals(key)) { ITEM.setSymbol(((ObjectProperty<Symbol>) properties.get(key)).get()); } else if("animated".equals(key)) { ITEM.setAnimated(((BooleanProperty) properties.get(key)).get()); } else if("animationDuration".equals(key)) { ITEM.setAnimationDuration(((LongProperty) properties.get(key)).get()); } else if ("x".equals(key)) { ITEM.setX(((DoubleProperty) properties.get(key)).get()); } else if ("y".equals(key)) { ITEM.setY(((DoubleProperty) properties.get(key)).get()); } else if ("isEmpty".equals(key)) { ITEM.setIsEmpty(((BooleanProperty) properties.get(key)).get()); } } return ITEM; } }
/* * Copyright 2015-2020 OpenCB * * 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.opencb.opencga.master.monitor.daemons; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.opencga.analysis.variant.operations.VariantAnnotationIndexOperationTool; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.AbstractManagerTest; import org.opencb.opencga.catalog.utils.ParamUtils; import org.opencb.opencga.core.api.ParamConstants; import org.opencb.opencga.core.common.JacksonUtils; import org.opencb.opencga.core.common.TimeUtils; import org.opencb.opencga.core.models.common.Enums; import org.opencb.opencga.core.models.file.FileContent; import org.opencb.opencga.core.models.job.Job; import org.opencb.opencga.core.models.job.JobInternal; import org.opencb.opencga.core.models.job.JobInternalWebhook; import org.opencb.opencga.core.models.study.GroupUpdateParams; import org.opencb.opencga.core.models.study.StudyNotification; import org.opencb.opencga.core.models.study.StudyUpdateParams; import org.opencb.opencga.core.response.OpenCGAResult; import org.opencb.opencga.core.tools.result.ExecutionResult; import org.opencb.opencga.core.tools.result.ExecutionResultManager; import org.opencb.opencga.core.tools.result.Status; import org.opencb.opencga.master.monitor.executors.BatchExecutor; import org.opencb.opencga.master.monitor.models.PrivateJobUpdateParams; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ExecutionDaemonTest extends AbstractManagerTest { private ExecutionDaemon daemon; private DummyBatchExecutor executor; @Override @Before public void setUp() throws IOException, CatalogException { super.setUp(); String expiringToken = this.catalogManager.getUserManager().loginAsAdmin("admin").getToken(); String nonExpiringToken = this.catalogManager.getUserManager().getNonExpiringToken("opencga", expiringToken); catalogManager.getConfiguration().getAnalysis().getIndex().getVariant().setMaxConcurrentJobs(1); daemon = new ExecutionDaemon(1000, nonExpiringToken, catalogManager, "/tmp"); executor = new DummyBatchExecutor(); daemon.batchExecutor = executor; } @Test public void testBuildCli() { Map<String, Object> params = new LinkedHashMap<>(); params.put("key", "value"); params.put("camelCaseKey", "value"); params.put("flag", ""); params.put("boolean", "true"); params.put("outdir", "/tmp/folder"); params.put("paramWithSpaces", "This could be a description"); params.put("paramWithSingleQuotes", "This could 'be' a description"); params.put("paramWithDoubleQuotes", "This could \"be\" a description"); Map<String, String> dynamic = new LinkedHashMap<>(); dynamic.put("dynamic", "It's true"); dynamic.put("param with spaces", "Fuc*!"); params.put("other", dynamic); String cli = ExecutionDaemon.buildCli("opencga-internal.sh", "variant-index", params); assertEquals("opencga-internal.sh variant index " + "--key value " + "--camel-case-key value " + "--flag " + "--boolean true " + "--outdir '/tmp/folder' " + "--param-with-spaces 'This could be a description' " + "--param-with-single-quotes 'This could '\"'\"'be'\"'\"' a description' " + "--param-with-double-quotes 'This could \"be\" a description' " + "-Ddynamic='It'\"'\"'s true' " + "-D'param with spaces'='Fuc*!'", cli); } @Test public void testCreateDefaultOutDir() throws Exception { HashMap<String, Object> params = new HashMap<>(); String jobId = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first().getId(); daemon.checkPendingJobs(); URI uri = getJob(jobId).getOutDir().getUri(); Assert.assertTrue(Files.exists(Paths.get(uri))); assertTrue(uri.getPath().startsWith(catalogManager.getConfiguration().getJobDir()) && uri.getPath().endsWith(jobId + "/")); } @Test public void testWebhookNotification() throws Exception { catalogManager.getStudyManager().update(studyFqn, new StudyUpdateParams() .setNotification(new StudyNotification(new URL("https://ptsv2.com/t/dgogf-1581523512/post"))), null, token); HashMap<String, Object> params = new HashMap<>(); String jobId = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first().getId(); daemon.checkPendingJobs(); // We sleep because there must be a thread sending notifying to the webhook url. Thread.sleep(1500); Job job = getJob(jobId); assertEquals(1, job.getInternal().getEvents().size()); assertTrue(job.getInternal().getWebhook().getStatus().containsKey("QUEUED")); assertEquals(JobInternalWebhook.Status.ERROR, job.getInternal().getWebhook().getStatus().get("QUEUED")); } @Test public void testCreateOutDir() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put("outdir", "outputDir/"); String jobId = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first().getId(); daemon.checkPendingJobs(); URI uri = getJob(jobId).getOutDir().getUri(); Assert.assertTrue(Files.exists(Paths.get(uri))); assertTrue(!uri.getPath().startsWith("/tmp/opencga/jobs/") && uri.getPath().endsWith("outputDir/")); } @Test public void testUseEmptyDirectory() throws Exception { // Create empty directory that is registered in OpenCGA org.opencb.opencga.core.models.file.File directory = catalogManager.getFileManager().createFolder(studyFqn, "outputDir/", true, "", QueryOptions.empty(), token).first(); catalogManager.getIoManagerFactory().get(directory.getUri()).createDirectory(directory.getUri(), true); HashMap<String, Object> params = new HashMap<>(); params.put("outdir", "outputDir/"); String jobId = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first().getId(); daemon.checkPendingJobs(); URI uri = getJob(jobId).getOutDir().getUri(); Assert.assertTrue(Files.exists(Paths.get(uri))); assertTrue(!uri.getPath().startsWith("/tmp/opencga/jobs/") && uri.getPath().endsWith("outputDir/")); } @Test public void testNotEmptyOutDir() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put("outdir", "data/"); String jobId = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first().getId(); daemon.checkPendingJobs(); OpenCGAResult<Job> jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, jobId, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.ABORTED, jobOpenCGAResult.first().getInternal().getStatus().getName()); assertTrue(jobOpenCGAResult.first().getInternal().getStatus().getDescription().contains("not an empty directory")); } @Test public void testProjectScopeTask() throws Exception { // User 2 to admins group in study1 but not in study2 catalogManager.getStudyManager().updateGroup(studyFqn, "@admins", ParamUtils.UpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user2")), token); // User 3 to admins group in both study1 and study2 catalogManager.getStudyManager().updateGroup(studyFqn, "@admins", ParamUtils.UpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user3")), token); catalogManager.getStudyManager().updateGroup(studyFqn2, "@admins", ParamUtils.UpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user3")), token); HashMap<String, Object> params = new HashMap<>(); String jobId = catalogManager.getJobManager().submit(studyFqn, VariantAnnotationIndexOperationTool.ID, Enums.Priority.MEDIUM, params, token).first().getId(); String jobId2 = catalogManager.getJobManager().submit(studyFqn, VariantAnnotationIndexOperationTool.ID, Enums.Priority.MEDIUM, params, sessionIdUser2).first().getId(); String jobId3 = catalogManager.getJobManager().submit(studyFqn, VariantAnnotationIndexOperationTool.ID, Enums.Priority.MEDIUM, params, sessionIdUser3).first().getId(); daemon.checkPendingJobs(); // Job sent by the owner OpenCGAResult<Job> jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, jobId, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.QUEUED, jobOpenCGAResult.first().getInternal().getStatus().getName()); // Job sent by user2 (admin from study1 but not from study2) jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, jobId2, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.ABORTED, jobOpenCGAResult.first().getInternal().getStatus().getName()); assertTrue(jobOpenCGAResult.first().getInternal().getStatus().getDescription() .contains("can only be executed by the project owners or admins")); // Job sent by user3 (admin from study1 and study2) jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, jobId3, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.QUEUED, jobOpenCGAResult.first().getInternal().getStatus().getName()); jobOpenCGAResult = catalogManager.getJobManager().search(studyFqn2, new Query(), QueryOptions.empty(), token); assertEquals(0, jobOpenCGAResult.getNumResults()); jobOpenCGAResult = catalogManager.getJobManager().search(studyFqn2, new Query(), new QueryOptions(ParamConstants.OTHER_STUDIES_FLAG, true), token); assertEquals(2, jobOpenCGAResult.getNumResults()); } @Test public void testDependsOnJobs() throws Exception { HashMap<String, Object> params = new HashMap<>(); String job1 = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first().getId(); String job2 = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, null, null, Collections.singletonList(job1), null, token).first().getId(); daemon.checkPendingJobs(); OpenCGAResult<Job> jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, job1, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.QUEUED, jobOpenCGAResult.first().getInternal().getStatus().getName()); jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, job2, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.PENDING, jobOpenCGAResult.first().getInternal().getStatus().getName()); // Set the status of job1 to ERROR catalogManager.getJobManager().update(studyFqn, job1, new PrivateJobUpdateParams() .setInternal(new JobInternal(new Enums.ExecutionStatus(Enums.ExecutionStatus.ERROR))), QueryOptions.empty(), token); // The job that depended on job1 should be ABORTED because job1 execution "failed" daemon.checkPendingJobs(); jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, job2, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.ABORTED, jobOpenCGAResult.first().getInternal().getStatus().getName()); assertTrue(jobOpenCGAResult.first().getInternal().getStatus().getDescription().contains("depended on did not finish successfully")); // Set status of job1 to DONE to simulate it finished successfully catalogManager.getJobManager().update(studyFqn, job1, new PrivateJobUpdateParams() .setInternal(new JobInternal(new Enums.ExecutionStatus(Enums.ExecutionStatus.DONE))), QueryOptions.empty(), token); // And create a new job to simulate a normal successfully dependency String job3 = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, null, null, Collections.singletonList(job1), null, token).first().getId(); daemon.checkPendingJobs(); jobOpenCGAResult = catalogManager.getJobManager().get(studyFqn, job3, QueryOptions.empty(), token); assertEquals(1, jobOpenCGAResult.getNumResults()); assertEquals(Enums.ExecutionStatus.QUEUED, jobOpenCGAResult.first().getInternal().getStatus().getName()); } @Test public void testDependsOnMultiStudy() throws Exception { HashMap<String, Object> params = new HashMap<>(); Job firstJob = catalogManager.getJobManager().submit(studyFqn, "files-delete", Enums.Priority.MEDIUM, params, token).first(); Job job = catalogManager.getJobManager().submit(studyFqn2, "files-delete", Enums.Priority.MEDIUM, params, null, null, Collections.singletonList(firstJob.getUuid()), null, token).first(); assertEquals(1, job.getDependsOn().size()); assertEquals(firstJob.getId(), job.getDependsOn().get(0).getId()); assertEquals(firstJob.getUuid(), job.getDependsOn().get(0).getUuid()); job = catalogManager.getJobManager().get(studyFqn2, job.getId(), QueryOptions.empty(), token).first(); assertEquals(1, job.getDependsOn().size()); assertEquals(firstJob.getId(), job.getDependsOn().get(0).getId()); assertEquals(firstJob.getUuid(), job.getDependsOn().get(0).getUuid()); } @Test public void testRunJob() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put(ExecutionDaemon.OUTDIR_PARAM, "outDir"); org.opencb.opencga.core.models.file.File inputFile = catalogManager.getFileManager().get(studyFqn, testFile1, null, token).first(); params.put("myFile", inputFile.getPath()); Job job = catalogManager.getJobManager().submit(studyFqn, "variant-index", Enums.Priority.MEDIUM, params, token).first(); String jobId = job.getId(); daemon.checkJobs(); String[] cli = getJob(jobId).getCommandLine().split(" "); int i = Arrays.asList(cli).indexOf("--my-file"); assertEquals("'" + inputFile.getPath() + "'", cli[i + 1]); assertEquals(1, getJob(jobId).getInput().size()); assertEquals(inputFile.getPath(), getJob(jobId).getInput().get(0).getPath()); assertEquals(Enums.ExecutionStatus.QUEUED, getJob(jobId).getInternal().getStatus().getName()); executor.jobStatus.put(jobId, Enums.ExecutionStatus.RUNNING); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.RUNNING, getJob(jobId).getInternal().getStatus().getName()); createAnalysisResult(jobId, "myTest", ar -> ar.setStatus(new Status(Status.Type.DONE, null, TimeUtils.getDate()))); executor.jobStatus.put(jobId, Enums.ExecutionStatus.READY); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.DONE, getJob(jobId).getInternal().getStatus().getName()); } @Test public void testCheckLogs() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put(ExecutionDaemon.OUTDIR_PARAM, "outDir"); org.opencb.opencga.core.models.file.File inputFile = catalogManager.getFileManager().get(studyFqn, testFile1, null, token).first(); params.put("myFile", inputFile.getPath()); Job job = catalogManager.getJobManager().submit(studyFqn, "variant-index", Enums.Priority.MEDIUM, params, token).first(); String jobId = job.getId(); daemon.checkJobs(); String[] cli = getJob(jobId).getCommandLine().split(" "); int i = Arrays.asList(cli).indexOf("--my-file"); assertEquals("'" + inputFile.getPath() + "'", cli[i + 1]); assertEquals(1, getJob(jobId).getInput().size()); assertEquals(inputFile.getPath(), getJob(jobId).getInput().get(0).getPath()); assertEquals(Enums.ExecutionStatus.QUEUED, getJob(jobId).getInternal().getStatus().getName()); executor.jobStatus.put(jobId, Enums.ExecutionStatus.RUNNING); job = catalogManager.getJobManager().get(studyFqn, jobId, null, token).first(); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.RUNNING, getJob(jobId).getInternal().getStatus().getName()); InputStream inputStream = new ByteArrayInputStream("my log content\nlast line".getBytes(StandardCharsets.UTF_8)); catalogManager.getIoManagerFactory().getDefault().copy(inputStream, Paths.get(job.getOutDir().getUri()).resolve(job.getId() + ".log").toUri()); OpenCGAResult<FileContent> fileContentResult = catalogManager.getJobManager().log(studyFqn, jobId, 0, 1, "stdout", true, token); assertEquals("last line", fileContentResult.first().getContent()); fileContentResult = catalogManager.getJobManager().log(studyFqn, jobId, 0, 1, "stdout", false, token); assertEquals("my log content\n", fileContentResult.first().getContent()); } @Test public void testRegisterFilesSuccessfully() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put(ExecutionDaemon.OUTDIR_PARAM, "outDir"); org.opencb.opencga.core.models.file.File inputFile = catalogManager.getFileManager().get(studyFqn, testFile1, null, token).first(); params.put("myFile", inputFile.getPath()); Job job = catalogManager.getJobManager().submit(studyFqn, "variant-index", Enums.Priority.MEDIUM, params, token).first(); String jobId = job.getId(); daemon.checkJobs(); String[] cli = getJob(jobId).getCommandLine().split(" "); int i = Arrays.asList(cli).indexOf("--my-file"); assertEquals("'" + inputFile.getPath() + "'", cli[i + 1]); assertEquals(1, getJob(jobId).getInput().size()); assertEquals(inputFile.getPath(), getJob(jobId).getInput().get(0).getPath()); assertEquals(Enums.ExecutionStatus.QUEUED, getJob(jobId).getInternal().getStatus().getName()); executor.jobStatus.put(jobId, Enums.ExecutionStatus.RUNNING); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.RUNNING, getJob(jobId).getInternal().getStatus().getName()); createAnalysisResult(jobId, "myTest", ar -> ar.setStatus(new Status(Status.Type.DONE, null, TimeUtils.getDate()))); executor.jobStatus.put(jobId, Enums.ExecutionStatus.READY); job = catalogManager.getJobManager().get(studyFqn, job.getId(), QueryOptions.empty(), token).first(); Files.createFile(Paths.get(job.getOutDir().getUri()).resolve("file1.txt")); Files.createFile(Paths.get(job.getOutDir().getUri()).resolve("file2.txt")); Files.createDirectory(Paths.get(job.getOutDir().getUri()).resolve("A")); Files.createFile(Paths.get(job.getOutDir().getUri()).resolve("A/file3.txt")); Files.createFile(Paths.get(job.getOutDir().getUri()).resolve(job.getId() + ".log")); Files.createFile(Paths.get(job.getOutDir().getUri()).resolve(job.getId() + ".err")); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.DONE, getJob(jobId).getInternal().getStatus().getName()); job = catalogManager.getJobManager().get(studyFqn, job.getId(), QueryOptions.empty(), token).first(); assertEquals(4, job.getOutput().size()); for (org.opencb.opencga.core.models.file.File file : job.getOutput()) { assertTrue(Arrays.asList("outDir/file1.txt", "outDir/file2.txt", "outDir/A/", "outDir/A/file3.txt").contains(file.getPath())); } assertEquals(0, job.getOutput().stream().filter(f -> f.getName().endsWith(ExecutionResultManager.FILE_EXTENSION)) .collect(Collectors.toList()).size()); assertEquals(job.getId() + ".log", job.getStdout().getName()); assertEquals(job.getId() + ".err", job.getStderr().getName()); } @Test public void testRunJobFail() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put(ExecutionDaemon.OUTDIR_PARAM, "outputDir/"); Job job = catalogManager.getJobManager().submit(studyFqn, "variant-index", Enums.Priority.MEDIUM, params, token).first(); String jobId = job.getId(); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.QUEUED, getJob(jobId).getInternal().getStatus().getName()); executor.jobStatus.put(jobId, Enums.ExecutionStatus.RUNNING); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.RUNNING, getJob(jobId).getInternal().getStatus().getName()); createAnalysisResult(jobId, "myTest", ar -> ar.setStatus(new Status(Status.Type.ERROR, null, TimeUtils.getDate()))); executor.jobStatus.put(jobId, Enums.ExecutionStatus.ERROR); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.ERROR, getJob(jobId).getInternal().getStatus().getName()); assertEquals("Job could not finish successfully", getJob(jobId).getInternal().getStatus().getDescription()); } @Test public void testRunJobFailMissingExecutionResult() throws Exception { HashMap<String, Object> params = new HashMap<>(); params.put(ExecutionDaemon.OUTDIR_PARAM, "outputDir/"); Job job = catalogManager.getJobManager().submit(studyFqn, "variant-index", Enums.Priority.MEDIUM, params, token).first(); String jobId = job.getId(); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.QUEUED, getJob(jobId).getInternal().getStatus().getName()); executor.jobStatus.put(jobId, Enums.ExecutionStatus.RUNNING); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.RUNNING, getJob(jobId).getInternal().getStatus().getName()); executor.jobStatus.put(jobId, Enums.ExecutionStatus.READY); daemon.checkJobs(); assertEquals(Enums.ExecutionStatus.ERROR, getJob(jobId).getInternal().getStatus().getName()); assertEquals("Job could not finish successfully. Missing execution result", getJob(jobId).getInternal().getStatus().getDescription()); } private Job getJob(String jobId) throws CatalogException { return catalogManager.getJobManager().get(studyFqn, jobId, new QueryOptions(), token).first(); } private void createAnalysisResult(String jobId, String analysisId, Consumer<ExecutionResult> c) throws CatalogException, IOException { ExecutionResult ar = new ExecutionResult(); c.accept(ar); File resultFile = Paths.get(getJob(jobId).getOutDir().getUri()).resolve(analysisId + ExecutionResultManager.FILE_EXTENSION).toFile(); JacksonUtils.getDefaultObjectMapper().writeValue(resultFile, ar); } private static class DummyBatchExecutor implements BatchExecutor { public Map<String, String> jobStatus = new HashMap<>(); @Override public void execute(String jobId, String commandLine, Path stdout, Path stderr) throws Exception { System.out.println("Executing job " + jobId + " --- " + commandLine); jobStatus.put(jobId, Enums.ExecutionStatus.QUEUED); } @Override public String getStatus(String jobId) { return jobStatus.getOrDefault(jobId, Enums.ExecutionStatus.UNKNOWN); } @Override public boolean isExecutorAlive() { return true; } @Override public boolean stop(String jobId) throws Exception { return false; } @Override public boolean resume(String jobId) throws Exception { return false; } @Override public boolean kill(String jobId) throws Exception { return false; } } }
package utils; public class PersonBean { String className = "utils/PersonBean"; String name; int age; int stature; String job; boolean isMarried; @Override public String toString() { return "PersonBean{" + "name='" + name + '\'' + ", age=" + age + ", stature=" + stature + ", job='" + job + '\'' + ", isMarried=" + isMarried + '}'; } }
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`. package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.Keep; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; import com.google.gson.JsonArray; import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** * Raster map textures such as satellite imagery. * * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#layers-raster">The online documentation</a> */ @UiThread public class RasterLayer extends Layer { /** * Creates a RasterLayer. * * @param nativePtr pointer used by core */ @Keep RasterLayer(long nativePtr) { super(nativePtr); } /** * Creates a RasterLayer. * * @param layerId the id of the layer * @param sourceId the id of the source */ public RasterLayer(String layerId, String sourceId) { super(); initialize(layerId, sourceId); } @Keep protected native void initialize(String layerId, String sourceId); /** * Set the source layer. * * @param sourceLayer the source layer to set */ public void setSourceLayer(String sourceLayer) { checkThread(); nativeSetSourceLayer(sourceLayer); } /** * Set the source Layer. * * @param sourceLayer the source layer to set * @return This */ public RasterLayer withSourceLayer(String sourceLayer) { setSourceLayer(sourceLayer); return this; } /** * Get the source id. * * @return id of the source */ public String getSourceId() { checkThread(); return nativeGetSourceId(); } /** * Set a property or properties. * * @param properties the var-args properties * @return This */ public RasterLayer withProperties(@NonNull PropertyValue<?>... properties) { setProperties(properties); return this; } // Property getters /** * Get the RasterOpacity property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterOpacity() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-opacity", nativeGetRasterOpacity()); } /** * Get the RasterOpacity property transition options * * @return transition options for Float */ public TransitionOptions getRasterOpacityTransition() { checkThread(); return nativeGetRasterOpacityTransition(); } /** * Set the RasterOpacity property transition options * * @param options transition options for Float */ public void setRasterOpacityTransition(TransitionOptions options) { checkThread(); nativeSetRasterOpacityTransition(options.getDuration(), options.getDelay()); } /** * Get the RasterHueRotate property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterHueRotate() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-hue-rotate", nativeGetRasterHueRotate()); } /** * Get the RasterHueRotate property transition options * * @return transition options for Float */ public TransitionOptions getRasterHueRotateTransition() { checkThread(); return nativeGetRasterHueRotateTransition(); } /** * Set the RasterHueRotate property transition options * * @param options transition options for Float */ public void setRasterHueRotateTransition(TransitionOptions options) { checkThread(); nativeSetRasterHueRotateTransition(options.getDuration(), options.getDelay()); } /** * Get the RasterBrightnessMin property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterBrightnessMin() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-brightness-min", nativeGetRasterBrightnessMin()); } /** * Get the RasterBrightnessMin property transition options * * @return transition options for Float */ public TransitionOptions getRasterBrightnessMinTransition() { checkThread(); return nativeGetRasterBrightnessMinTransition(); } /** * Set the RasterBrightnessMin property transition options * * @param options transition options for Float */ public void setRasterBrightnessMinTransition(TransitionOptions options) { checkThread(); nativeSetRasterBrightnessMinTransition(options.getDuration(), options.getDelay()); } /** * Get the RasterBrightnessMax property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterBrightnessMax() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-brightness-max", nativeGetRasterBrightnessMax()); } /** * Get the RasterBrightnessMax property transition options * * @return transition options for Float */ public TransitionOptions getRasterBrightnessMaxTransition() { checkThread(); return nativeGetRasterBrightnessMaxTransition(); } /** * Set the RasterBrightnessMax property transition options * * @param options transition options for Float */ public void setRasterBrightnessMaxTransition(TransitionOptions options) { checkThread(); nativeSetRasterBrightnessMaxTransition(options.getDuration(), options.getDelay()); } /** * Get the RasterSaturation property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterSaturation() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-saturation", nativeGetRasterSaturation()); } /** * Get the RasterSaturation property transition options * * @return transition options for Float */ public TransitionOptions getRasterSaturationTransition() { checkThread(); return nativeGetRasterSaturationTransition(); } /** * Set the RasterSaturation property transition options * * @param options transition options for Float */ public void setRasterSaturationTransition(TransitionOptions options) { checkThread(); nativeSetRasterSaturationTransition(options.getDuration(), options.getDelay()); } /** * Get the RasterContrast property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterContrast() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-contrast", nativeGetRasterContrast()); } /** * Get the RasterContrast property transition options * * @return transition options for Float */ public TransitionOptions getRasterContrastTransition() { checkThread(); return nativeGetRasterContrastTransition(); } /** * Set the RasterContrast property transition options * * @param options transition options for Float */ public void setRasterContrastTransition(TransitionOptions options) { checkThread(); nativeSetRasterContrastTransition(options.getDuration(), options.getDelay()); } /** * Get the RasterResampling property * * @return property wrapper value around String */ @SuppressWarnings("unchecked") public PropertyValue<String> getRasterResampling() { checkThread(); return (PropertyValue<String>) new PropertyValue("raster-resampling", nativeGetRasterResampling()); } /** * Get the RasterFadeDuration property * * @return property wrapper value around Float */ @SuppressWarnings("unchecked") public PropertyValue<Float> getRasterFadeDuration() { checkThread(); return (PropertyValue<Float>) new PropertyValue("raster-fade-duration", nativeGetRasterFadeDuration()); } @Keep private native Object nativeGetRasterOpacity(); @Keep private native TransitionOptions nativeGetRasterOpacityTransition(); @Keep private native void nativeSetRasterOpacityTransition(long duration, long delay); @Keep private native Object nativeGetRasterHueRotate(); @Keep private native TransitionOptions nativeGetRasterHueRotateTransition(); @Keep private native void nativeSetRasterHueRotateTransition(long duration, long delay); @Keep private native Object nativeGetRasterBrightnessMin(); @Keep private native TransitionOptions nativeGetRasterBrightnessMinTransition(); @Keep private native void nativeSetRasterBrightnessMinTransition(long duration, long delay); @Keep private native Object nativeGetRasterBrightnessMax(); @Keep private native TransitionOptions nativeGetRasterBrightnessMaxTransition(); @Keep private native void nativeSetRasterBrightnessMaxTransition(long duration, long delay); @Keep private native Object nativeGetRasterSaturation(); @Keep private native TransitionOptions nativeGetRasterSaturationTransition(); @Keep private native void nativeSetRasterSaturationTransition(long duration, long delay); @Keep private native Object nativeGetRasterContrast(); @Keep private native TransitionOptions nativeGetRasterContrastTransition(); @Keep private native void nativeSetRasterContrastTransition(long duration, long delay); @Keep private native Object nativeGetRasterResampling(); @Keep private native Object nativeGetRasterFadeDuration(); @Override @Keep protected native void finalize() throws Throwable; }
package me.zhengjie.modules.system.service; import me.zhengjie.modules.system.domain.Dept; import me.zhengjie.modules.system.service.dto.DeptDTO; import me.zhengjie.modules.system.service.dto.DeptQueryCriteria; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import java.util.List; import java.util.Set; /** * @author Zheng Jie * @date 2019-03-25 */ @CacheConfig(cacheNames = "dept") public interface DeptService { /** * queryAll * @param criteria * @return */ @Cacheable List<DeptDTO> queryAll(DeptQueryCriteria criteria); /** * findById * @param id * @return */ @Cacheable(key = "#p0") DeptDTO findById(Long id); /** * create * @param resources * @return */ @CacheEvict(allEntries = true) DeptDTO create(Dept resources); /** * update * @param resources */ @CacheEvict(allEntries = true) void update(Dept resources); /** * delete * @param id */ @CacheEvict(allEntries = true) void delete(Long id); /** * buildTree * @param deptDTOS * @return */ @Cacheable Object buildTree(List<DeptDTO> deptDTOS); /** * findByPid * @param pid * @return */ @Cacheable List<Dept> findByPid(long pid); Set<Dept> findByRoleIds(Long id); }
package org.akj.springboot.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.data.mongodb.config.EnableReactiveMongoAuditing; @SpringBootApplication(scanBasePackages = "org.akj.springboot") @EnableReactiveMongoAuditing(auditorAwareRef = "mongoDBAuditorAware") @EnableDiscoveryClient public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } }
package WayofTime.alchemicalWizardry.common.rituals; import WayofTime.alchemicalWizardry.common.LifeEssenceNetwork; import WayofTime.alchemicalWizardry.common.tileEntity.TEAltar; import WayofTime.alchemicalWizardry.common.tileEntity.TEMasterStone; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import java.util.Iterator; import java.util.List; public class RitualEffectFeatheredKnife extends RitualEffect { public final int timeDelay = 20; public final int amount = 100; @Override public void performEffect(TEMasterStone ritualStone) { String owner = ritualStone.getOwner(); World worldSave = MinecraftServer.getServer().worldServers[0]; LifeEssenceNetwork data = (LifeEssenceNetwork) worldSave.loadItemData(LifeEssenceNetwork.class, owner); if (data == null) { data = new LifeEssenceNetwork(owner); worldSave.setItemData(owner, data); } int currentEssence = data.currentEssence; World world = ritualStone.getWorldObj(); int x = ritualStone.xCoord; int y = ritualStone.yCoord; int z = ritualStone.zCoord; if (world.getWorldTime() % this.timeDelay != 0) { return; } // if(!(world.getBlockTileEntity(x, y-1, z) instanceof TEAltar)) // { // return; // } TEAltar tileAltar = null; boolean testFlag = false; for (int i = -5; i <= 5; i++) { for (int j = -5; j <= 5; j++) { for (int k = -10; k <= 10; k++) { if (world.getTileEntity(x + i, y + k, z + j) instanceof TEAltar) { tileAltar = (TEAltar) world.getTileEntity(x + i, y + k, z + j); testFlag = true; } } } } if (!testFlag) { return; } //tileAltar = (TEAltar)world.getBlockTileEntity(x,y-1,z); int d0 = 15; int vertRange = 20; AxisAlignedBB axisalignedbb = AxisAlignedBB.getAABBPool().getAABB((double) x, (double) y, (double) z, (double) (x + 1), (double) (y + 1), (double) (z + 1)).expand(d0, vertRange, d0); List list = world.getEntitiesWithinAABB(EntityPlayer.class, axisalignedbb); Iterator iterator1 = list.iterator(); EntityPlayer entity; int entityCount = 0; boolean flag = false; while (iterator1.hasNext()) { entity = (EntityPlayer) iterator1.next(); if (entity.getClass().equals(EntityPlayerMP.class) || entity.getClass().equals(EntityPlayer.class)) { entityCount++; } } if (currentEssence < this.getCostPerRefresh() * entityCount) { EntityPlayer entityOwner = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(owner); if (entityOwner == null) { return; } entityOwner.addPotionEffect(new PotionEffect(Potion.confusion.id, 80)); } else { Iterator iterator2 = list.iterator(); entityCount = 0; while (iterator2.hasNext()) { entity = (EntityPlayer) iterator2.next(); //entity = (EntityPlayer)iterator1.next(); if (entity.getClass().equals(EntityPlayerMP.class) || entity.getClass().equals(EntityPlayer.class)) { if (entity.getHealth() > 6.2f) { entity.setHealth(entity.getHealth() - 1); entityCount++; tileAltar.sacrificialDaggerCall(this.amount, false); } } //entity.setHealth(entity.getHealth()-1); // if(entity.getHealth()<=0.2f) // { // entity.onDeath(DamageSource.inFire); // } } data.currentEssence = currentEssence - this.getCostPerRefresh() * entityCount; data.markDirty(); } } @Override public int getCostPerRefresh() { // TODO Auto-generated method stub return 20; } }
package edu.citadel.cprl.ast; import edu.citadel.compiler.CodeGenException; import edu.citadel.compiler.ConstraintException; import edu.citadel.compiler.ErrorHandler; import edu.citadel.cprl.Symbol; import edu.citadel.cprl.Token; import edu.citadel.cprl.Type; /** * The abstract syntax tree node for a constant value expression, which is * either a literal or a declared constant identifier representing a literal. */ public class ConstValue extends Expression { /** * The literal token for the constant. If the const value is created from * a ConstDecl, then the literal is the one contained in the declaration. */ private Token literal; /** * Construct a constant value from a literal token. */ public ConstValue(Token literal) { super(Type.getTypeOf(literal.getSymbol()), literal.getPosition()); this.literal = literal; } /** * Construct a constant value from a constant identifier * token and its corresponding constant declaration. */ public ConstValue(Token identifier, ConstDecl decl) { super(decl.getType(), identifier.getPosition()); this.literal = decl.getLiteral(); } /** * Returns an integer value for the declaration literal. For an integer * literal, this method simply returns its integer value. For a char * literal, this method returns the underlying integer value for the * character. For a boolean literal, this method returns 0 for false * and 1 for true. For any other literal, the method returns 0. */ public int getLiteralIntValue() { if (literal.getSymbol() == Symbol.intLiteral) return Integer.parseInt(literal.getText()); else if (literal.getSymbol() == Symbol.trueRW) return 1; else if (literal.getSymbol() == Symbol.charLiteral) { char ch = literal.getText().charAt(1); return (int) ch; } else return 0; } @Override public void checkConstraints() { try { // check that an intLiteral can actually be converted to an integer if (literal.getSymbol() == Symbol.intLiteral) { try { Integer.parseInt(literal.getText()); } catch(NumberFormatException e1) { String errorMsg = "The number \"" + literal.getText() + "\" cannot be converted to an integer in CPRL."; throw error(literal.getPosition(), errorMsg); } } } catch (ConstraintException e) { ErrorHandler.getInstance().reportError(e); } } @Override public void emit() throws CodeGenException { Type exprType = getType(); if (exprType == Type.Integer) emit("LDCINT " + getLiteralIntValue()); else if (exprType == Type.Boolean) emit("LDCB " + getLiteralIntValue()); else if (exprType == Type.Char) emit("LDCCH " + literal.getText()); else if (exprType == Type.String) emit("LDCSTR " + literal.getText()); else { String errorMsg = "Invalid type for constant value."; throw new CodeGenException(literal.getPosition(), errorMsg); } } }
package exercicios; import java.util.Scanner; public class Uri1019 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int horas = N / 3600; int minutos = (N % 3600) / 60; int segundos = N % 60; System.out.println(horas + ":" + minutos + ":" + segundos); sc.close(); } }
/* * Copyright (c) 2016, LinkedKeeper * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of LinkedKeeper nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.qiqiim.server.exception; public class InitErrorException extends RuntimeException { private static final long serialVersionUID = 4401440531171871948L; private int errorCode = 1; private String errorMsg; protected InitErrorException() { } public InitErrorException(String errorMsg, Throwable e) { super(errorMsg, e); this.errorMsg = errorMsg; } public InitErrorException(String errorMsg) { super(errorMsg); this.errorMsg = errorMsg; } }
/** * Copyright (c) 2016 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.web.component.data.column; import org.apache.wicket.AttributeModifier; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.export.IExportableColumn; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.component.util.SelectableBean; import com.evolveum.midpoint.web.page.admin.server.dto.OperationResultStatusPresentationProperties; import com.evolveum.midpoint.web.page.error.PageOperationResult; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import org.apache.wicket.model.Model; /** * @author semancik * */ public class ObjectNameColumn<O extends ObjectType> extends AbstractColumn<SelectableBean<O>, String> implements IExportableColumn<SelectableBean<O>, String>{ private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(ObjectNameColumn.class); public ObjectNameColumn(IModel<String> displayModel) { super(displayModel, ObjectType.F_NAME.getLocalPart()); } public ObjectNameColumn(IModel<String> displayModel, String itemPath) { super(displayModel, itemPath); } @Override public void populateItem(final Item<ICellPopulator<SelectableBean<O>>> cellItem, String componentId, final IModel<SelectableBean<O>> rowModel) { IModel<String> labelModel = new AbstractReadOnlyModel<String>() { private static final long serialVersionUID = 1L; @Override public String getObject() { SelectableBean<O> selectableBean = rowModel.getObject(); O value = selectableBean.getValue(); if (value == null) { OperationResult result = selectableBean.getResult(); OperationResultStatusPresentationProperties props = OperationResultStatusPresentationProperties.parseOperationalResultStatus(result.getStatus()); return cellItem.getString(props.getStatusLabelKey()); } else { String name = WebComponentUtil.getName(value); if (selectableBean.getResult() != null){ StringBuilder complexName = new StringBuilder(); complexName.append(name); complexName.append(" ("); complexName.append(selectableBean.getResult().getStatus()); complexName.append(")"); return complexName.toString(); } return name; } } }; if (isClickable(rowModel)) { // beware: rowModel is very probably resolved at this moment; but it seems to cause no problems cellItem.add(new LinkPanel(componentId, labelModel) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { SelectableBean<O> selectableBean = rowModel.getObject(); O value = selectableBean.getValue(); if (value == null) { OperationResult result = selectableBean.getResult(); throw new RestartResponseException(new PageOperationResult(result)); } else { if (selectableBean.getResult() != null) { throw new RestartResponseException(new PageOperationResult(selectableBean.getResult())); } else { ObjectNameColumn.this.onClick(target, rowModel); } } } }); } else { cellItem.add(new Label(componentId, labelModel)); } } public boolean isClickable(IModel<SelectableBean<O>> rowModel) { return true; } public void onClick(AjaxRequestTarget target, IModel<SelectableBean<O>> rowModel) { } public IModel<String> getDataModel(IModel<SelectableBean<O>> rowModel) { SelectableBean<O> selectableBean = rowModel.getObject(); O value = selectableBean.getValue(); return Model.of(value == null ? "" : WebComponentUtil.getName(value)); } }
package net.feichti.codingcontest.diagram.part; import org.eclipse.emf.common.ui.URIEditorInput; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorMatchingStrategy; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.PartInitException; /** * @generated */ public class CodingcontestMatchingStrategy implements IEditorMatchingStrategy { /** * @generated */ public boolean matches(IEditorReference editorRef, IEditorInput input) { IEditorInput editorInput; try { editorInput = editorRef.getEditorInput(); } catch(PartInitException e) { return false; } if(editorInput.equals(input)) { return true; } if(editorInput instanceof URIEditorInput && input instanceof URIEditorInput) { return ((URIEditorInput) editorInput).getURI().equals(((URIEditorInput) input).getURI()); } return false; } }
package software.amazon.sso.permissionset; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import software.amazon.awssdk.services.ssoadmin.model.CreatePermissionSetRequest; import software.amazon.awssdk.services.ssoadmin.model.DeletePermissionSetRequest; import software.amazon.awssdk.services.ssoadmin.model.DescribePermissionSetRequest; import software.amazon.awssdk.services.ssoadmin.model.DescribePermissionSetResponse; import software.amazon.awssdk.services.ssoadmin.model.PermissionSet; import software.amazon.awssdk.services.ssoadmin.model.ProvisionPermissionSetRequest; import software.amazon.awssdk.services.ssoadmin.model.ProvisionTargetType; import software.amazon.awssdk.services.ssoadmin.model.Tag; import software.amazon.awssdk.services.ssoadmin.model.TagResourceRequest; import software.amazon.awssdk.services.ssoadmin.model.UntagResourceRequest; import software.amazon.awssdk.services.ssoadmin.model.UpdatePermissionSetRequest; import software.amazon.awssdk.services.ssoadmin.model.ValidationException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; /** * This class is a centralized placeholder for * - api request construction * - object translation to/from aws sdk * - resource model construction for read/list handlers */ public class Translator { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); /** * Request to create a resource * @param model resource model * @return awsRequest the aws service request to create a resource */ static CreatePermissionSetRequest translateToCreateRequest(final ResourceModel model) { return CreatePermissionSetRequest.builder() .name(model.getName()) .description(model.getDescription()) .instanceArn(model.getInstanceArn()) .relayState(model.getRelayStateType()) .sessionDuration(model.getSessionDuration()) .tags(ConvertToSSOTag(model.getTags())) .build(); } /** * Request to read a resource * @param model resource model * @return awsRequest the aws service request to describe a resource */ static DescribePermissionSetRequest translateToReadRequest(final ResourceModel model) { return DescribePermissionSetRequest.builder() .instanceArn(model.getInstanceArn()) .permissionSetArn(model.getPermissionSetArn()) .build(); } /** * Translates resource object from sdk into a resource model * @param awsResponse the aws service describe resource response * @return model resource model */ static ResourceModel translateFromReadResponse(final DescribePermissionSetResponse readResult, String instanceArn, List<software.amazon.sso.permissionset.Tag> tags) { PermissionSet returnedPermissionSet = readResult.permissionSet(); ResourceModel returnedModel = ResourceModel.builder() .permissionSetArn(returnedPermissionSet.permissionSetArn()) .description(returnedPermissionSet.description()) .name(returnedPermissionSet.name()) .relayStateType(returnedPermissionSet.relayState()) .sessionDuration(returnedPermissionSet.sessionDuration()) .instanceArn(instanceArn) .build(); if (tags != null && tags.size() > 0) { returnedModel.setTags(tags); } return returnedModel; } /** * Request to delete a resource * @param model resource model * @return awsRequest the aws service request to delete a resource */ static DeletePermissionSetRequest translateToDeleteRequest(final ResourceModel model) { return DeletePermissionSetRequest.builder() .instanceArn(model.getInstanceArn()) .permissionSetArn(model.getPermissionSetArn()) .build(); } /** * Request to update properties of a previously created resource * @param model resource model * @return awsRequest the aws service request to modify a resource */ static UpdatePermissionSetRequest translateToUpdateRequest(final ResourceModel model) { return UpdatePermissionSetRequest.builder() .description(model.getDescription()) .permissionSetArn(model.getPermissionSetArn()) .instanceArn(model.getInstanceArn()) .relayState(model.getRelayStateType()) .sessionDuration(model.getSessionDuration()) .build(); } /** * Request to untag resource * @param model resource model * @return awsRequest the aws service request to modify a resource */ static UntagResourceRequest translateToUntagResourceRequest(final ResourceModel model, List<String> tagKeys) { return UntagResourceRequest.builder() .instanceArn(model.getInstanceArn()) .resourceArn(model.getPermissionSetArn()) .tagKeys(tagKeys) .build(); } /** * Request to tag resource * @param model resource model * @return awsRequest the aws service request to modify a resource */ static TagResourceRequest translateToTagResourceRequest(final ResourceModel model, List<Tag> tags) { return TagResourceRequest.builder() .instanceArn(model.getInstanceArn()) .resourceArn(model.getPermissionSetArn()) .tags(tags) .build(); } static ProvisionPermissionSetRequest translateToProvsionPermissionSetRequest(final ResourceModel model) { return ProvisionPermissionSetRequest.builder() .instanceArn(model.getInstanceArn()) .permissionSetArn(model.getPermissionSetArn()) .targetType(ProvisionTargetType.ALL_PROVISIONED_ACCOUNTS) .build(); } private static <T> Stream<T> streamOfOrEmpty(final Collection<T> collection) { return Optional.ofNullable(collection) .map(Collection::stream) .orElseGet(Stream::empty); } static List<Tag> ConvertToSSOTag(List<software.amazon.sso.permissionset.Tag> tags) { List<Tag> ssoPermissionSetTags = new ArrayList<>(); if (tags == null || tags.size() == 0) { return ssoPermissionSetTags; } for (software.amazon.sso.permissionset.Tag tag : tags) { ssoPermissionSetTags.add(Tag.builder().key(tag.getKey()).value(tag.getValue()).build()); } return ssoPermissionSetTags; } static List<software.amazon.sso.permissionset.Tag> ConvertToModelTag(List<Tag> tags) { List<software.amazon.sso.permissionset.Tag> ssoPermissionSetTags = new ArrayList<>(); if (tags == null) { return null; } for (Tag tag : tags) { ssoPermissionSetTags.add(software.amazon.sso.permissionset.Tag.builder() .key(tag.key()) .value(tag.value()) .build()); } return ssoPermissionSetTags; } static String processInlinePolicy(final Object policyDocument) { if(policyDocument == null) { return null; } if (policyDocument instanceof Map) { try { return OBJECT_MAPPER.writeValueAsString(policyDocument); } catch (final JsonProcessingException e) { throw ValidationException.builder().message(e.getMessage()).build(); } } return (String)policyDocument; } }
package com.android.renly.meetingreservation.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Locale; public class sHA1Utils { public static String sHA1(Context context) { try { PackageInfo info = context.getPackageManager().getPackageInfo( context.getPackageName(), PackageManager.GET_SIGNATURES); byte[] cert = info.signatures[0].toByteArray(); MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] publicKey = md.digest(cert); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < publicKey.length; i++) { String appendString = Integer.toHexString(0xFF & publicKey[i]) .toUpperCase(Locale.US); if (appendString.length() == 1) hexString.append("0"); hexString.append(appendString); hexString.append(":"); } String result = hexString.toString(); return result.substring(0, result.length()-1); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } }
package org.jabref.logic.importer.fileformat; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.FileExtensions; import org.jabref.model.entry.BibEntry; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; public class PdfContentImporterTest { private PdfContentImporter importer; @Before public void setUp() { importer = new PdfContentImporter(mock(ImportFormatPreferences.class)); } @Test public void testsGetExtensions() { assertEquals(FileExtensions.PDF_CONTENT, importer.getExtensions()); } @Test public void testGetDescription() { assertEquals( "PdfContentImporter parses data of the first page of the PDF and creates a BibTeX entry. Currently, Springer and IEEE formats are supported.", importer.getDescription()); } @Test public void doesNotHandleEncryptedPdfs() throws URISyntaxException { Path file = Paths.get(PdfContentImporter.class.getResource("/pdfs/encrypted.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file, StandardCharsets.UTF_8).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); } }
/* */ /** * This package contains the RESTful administration interface to Taverna Server. * @author Donal Fellows */ @XmlSchema(namespace = ADMIN, elementFormDefault = QUALIFIED, attributeFormDefault = QUALIFIED, xmlns = { @XmlNs(prefix = "xlink", namespaceURI = XLINK), @XmlNs(prefix = "ts", namespaceURI = SERVER), @XmlNs(prefix = "ts-rest", namespaceURI = SERVER_REST), @XmlNs(prefix = "ts-soap", namespaceURI = SERVER_SOAP), @XmlNs(prefix = "feed", namespaceURI = FEED), @XmlNs(prefix = "admin", namespaceURI = ADMIN), @XmlNs(prefix = "ur", namespaceURI = UR), @XmlNs(prefix = "ds", namespaceURI = XSIG) }) package org.apache.taverna.server.master.admin; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static javax.xml.bind.annotation.XmlNsForm.QUALIFIED; import static org.apache.taverna.server.master.common.Namespaces.ADMIN; import static org.apache.taverna.server.master.common.Namespaces.FEED; import static org.apache.taverna.server.master.common.Namespaces.SERVER; import static org.apache.taverna.server.master.common.Namespaces.SERVER_REST; import static org.apache.taverna.server.master.common.Namespaces.SERVER_SOAP; import static org.apache.taverna.server.master.common.Namespaces.UR; import static org.apache.taverna.server.master.common.Namespaces.XLINK; import static org.apache.taverna.server.master.common.Namespaces.XSIG; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlSchema;
/** * Copyright 2016 SAP SE * * 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.sap.cloud.sfsf.timeoff.google; import java.time.ZonedDateTime; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.api.services.gmail.model.VacationSettings; import com.sap.cloud.sfsf.timeoff.entity.Messages; import com.sap.cloud.sfsf.timeoff.entity.SFSFEmployeeTime; import com.sap.cloud.sfsf.timeoff.jackson.DefaultMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import rx.Observable; @Component public class AutoReplies { private final CalendarService calendarService; private final Messages message; private final ObjectMapper mapper = DefaultMapper.newMapper(); private final Logger logger = LoggerFactory.getLogger(AutoReplies.class); @Autowired public AutoReplies(final CalendarService calendarService, final Messages message) { this.calendarService = calendarService; this.message = message; } public Observable<VacationSettings> getAutomaticReply(final SFSFEmployeeTime employeeTime) { return calendarService.getAutoReply(employeeTime.getUserId()); } public Observable<VacationSettings> enableAutomaticReply(final SFSFEmployeeTime employeeTime) { final ZonedDateTime start = employeeTime.getStartDate(); final ZonedDateTime end = employeeTime.getEndDate(); final String replyMessage = message.getAutoReplyMessage(employeeTime); final VacationSettings autoReplySettings = new VacationSettings() // start time for autoreply .setStartTime(start.toInstant().toEpochMilli()) // end time for autoreply .setEndTime(end.toInstant().toEpochMilli()) // it's scheduled for specific period .setEnableAutoReply(true) // comment .setResponseBodyHtml(replyMessage); logger.debug(String.format("Enabling Google Autoreply: %s", asJson(autoReplySettings))); return calendarService.setAutoReply(autoReplySettings, employeeTime.getUserId()); } public Observable<VacationSettings> disableAutomaticReply(final String userId) { final VacationSettings disabledAutoreplySetting = new VacationSettings().setEnableAutoReply(false); logger.debug(String.format("Disabling Google Autoreply: %s", asJson(disabledAutoreplySetting))); return calendarService.setAutoReply(disabledAutoreplySetting, userId); } private <T> String asJson(final T obj) { try { return mapper.writeValueAsString(obj); } catch (final JsonProcessingException e) { logger.error("Failed to serialize object.", e); } return null; } }
package net.bither.db;///* // * Copyright 2014 http://Bither.net // * // * 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.bither.db; // //import android.database.sqlite.SQLiteOpenHelper; // //import net.bither.PrimerApplication; //import net.bither.bitherj.db.IDesktopAddressProvider; // //import java.util.ArrayList; //import java.util.List; // ///** // * Created by nn on 15/6/17. // */ //public class DesktopAddressProvider implements IDesktopAddressProvider { // // private static DesktopAddressProvider desktopAddressProvider = new DesktopAddressProvider(PrimerApplication.mAddressDbHelper); // // public static DesktopAddressProvider getInstance() { // return desktopAddressProvider; // } // // private SQLiteOpenHelper mDb; // // // private DesktopAddressProvider(SQLiteOpenHelper db) { // this.mDb = db; // } // // @Override // public int addHDKey(String encryptedMnemonicSeed, String encryptHdSeed, String firstAddress, boolean isXrandom, String addressOfPS, byte[] externalPub, byte[] internalPub) { // return 0; // } // // @Override // public void addHDMPub(List<byte[]> externalPubs, List<byte[]> internalPubs) { // // } // // @Override // public List<byte[]> getExternalPubs() { // return new ArrayList<byte[]>(); // } // // @Override // public List<byte[]> getInternalPubs() { // return new ArrayList<byte[]>(); // } // // @Override // public boolean isHDSeedFromXRandom(int hdSeedId) { // return false; // } // // @Override // public String getEncryptMnemonicSeed(int hdSeedId) { // return null; // } // // @Override // public String getEncryptHDSeed(int hdSeedId) { // return null; // } // // @Override // public String getHDMFristAddress(int hdSeedId) { // return null; // } // // @Override // public List<Integer> getDesktopKeyChainSeed() { // return new ArrayList<Integer>(); // } //}
package dev.sheldan.abstracto.modmail.service; import com.jagrosh.jdautilities.commons.waiter.EventWaiter; import com.jagrosh.jdautilities.menu.ButtonMenu; import dev.sheldan.abstracto.core.command.exception.AbstractoTemplatedException; import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException; import dev.sheldan.abstracto.core.metric.service.CounterMetric; import dev.sheldan.abstracto.core.metric.service.MetricService; import dev.sheldan.abstracto.core.metric.service.MetricTag; import dev.sheldan.abstracto.core.models.FeatureValidationResult; import dev.sheldan.abstracto.core.models.FullGuild; import dev.sheldan.abstracto.core.models.FullUserInServer; import dev.sheldan.abstracto.core.models.UndoActionInstance; import dev.sheldan.abstracto.core.models.database.*; import dev.sheldan.abstracto.core.service.*; import dev.sheldan.abstracto.core.service.management.ChannelManagementService; import dev.sheldan.abstracto.core.service.management.ServerManagementService; import dev.sheldan.abstracto.core.service.management.UserInServerManagementService; import dev.sheldan.abstracto.core.utils.CompletableFutureList; import dev.sheldan.abstracto.core.utils.FutureUtils; import dev.sheldan.abstracto.modmail.config.ModMailFeatureConfig; import dev.sheldan.abstracto.modmail.config.ModMailFeatureDefinition; import dev.sheldan.abstracto.modmail.config.ModMailMode; import dev.sheldan.abstracto.modmail.config.ModMailPostTargets; import dev.sheldan.abstracto.modmail.exception.ModMailCategoryIdException; import dev.sheldan.abstracto.modmail.exception.ModMailThreadChannelNotFound; import dev.sheldan.abstracto.modmail.exception.ModMailThreadNotFoundException; import dev.sheldan.abstracto.modmail.model.ClosingContext; import dev.sheldan.abstracto.modmail.model.database.*; import dev.sheldan.abstracto.modmail.model.dto.ServerChoice; import dev.sheldan.abstracto.modmail.model.template.*; import dev.sheldan.abstracto.modmail.service.management.ModMailMessageManagementService; import dev.sheldan.abstracto.modmail.service.management.ModMailRoleManagementService; import dev.sheldan.abstracto.modmail.service.management.ModMailSubscriberManagementService; import dev.sheldan.abstracto.modmail.service.management.ModMailThreadManagementService; import dev.sheldan.abstracto.modmail.validator.ModMailFeatureValidator; import dev.sheldan.abstracto.core.templating.model.MessageToSend; import dev.sheldan.abstracto.core.templating.service.TemplateService; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.exceptions.InsufficientPermissionException; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; @Component @Slf4j public class ModMailThreadServiceBean implements ModMailThreadService { /** * The config key to use for the closing text */ public static final String MODMAIL_CLOSING_MESSAGE_TEXT = "modMailClosingText"; /** * The config key to use for the ID of the category to create {@link MessageChannel} in */ public static final String MODMAIL_CATEGORY = "modmailCategory"; public static final String TEXT_CHANNEL_NAME_TEMPLATE_KEY = "modMail_channel_name"; /** * The template key used for default mod mail exceptions */ public static final String MODMAIL_CLOSE_PROGRESS_TEMPLATE_KEY = "modmail_closing_progress"; public static final String MODMAIL_STAFF_MESSAGE_TEMPLATE_KEY = "modmail_staff_message"; public static final String MODMAIL_THREAD_CREATED_TEMPLATE_KEY = "modmail_thread_created"; @Autowired private ModMailThreadManagementService modMailThreadManagementService; @Autowired private ConfigService configService; @Autowired private ChannelService channelService; @Autowired private ChannelManagementService channelManagementService; @Autowired private UserInServerManagementService userInServerManagementService; @Autowired private MemberService memberService; @Autowired private TemplateService templateService; @Autowired private ModMailMessageManagementService modMailMessageManagementService; @Autowired private ModMailMessageService modMailMessageService; @Autowired private PostTargetService postTargetService; @Autowired private ReactionService reactionService; @Autowired private GuildService guildService; @Autowired private MessageService messageService; @Autowired private FeatureFlagService featureFlagService; @Autowired private ModMailFeatureConfig modMailFeatureConfig; @Autowired private ModMailRoleManagementService modMailRoleManagementService; @Autowired private UndoActionService undoActionService; @Autowired private ModMailSubscriberManagementService modMailSubscriberManagementService; @Autowired private EventWaiter eventWaiter; @Autowired private FeatureModeService featureModeService; @Autowired private ModMailFeatureValidator modMailFeatureValidator; @Autowired private ServerManagementService serverManagementService; @Autowired private UserService userService; @Autowired private ModMailThreadServiceBean self; @Autowired private MetricService metricService; public static final String MODMAIL_THREAD_METRIC = "modmail.threads"; public static final String MODMAIL_MESSAGE_METRIC = "modmail.messges"; public static final String ACTION = "action"; public static final String MESSAGE_DIRECTION = "direction"; private static final CounterMetric MODMAIL_THREAD_CREATED_COUNTER = CounterMetric .builder() .name(MODMAIL_THREAD_METRIC) .tagList(Arrays.asList(MetricTag.getTag(ACTION, "created"))) .build(); private static final CounterMetric MODMAIL_THREAD_CLOSED_COUNTER = CounterMetric .builder() .name(MODMAIL_THREAD_METRIC) .tagList(Arrays.asList(MetricTag.getTag(ACTION, "closed"))) .build(); private static final CounterMetric MDOMAIL_THREAD_MESSAGE_RECEIVED = CounterMetric .builder().name(MODMAIL_MESSAGE_METRIC) .tagList(Arrays.asList(MetricTag.getTag(MESSAGE_DIRECTION, "received"))) .build(); private static final CounterMetric MDOMAIL_THREAD_MESSAGE_SENT = CounterMetric .builder() .name(MODMAIL_MESSAGE_METRIC) .tagList(Arrays.asList(MetricTag.getTag(MESSAGE_DIRECTION, "sent"))) .build(); /** * The emoji used when the user can decide for a server to open a mod mail thread in. */ private static List<String> NUMBER_EMOJI = Arrays.asList("\u0031\u20e3", "\u0032\u20e3", "\u0033\u20e3", "\u0034\u20e3", "\u0035\u20e3", "\u0036\u20e3", "\u0037\u20e3", "\u0038\u20e3", "\u0039\u20e3", "\u0040\u20e3"); @Override public CompletableFuture<Void> createModMailThreadForUser(Member member, Message initialMessage, MessageChannel feedBackChannel, boolean userInitiated, List<UndoActionInstance> undoActions) { Long serverId = member.getGuild().getIdLong(); Long categoryId = configService.getLongValue(MODMAIL_CATEGORY, serverId); AServer server = serverManagementService.loadServer(member.getGuild().getIdLong()); metricService.incrementCounter(MODMAIL_THREAD_CREATED_COUNTER); User user = member.getUser(); log.info("Creating modmail channel for user {} in category {} on server {}.", user.getId(), categoryId, serverId); ModMailChannelNameModel model = ModMailChannelNameModel .builder() .serverId(serverId) .userId(member.getIdLong()) .randomText(RandomStringUtils.randomAlphanumeric(25)) .uuid(UUID.randomUUID().toString()) .currentDate(Instant.now()) .build(); String channelName = templateService.renderTemplate(TEXT_CHANNEL_NAME_TEMPLATE_KEY, model, serverId); CompletableFuture<TextChannel> textChannelFuture = channelService.createTextChannel(channelName, server, categoryId); return textChannelFuture.thenCompose(channel -> { undoActions.add(UndoActionInstance.getChannelDeleteAction(serverId, channel.getIdLong())); return self.performModMailThreadSetup(member, initialMessage, channel, userInitiated, undoActions, feedBackChannel); }); } @Transactional public CompletableFuture<Void> sendContactNotification(Member member, TextChannel textChannel, MessageChannel feedBackChannel) { ContactNotificationModel model = ContactNotificationModel .builder() .createdChannel(textChannel) .targetMember(member) .build(); return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInMessageChannelList(MODMAIL_THREAD_CREATED_TEMPLATE_KEY, model, feedBackChannel)); } /** * This method is responsible for creating the instance in the database, sending the header in the newly created text channel and forwarding the initial message * by the user (if any), after this is complete, this method executes the method to perform the mod mail notification. * @param member The {@link Member} for which a {@link ModMailThread} is being created * @param initialMessage The {@link Message} which was sent by the user to open a thread, this is null, if the thread was opened via a command * @param channel The created {@link TextChannel} in which the mod mail thread is dealt with * @param userInitiated Whether or not the thread was initiated by a member * @param undoActions The list of actions to undo, in case an exception occurs * @return A {@link CompletableFuture future} which completes when the setup is done */ @Transactional public CompletableFuture<Void> performModMailThreadSetup(Member member, Message initialMessage, TextChannel channel, boolean userInitiated, List<UndoActionInstance> undoActions, MessageChannel feedBackChannel) { log.info("Performing modmail thread setup for channel {} for user {} in server {}. It was initiated by a user: {}.", channel.getIdLong(), member.getId(), channel.getGuild().getId(), userInitiated); CompletableFuture<Void> headerFuture = sendModMailHeader(channel, member); CompletableFuture<Message> userReplyMessage; if(initialMessage != null){ log.info("Sending initial message {} of user {} to modmail thread {}.", initialMessage.getId(), member.getId(), channel.getId()); userReplyMessage = self.sendUserReply(channel, 0L, initialMessage, member, false); } else { log.info("No initial message to send."); userReplyMessage = CompletableFuture.completedFuture(null); } CompletableFuture notificationFuture; if (userInitiated) { notificationFuture = self.sendModMailNotification(member, channel); } else { notificationFuture = CompletableFuture.completedFuture(null); } return CompletableFuture.allOf(headerFuture, notificationFuture, userReplyMessage).thenAccept(aVoid -> { undoActions.clear(); self.setupModMailThreadInDB(initialMessage, channel, member, userReplyMessage.join()); }).thenAccept(unused -> { if(!userInitiated) { self.sendContactNotification(member, channel, feedBackChannel); } }); } @Transactional public void setupModMailThreadInDB(Message initialMessage, TextChannel channel, Member member, Message sendMessage) { log.info("Persisting info about modmail thread {} in database.", channel.getIdLong()); AUserInAServer aUserInAServer = userInServerManagementService.loadOrCreateUser(member); ModMailThread thread = createThreadObject(channel, aUserInAServer); if(initialMessage != null) { log.debug("Adding initial message {} to modmail thread in channel {}.", initialMessage.getId(), channel.getId()); modMailMessageManagementService.addMessageToThread(thread, null, sendMessage, initialMessage, aUserInAServer, false, false); } } /** * Sends the message containing the pings to notify the staff members to handle the opened {@link ModMailThread} * @param member The {@link FullUserInServer} which opened the thread * @param channel The created {@link TextChannel} in which the mod mail thread is dealt with * @return A {@link CompletableFuture future} which complets when the notification has been sent */ @Transactional public CompletableFuture<Void> sendModMailNotification(Member member, TextChannel channel) { Long serverId = member.getGuild().getIdLong(); log.info("Sending modmail notification for new modmail thread about user {} in server {}.", member.getId(), serverId); AServer server = serverManagementService.loadServer(serverId); List<ModMailRole> rolesToPing = modMailRoleManagementService.getRolesForServer(server); log.debug("Pinging {} roles to notify about modmail thread about user {} in server {}.", rolesToPing.size(), member.getId(), serverId); ModMailNotificationModel modMailNotificationModel = ModMailNotificationModel .builder() .member(member) .roles(rolesToPing) .channel(channel) .build(); MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_notification_message", modMailNotificationModel, channel.getGuild().getIdLong()); return FutureUtils.toSingleFutureGeneric(postTargetService.sendEmbedInPostTarget(messageToSend, ModMailPostTargets.MOD_MAIL_PING, serverId)); } /** * Creates the instance of the {@link ModMailThread} in the database. * @param channel The {@link TextChannel} in which the {@link ModMailThread} is being done * @param user The {@link AUserInAServer} which the thread is about * @return The created instance of {@link ModMailThread} */ public ModMailThread createThreadObject(TextChannel channel, AUserInAServer user) { log.info("Creating database objects related to modmail thread in channel {} and about user {} in server {}.", channel.getIdLong(), user.getUserReference().getId(), channel.getGuild().getId()); AChannel channel2 = channelManagementService.createChannel(channel.getIdLong(), AChannelType.TEXT, user.getServerReference()); log.info("Creating mod mail thread in channel {} with db channel {}", channel.getIdLong(), channel2.getId()); return modMailThreadManagementService.createModMailThread(user, channel2); } @Override public void setModMailCategoryTo(Guild guild, Long categoryId) { log.info("Trying to set modmail category to {} in guild {}.", categoryId, guild.getId()); FeatureValidationResult result = FeatureValidationResult.builder().build(); modMailFeatureValidator.validateModMailCategory(result, guild, categoryId); if(result.getValidationResult()) { throw new ModMailCategoryIdException(categoryId); } configService.setLongValue(MODMAIL_CATEGORY, guild.getIdLong(), categoryId); } @Override public void createModMailPrompt(AUser user, Message initialMessage) { List<AUserInAServer> knownServers = userInServerManagementService.getUserInAllServers(user.getId()); // if the user doesnt exist in the servery set, we need to create the user first in all of them, in order to offer it if(knownServers.isEmpty()) { List<Guild> mutualServers = initialMessage.getJDA().getMutualGuilds(initialMessage.getAuthor()); mutualServers.forEach(guild -> { AServer server = serverManagementService.loadServer(guild); knownServers.add(userInServerManagementService.loadOrCreateUser(server, user)); }); } if(!knownServers.isEmpty()) { log.info("There are {} shared servers between user and the bot.", knownServers.size()); List<ServerChoice> availableGuilds = new ArrayList<>(); HashMap<String, Long> choices = new HashMap<>(); for (int i = 0; i < knownServers.size(); i++) { AUserInAServer aUserInAServer = knownServers.get(i); // only take the servers in which mod mail is actually enabled, would not make much sense to make the // other servers available if(featureFlagService.isFeatureEnabled(modMailFeatureConfig, aUserInAServer.getServerReference())) { AServer serverReference = aUserInAServer.getServerReference(); FullGuild guild = FullGuild .builder() .guild(guildService.getGuildById(serverReference.getId())) .server(serverReference) .build(); // TODO support more than this limited amount of servers String reactionEmote = NUMBER_EMOJI.get(i); ServerChoice serverChoice = ServerChoice.builder().guild(guild).reactionEmote(reactionEmote).build(); choices.put(reactionEmote, aUserInAServer.getServerReference().getId()); availableGuilds.add(serverChoice); } } log.info("There were {} shared servers found which have modmail enabled.", availableGuilds.size()); // if more than 1 server is available, show a choice dialog ArrayList<UndoActionInstance> undoActions = new ArrayList<>(); if(availableGuilds.size() > 1) { ModMailServerChooserModel modMailServerChooserModel = ModMailServerChooserModel .builder() .commonGuilds(availableGuilds) .build(); String text = templateService.renderTemplate("modmail_modal_server_choice", modMailServerChooserModel); ButtonMenu menu = new ButtonMenu.Builder() .setChoices(choices.keySet().toArray(new String[0])) .setEventWaiter(eventWaiter) .setDescription(text) .setAction(reactionEmote -> { Long chosenServerId = choices.get(reactionEmote.getEmoji()); Long userId = initialMessage.getAuthor().getIdLong(); log.debug("Executing action for creationg a modmail thread in server {} for user {}.", chosenServerId, userId); memberService.getMemberInServerAsync(chosenServerId, userId).thenCompose(member -> { try { return self.createModMailThreadForUser(member, initialMessage, initialMessage.getChannel(), true, undoActions); } catch (Exception exception) { log.error("Setting up modmail thread for user {} in server {} failed.", userId, chosenServerId, exception); CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(exception); return future; } }).exceptionally(throwable -> { log.error("Failed to load member {} for modmail in server {}.", userId, chosenServerId, throwable); undoActionService.performActions(undoActions); return null; }); }) .build(); log.debug("Displaying server choice message for user {} in channel {}.", user.getId(), initialMessage.getChannel().getId()); menu.display(initialMessage.getChannel()); } else if(availableGuilds.size() == 1) { // if exactly one server is available, open the thread directly Long chosenServerId = choices.get(availableGuilds.get(0).getReactionEmote()); log.info("Only one server available to modmail. Directly opening modmail thread for user {} in server {}.", initialMessage.getAuthor().getId(), chosenServerId); memberService.getMemberInServerAsync(chosenServerId, initialMessage.getAuthor().getIdLong()).thenCompose(member -> { try { return self.createModMailThreadForUser(member, initialMessage, initialMessage.getChannel(), true, undoActions); } catch (Exception exception) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(exception); return future; } }).exceptionally(throwable -> { log.error("Failed to setup thread correctly", throwable); undoActionService.performActions(undoActions); return null; }); } else { log.info("No server available to open a modmail thread in."); // in case there is no server available, send an error message channelService.sendEmbedTemplateInMessageChannelList("modmail_no_server_available", new Object(), initialMessage.getChannel()); } } else { log.warn("User {} which was not known in any of the servers tried to contact the bot.", user.getId()); } } /** * Method used to send the header of a newly created mod mail thread. This message contains information about * the user which the thread is about * @param channel The {@link TextChannel} in which the mod mail thread is present in * @param member The {@link Member} which the {@link ModMailThread} is about */ private CompletableFuture<Void> sendModMailHeader(TextChannel channel, Member member) { log.debug("Sending modmail thread header for tread in channel {} on server {}.", channel.getIdLong(), channel.getGuild().getId()); AUserInAServer aUserInAServer = userInServerManagementService.loadOrCreateUser(member); ModMailThread latestThread = modMailThreadManagementService.getLatestModMailThread(aUserInAServer); List<ModMailThread> oldThreads = modMailThreadManagementService.getModMailThreadForUser(aUserInAServer); ModMailThreaderHeader header = ModMailThreaderHeader .builder() .member(member) .latestModMailThread(latestThread) .memberJoinDate(member.getTimeJoined().toInstant()) .pastModMailThreadCount((long)oldThreads.size()) .build(); List<CompletableFuture<Message>> messages = channelService.sendEmbedTemplateInTextChannelList("modmail_thread_header", header, channel); return CompletableFuture.allOf(messages.toArray(new CompletableFuture[0])); } @Override public CompletableFuture<Message> relayMessageToModMailThread(ModMailThread modMailThread, Message messageFromUser, List<UndoActionInstance> undoActions) { Long serverId = modMailThread.getServer().getId(); Long channelId = modMailThread.getChannel().getId(); Long modmailThreadId = modMailThread.getId(); metricService.incrementCounter(MDOMAIL_THREAD_MESSAGE_RECEIVED); log.debug("Relaying message {} to modmail thread {} for user {} to server {}.", messageFromUser.getId(), modMailThread.getId(), messageFromUser.getAuthor().getIdLong(), modMailThread.getServer().getId()); return memberService.getMemberInServerAsync(modMailThread.getServer().getId(), messageFromUser.getAuthor().getIdLong()).thenCompose(member -> self.relayMessage(messageFromUser, serverId, channelId, modmailThreadId, member) ); } @Transactional public CompletableFuture<Message> relayMessage(Message messageFromUser, Long serverId, Long channelId, Long modmailThreadId, Member member) { Optional<TextChannel> textChannelFromServer = channelService.getTextChannelFromServerOptional(serverId, channelId); if(textChannelFromServer.isPresent()) { TextChannel textChannel = textChannelFromServer.get(); return self.sendUserReply(textChannel, modmailThreadId, messageFromUser, member, true); } else { log.warn("Closing mod mail thread {}, because it seems the channel {} in server {} got deleted.", modmailThreadId, channelId, serverId); // in this case there was no text channel on the server associated with the mod mail thread // close the existing one, so the user can start a new one self.closeModMailThreadInDb(modmailThreadId); String textToSend = templateService.renderTemplate("modmail_failed_to_forward_message", new Object()); return channelService.sendTextToChannel(textToSend, messageFromUser.getChannel()); } } /** * This message takes a received {@link Message} from a user, renders it to a new message to send and sends it to * the appropriate {@link ModMailThread} channel, the returned promise only returns if the message was dealt with on the user * side. * @param textChannel The {@link TextChannel} in which the {@link ModMailThread} is being handled * @param modMailThreadId The id of the modmail thread to which the received {@link Message} is a reply to, can be null, if it is null, its the initial message * @param messageFromUser The received message from the user * @param member The {@link Member} instance from the user the thread is about. It is used as author * @param modMailThreadExists Whether or not the modmail thread already exists and is persisted. * @return A {@link CompletableFuture} which resolves when the post processing of the message is completed (adding read notification, and storing messageIDs) */ public CompletableFuture<Message> sendUserReply(TextChannel textChannel, Long modMailThreadId, Message messageFromUser, Member member, boolean modMailThreadExists) { List<CompletableFuture<Member>> subscriberMemberFutures = new ArrayList<>(); if(modMailThreadExists) { ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId); List<ModMailThreadSubscriber> subscriberList = modMailSubscriberManagementService.getSubscribersForThread(modMailThread); subscriberList.forEach(modMailThreadSubscriber -> subscriberMemberFutures.add(memberService.getMemberInServerAsync(modMailThreadSubscriber.getSubscriber())) ); if(subscriberList.isEmpty()) { subscriberMemberFutures.add(CompletableFuture.completedFuture(null)); } log.info("Mentioning {} subscribers for modmail thread {}.", subscriberList.size(), modMailThreadId); } else { subscriberMemberFutures.add(CompletableFuture.completedFuture(null)); log.info("Initial setup of modmail - not mentioning subscribers."); } CompletableFuture<Message> messageFuture = new CompletableFuture<>(); FutureUtils.toSingleFutureGeneric(subscriberMemberFutures).whenComplete((unused, throwable) -> { if(throwable != null) { log.warn("Failed to load subscriber users. Still relaying message.", throwable); } List<Member> subscribers = subscriberMemberFutures .stream() .filter(memberCompletableFuture -> !memberCompletableFuture.isCompletedExceptionally()) .map(CompletableFuture::join) .filter(Objects::nonNull) .collect(Collectors.toList()); ModMailUserReplyModel modMailUserReplyModel = ModMailUserReplyModel .builder() .postedMessage(messageFromUser) .member(member) .subscribers(subscribers) .build(); MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_user_message", modMailUserReplyModel, textChannel.getGuild().getIdLong()); List<CompletableFuture<Message>> completableFutures = channelService.sendMessageToSendToChannel(messageToSend, textChannel); CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])) .thenCompose(aVoid -> { log.debug("Adding read reaction to initial message for mod mail thread in channel {}.", textChannel.getGuild().getId()); return reactionService.addReactionToMessageAsync("readReaction", textChannel.getGuild().getIdLong(), messageFromUser); }) .thenApply(aVoid -> { Message createdMessage = completableFutures.get(0).join(); if(modMailThreadExists) { self.postProcessSendMessages(textChannel, createdMessage, messageFromUser); } return messageFuture.complete(createdMessage); }).exceptionally(throwable1 -> { log.error("Failed to forward message to thread.", throwable1); messageFuture.completeExceptionally(throwable1); return null; }); }).exceptionally(throwable -> { messageFuture.completeExceptionally(throwable); return null; }); return messageFuture; } /** * This message handles the post processing of the messages received by the user. This includes: saving the messageIDs * in the database, updating the state of the {@link ModMailThread} and adding the read reaction to the user message * @param textChannel The channel in which the message * @param messageInModMailThread The actual {@link Message} instance which was sent to the mod mail thread * @param messageFromUser The {@link Message} object which was sent from the user */ @Transactional public void postProcessSendMessages(TextChannel textChannel, Message messageInModMailThread, Message messageFromUser) { Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getByChannelIdOptional(textChannel.getIdLong()); if(modMailThreadOpt.isPresent()) { ModMailThread modMailThread = modMailThreadOpt.get(); log.debug("Adding created message {} based on messeage {} sent from user to modmail thread {} and setting status to {}.", messageInModMailThread.getId(), messageFromUser.getId(), modMailThread.getId(), ModMailThreadState.USER_REPLIED); modMailMessageManagementService.addMessageToThread(modMailThread, null, messageInModMailThread, messageFromUser, modMailThread.getUser(), false, false); // update the state of the thread modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.USER_REPLIED); } else { throw new ModMailThreadChannelNotFound(); } } @Override @Transactional public CompletableFuture<Void> loadExecutingMemberAndRelay(Long modmailThreadId, String text, Message replyCommandMessage, boolean anonymous, Member targetMember) { log.info("Relaying message {} to user {} in modmail thread {} on server {}.", replyCommandMessage.getId(), targetMember.getId(), modmailThreadId, targetMember.getGuild().getId()); return memberService.getMemberInServerAsync(replyCommandMessage.getGuild().getIdLong(), replyCommandMessage.getAuthor().getIdLong()) .thenCompose(executingMember -> self.relayMessageToDm(modmailThreadId, text, replyCommandMessage, anonymous, targetMember, executingMember)); } @Transactional public CompletableFuture<Void> relayMessageToDm(Long modmailThreadId, String text, Message replyCommandMessage, boolean anonymous, Member targetMember, Member executingMember) { metricService.incrementCounter(MDOMAIL_THREAD_MESSAGE_SENT); ModMailThread modMailThread = modMailThreadManagementService.getById(modmailThreadId); FullUserInServer fullThreadUser = FullUserInServer .builder() .aUserInAServer(modMailThread.getUser()) .member(targetMember) .build(); ModMailModeratorReplyModel.ModMailModeratorReplyModelBuilder modMailModeratorReplyModelBuilder = ModMailModeratorReplyModel .builder() .text(text) .modMailThread(modMailThread) .postedMessage(replyCommandMessage) .anonymous(anonymous) .threadUser(fullThreadUser); if(anonymous) { log.debug("Message is sent anonymous."); modMailModeratorReplyModelBuilder.moderator(memberService.getBotInGuild(modMailThread.getServer())); } else { modMailModeratorReplyModelBuilder.moderator(executingMember); } ModMailModeratorReplyModel modMailUserReplyModel = modMailModeratorReplyModelBuilder.build(); MessageToSend messageToSend = templateService.renderEmbedTemplate(MODMAIL_STAFF_MESSAGE_TEMPLATE_KEY, modMailUserReplyModel, modMailThread.getServer().getId()); CompletableFuture<Message> future = messageService.sendMessageToSendToUser(targetMember.getUser(), messageToSend); CompletableFuture<Message> sameThreadMessageFuture; if(featureModeService.featureModeActive(ModMailFeatureDefinition.MOD_MAIL, modMailThread.getServer(), ModMailMode.SEPARATE_MESSAGE)) { sameThreadMessageFuture = channelService.sendMessageEmbedToSendToAChannel(messageToSend, modMailThread.getChannel()).get(0); } else { sameThreadMessageFuture = CompletableFuture.completedFuture(null); } return CompletableFuture.allOf(future, sameThreadMessageFuture).thenAccept(avoid -> self.saveSendMessagesAndUpdateState(modmailThreadId, anonymous, future.join(), replyCommandMessage, sameThreadMessageFuture.join()) ); } @Override public CompletableFuture<Void> closeModMailThreadEvaluateLogging(ModMailThread modMailThread, ClosingContext closingConfig, List<UndoActionInstance> undoActions) { boolean loggingMode = featureModeService.featureModeActive(ModMailFeatureDefinition.MOD_MAIL, modMailThread.getServer(), ModMailMode.LOGGING); closingConfig.setLog(closingConfig.getLog() && loggingMode); return closeModMailThread(modMailThread, closingConfig, undoActions); } @Override public CompletableFuture<Void> closeModMailThread(ModMailThread modMailThread, ClosingContext closingConfig, List<UndoActionInstance> undoActions) { metricService.incrementCounter(MODMAIL_THREAD_CLOSED_COUNTER); Long modMailThreadId = modMailThread.getId(); log.info("Starting closing procedure for thread {}", modMailThread.getId()); List<ModMailMessage> modMailMessages = modMailThread.getMessages(); Long userId = modMailThread.getUser().getUserReference().getId(); Long serverId = modMailThread.getServer().getId(); if(closingConfig.getLog()) { if(!modMailMessages.isEmpty()) { return modMailMessageService.loadModMailMessages(modMailMessages) .thenAccept(loadedModmailThreadMessages -> self.logMessagesToModMailLog(closingConfig, modMailThreadId, undoActions, loadedModmailThreadMessages, serverId, userId)); } else { log.info("Modmail thread {} in server {} has no messages. Only logging header.", modMailThreadId, serverId); return loadUserAndSendClosingHeader(modMailThread, closingConfig) .thenAccept(unused -> memberService.getMemberInServerAsync(modMailThread.getUser()).thenCompose(member -> self.afterSuccessfulLog(modMailThreadId, closingConfig.getNotifyUser(), member, undoActions) )); } } else { log.debug("Not logging modmail thread {}.", modMailThreadId); return memberService.getMemberInServerAsync(modMailThread.getUser()).thenCompose(member -> self.afterSuccessfulLog(modMailThreadId, closingConfig.getNotifyUser(), member, undoActions) ); } } @Override public boolean isModMailThread(AChannel channel) { return modMailThreadManagementService.getByChannelOptional(channel).isPresent(); } @Override public boolean isModMailThread(Long channelId) { AChannel channel = channelManagementService.loadChannel(channelId); return isModMailThread(channel); } /** * This method takes the actively loaded futures, calls the method responsible for logging the messages, and calls the method * after the logging has been done. * @param modMailThreadId The ID of the {@link ModMailThread} which is being closed * @param undoActions The list of {@link UndoActionInstance} to execute in case of exceptions * @param messages The list of loaded {@link Message} to log * @param serverId The ID of the {@link Guild} the {@link ModMailThread} is in * @param userId The ID of the user the {@link ModMailThread} is about * @return A {@link CompletableFuture future} which completes when the messages have been logged */ @Transactional public CompletableFuture<Void> logMessagesToModMailLog(ClosingContext closingContext, Long modMailThreadId, List<UndoActionInstance> undoActions, ModmailLoggingThreadMessages messages, Long serverId, Long userId) { log.debug("Logging {} modmail messages for modmail thread {}.", messages.getMessages().size(), modMailThreadId); try { return self.logModMailThread(modMailThreadId, messages, closingContext, undoActions, serverId) .thenCompose(list -> list.getMainFuture().thenCompose(unused -> { list.getFutures().forEach(messageCompletableFuture -> { Message message = messageCompletableFuture.join(); if(message != null) { undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getGuild().getIdLong(), message.getChannel().getIdLong(), message.getIdLong())); } }); return memberService.getMemberInServerAsync(serverId, userId).thenCompose(member -> self.afterSuccessfulLog(modMailThreadId, closingContext.getNotifyUser(), member, undoActions) ).exceptionally(throwable -> { log.warn("Failed to retrieve member for closing the modmail thread. Closing without member information.", throwable); self.afterSuccessfulLog(modMailThreadId, false, null, undoActions); return null; }); })); } catch (Exception e) { log.error("Failed to log mod mail messages", e); throw new AbstractoRunTimeException(e); } } /** * This message is executed after the thread has been logged and notifies the user about the closed {@link ModMailThread} * which a configurable closing text. This method then calls the method to delete the channel. * @param modMailThreadId The ID of the {@link ModMailThread} which is being closed. * @param notifyUser Whether or not the user should be notified * @param undoActions The list of {@link UndoActionInstance} to execute in case of exceptions * @param modMailThreaduser The {@link Member member} for which the {@link ModMailThread thread} was for * @throws ModMailThreadNotFoundException in case the {@link ModMailThread} is not found by the ID * @return A {@link CompletableFuture future} which completes after the messages have been logged */ @Transactional public CompletableFuture<Void> afterSuccessfulLog(Long modMailThreadId, Boolean notifyUser, Member modMailThreaduser, List<UndoActionInstance> undoActions) { log.debug("Mod mail logging for thread {} has completed. Starting post logging activities.", modMailThreadId); Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getByIdOptional(modMailThreadId); if(modMailThreadOpt.isPresent()) { if(notifyUser) { log.info("Notifying user about the closed modmail thread {}.", modMailThreadId); ModMailThread modMailThread = modMailThreadOpt.get(); HashMap<String, String> closingMessage = new HashMap<>(); String defaultValue = templateService.renderSimpleTemplate("modmail_closing_user_message_description"); closingMessage.put("closingMessage", configService.getStringValue(MODMAIL_CLOSING_MESSAGE_TEXT, modMailThread.getServer().getId(), defaultValue)); return messageService.sendEmbedToUser(modMailThreaduser.getUser(), "modmail_closing_user_message", closingMessage).thenAccept(message -> self.deleteChannelAndClose(modMailThreadId, undoActions) ).exceptionally(throwable -> { self.deleteChannelAndClose(modMailThreadId, undoActions); return null; }); } else { log.info("NOT Notifying user about the closed modmail thread {}.", modMailThreadId); return deleteChannelAndClose(modMailThreadId, undoActions); } } else { throw new ModMailThreadNotFoundException(modMailThreadId); } } /** * Deletes the actual {@link MessageChannel} in which the {@link ModMailThread} happened. This method then calls the * method to update the stats in the database * @param modMailThreadId The ID of the {@link ModMailThread} to delete the {@link MessageChannel} from * @param undoActions The list of {@link UndoActionInstance} to execute in case of exceptions * @throws ModMailThreadNotFoundException in case the {@link ModMailThread} is not found by the ID * @return A {@link CompletableFuture future} which completes after the {@link TextChannel channel} in which the thread was has been deleted */ @Transactional public CompletableFuture<Void> deleteChannelAndClose(Long modMailThreadId, List<UndoActionInstance> undoActions) { Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getByIdOptional(modMailThreadId); if(modMailThreadOpt.isPresent()) { ModMailThread modMailThread = modMailThreadOpt.get(); String failureMessage = "Failed to delete text channel containing mod mail thread {}"; try { log.debug("Deleting channel {} which contained the modmail thread {}.", modMailThread.getChannel().getId(), modMailThreadId); return channelService.deleteTextChannel(modMailThread.getChannel()).thenAccept(avoid -> { undoActions.clear(); self.closeModMailThreadInDb(modMailThreadId); }); } catch (InsufficientPermissionException ex) { log.error(failureMessage, modMailThreadId, ex); String message = "Failed To delete mod mail thread channel because no permissions."; throw new AbstractoTemplatedException(message, "modmail_exception_cannot_delete_channel", ex); } catch (Exception ex) { log.error(failureMessage, modMailThreadId, ex); throw new AbstractoRunTimeException(ex); } } else { throw new ModMailThreadNotFoundException(modMailThreadId); } } /** * Takes the list of {@link CompletableFuture} which are returned from retrieving the {@link Message} to log, * and creates the models necessary to render the log entries. This message also sends the closing header in the * log concerning general information about the closed {@link ModMailThread} * @param modMailThreadId The ID of the {@link ModMailThread} to log the messages of * @param messages The list of {@link CompletableFuture} which contain the {@link Message} which could be loaded * @param undoActions A list of {@link dev.sheldan.abstracto.core.models.UndoAction actions} to be undone in case the operation fails. This list will be filled in the method. * @param serverId The ID of the {@link Guild server} the modmail thread is in * @throws ModMailThreadNotFoundException in case the {@link ModMailThread} is not found by the ID * @return An instance of {@link CompletableFutureList}, which contains a main {@link CompletableFuture} which is resolved, * when all of the smaller {@link CompletableFuture} in it are resolved. We need this construct, because we need to access * the result values of the individual futures after they are done. */ @Transactional public CompletableFuture<CompletableFutureList<Message>> logModMailThread(Long modMailThreadId, ModmailLoggingThreadMessages messages, ClosingContext context, List<UndoActionInstance> undoActions, Long serverId) { log.info("Logging mod mail thread {} with {} messages.", modMailThreadId, messages.getMessages().size()); if(messages.getMessages().isEmpty()) { log.info("Modmail thread {} is empty. No messages to log.", modMailThreadId); return CompletableFuture.completedFuture(new CompletableFutureList<>(new ArrayList<>())); } TextChannel channel = channelService.getTextChannelFromServer(serverId, modMailThreadId); ClosingProgressModel progressModel = ClosingProgressModel .builder() .loggedMessages(0) .totalMessages(messages.getMessages().size()) .build(); List<CompletableFuture<Message>> updateMessageFutures = channelService.sendEmbedTemplateInTextChannelList(MODMAIL_CLOSE_PROGRESS_TEMPLATE_KEY, progressModel, channel); return FutureUtils.toSingleFutureGeneric(updateMessageFutures) .thenCompose(updateMessage -> self.logMessages(modMailThreadId, messages, context, updateMessageFutures.get(0).join())); } @Transactional public CompletableFuture<CompletableFutureList<Message>> logMessages(Long modMailThreadId, ModmailLoggingThreadMessages messages, ClosingContext context, Message updateMessage) { Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getByIdOptional(modMailThreadId); if(modMailThreadOpt.isPresent()) { ModMailThread modMailThread = modMailThreadOpt.get(); List<ModMailLoggedMessageModel> loggedMessages = new ArrayList<>(); Map<Long, User> authors = messages .getAuthors() .stream().collect(Collectors.toMap(ISnowflake::getIdLong, Function.identity())); messages.getMessages().forEach(message -> { log.info("Logging message {} in modmail thread {}.", message.getId(), modMailThreadId); ModMailMessage modmailMessage = modMailThread.getMessages() .stream() .filter(modMailMessage -> { if(modMailMessage.getDmChannel()) { return modMailMessage.getCreatedMessageInDM().equals(message.getIdLong()); } else { return modMailMessage.getCreatedMessageInChannel().equals(message.getIdLong()); } }) .findFirst().orElseThrow(() -> new AbstractoRunTimeException("Could not find desired message in list of messages in thread. This should not happen, as we just retrieved them from the same place.")); User author = authors.getOrDefault(modmailMessage.getAuthor().getUserReference().getId(), message.getJDA().getSelfUser()); ModMailLoggedMessageModel modMailLoggedMessageModel = ModMailLoggedMessageModel .builder() .message(message) .author(author) .modMailMessage(modmailMessage) .build(); loggedMessages.add(modMailLoggedMessageModel); }); List<CompletableFuture<Message>> completableFutures = new ArrayList<>(); log.debug("Sending close header and individual mod mail messages to mod mail log target for thread {}.", modMailThreadId); CompletableFuture<Message> headerFuture = loadUserAndSendClosingHeader(modMailThread, context); completableFutures.add(headerFuture); return headerFuture.thenApply(message -> { completableFutures.addAll(self.sendMessagesToPostTarget(modMailThreadId, loggedMessages, updateMessage)); return new CompletableFutureList<>(completableFutures); }); } else { throw new ModMailThreadNotFoundException(modMailThreadId); } } private CompletableFuture<Message> loadUserAndSendClosingHeader(ModMailThread modMailThread, ClosingContext closingContext) { ModMailClosingHeaderModel headerModel = ModMailClosingHeaderModel .builder() .closingMember(closingContext.getClosingMember()) .note(closingContext.getNote()) .silently(!closingContext.getNotifyUser()) .messageCount(modMailThread.getMessages().size()) .startDate(modMailThread.getCreated()) .serverId(modMailThread.getServer().getId()) .userId(modMailThread.getUser().getUserReference().getId()) .build(); return userService.retrieveUserForId(modMailThread.getUser().getUserReference().getId()).thenApply(user -> { headerModel.setUser(user); return self.sendClosingHeader(headerModel).get(0); }).thenCompose(Function.identity()); } @Transactional public List<CompletableFuture<Message>> sendClosingHeader(ModMailClosingHeaderModel model) { MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_close_header", model, model.getServerId()); return postTargetService.sendEmbedInPostTarget(messageToSend, ModMailPostTargets.MOD_MAIL_LOG, model.getServerId()); } /** * Sets the {@link ModMailThread} in the database to CLOSED. * @param modMailThreadId The ID of the {@link ModMailThread} to update the state of * @throws ModMailThreadNotFoundException in case the {@link ModMailThread} is not found by the ID */ @Transactional public void closeModMailThreadInDb(Long modMailThreadId) { Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getByIdOptional(modMailThreadId); if(modMailThreadOpt.isPresent()) { ModMailThread modMailThread = modMailThreadOpt.get(); log.info("Setting thread {} to closed in db.", modMailThread.getId()); modMailThread.setClosed(Instant.now()); modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.CLOSED); } else { throw new ModMailThreadNotFoundException(modMailThreadId); } } /** * Renders the retrieved {@link Message} which are in {@link ModMailLoggedMessageModel} into {@link MessageToSend} and * sends this to the appropriate logging {@link PostTarget} * @param modMailThreadId The ID of {@link ModMailThread} to which the loaded messages belong to * @param loadedMessages The list of {@link ModMailLoggedMessageModel} which can be rendered * @return A list of {@link CompletableFuture} which represent each of the messages being send to the {@link PostTarget} */ public List<CompletableFuture<Message>> sendMessagesToPostTarget(Long modMailThreadId, List<ModMailLoggedMessageModel> loadedMessages, Message updateMessage) { List<CompletableFuture<Message>> messageFutures = new ArrayList<>(); ClosingProgressModel progressModel = ClosingProgressModel .builder() .loggedMessages(0) .totalMessages(loadedMessages.size()) .build(); loadedMessages = loadedMessages.stream().sorted(Comparator.comparing(o -> o.getMessage().getTimeCreated())).collect(Collectors.toList()); for (int i = 0; i < loadedMessages.size(); i++) { ModMailLoggedMessageModel message = loadedMessages.get(i); log.debug("Sending message {} of modmail thread {} to modmail log post target.", modMailThreadId, message.getMessage().getId()); MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_close_logged_message", message, updateMessage.getGuild().getIdLong()); List<CompletableFuture<Message>> logFuture = postTargetService.sendEmbedInPostTarget(messageToSend, ModMailPostTargets.MOD_MAIL_LOG, updateMessage.getGuild().getIdLong()); if(i != 0 && (i % 10) == 0) { progressModel.setLoggedMessages(i); messageService.editMessageWithNewTemplate(updateMessage, MODMAIL_CLOSE_PROGRESS_TEMPLATE_KEY, progressModel); } messageFutures.addAll(logFuture); } return messageFutures; } /** * Evaluates the promises which were created when sending the messages to the private channel and stores the message IDs * and updates the state of the {@link ModMailThread}. * @param modMailThreadId The ID of the {@link ModMailThread} for which the messages were sent for * @param anonymous Whether or not the messages were send anonymous * @param createdMessageInDM The {@link Message message} which was sent to the private channel with the {@link User user} * @param modMailThreadMessage The {@link Message message} which was sent in the channel representing the {@link ModMailThread thread}. Might be null. * @param replyCommandMessage The {@link Message message} which contained the command used to reply to the user * @throws ModMailThreadNotFoundException in case the {@link ModMailThread} is not found by the ID */ @Transactional public void saveSendMessagesAndUpdateState(Long modMailThreadId, Boolean anonymous, Message createdMessageInDM, Message replyCommandMessage, Message modMailThreadMessage) { Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getByIdOptional(modMailThreadId); AUserInAServer moderator = userInServerManagementService.loadOrCreateUser(replyCommandMessage.getMember()); if(modMailThreadOpt.isPresent()) { ModMailThread modMailThread = modMailThreadOpt.get(); log.debug("Adding (anonymous: {}) message {} of moderator to modmail thread {} and setting state to {}.", anonymous, createdMessageInDM.getId(), modMailThreadId, ModMailThreadState.MOD_REPLIED); modMailMessageManagementService.addMessageToThread(modMailThread, createdMessageInDM, modMailThreadMessage, replyCommandMessage, moderator, anonymous, true); modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.MOD_REPLIED); } else { throw new ModMailThreadNotFoundException(modMailThreadId); } } @PostConstruct public void postConstruct() { metricService.registerCounter(MODMAIL_THREAD_CREATED_COUNTER, "Mod mail threads created"); metricService.registerCounter(MODMAIL_THREAD_CLOSED_COUNTER, "Mod mail threads closed"); metricService.registerCounter(MDOMAIL_THREAD_MESSAGE_RECEIVED, "Mod mail messages received"); metricService.registerCounter(MDOMAIL_THREAD_MESSAGE_SENT, "Mod mail messages sent"); } }
package org.onosproject.security.impl; import org.apache.commons.collections.FastHashMap; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Deactivate; import org.apache.karaf.features.BundleInfo; import org.apache.karaf.features.Feature; import org.apache.karaf.features.FeaturesService; import org.onosproject.app.ApplicationAdminService; import org.onosproject.app.ApplicationEvent; import org.onosproject.app.ApplicationListener; import org.onosproject.app.ApplicationState; import org.onosproject.core.Application; import org.onosproject.core.ApplicationId; import org.onosproject.core.Permission; import org.onosproject.security.AppPermission; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.PackagePermission; import org.osgi.framework.ServicePermission; import org.osgi.service.log.LogEntry; import org.osgi.service.log.LogListener; import org.osgi.service.log.LogReaderService; import org.osgi.service.permissionadmin.PermissionInfo; import java.security.AccessControlException; import java.security.AllPermission; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.osgi.service.permissionadmin.PermissionAdmin; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; /** * Security-Mode ONOS management implementation. */ //TODO : implement a dedicated distributed store for SM-ONOS @Component(immediate = true) public class SecurityModeManager { @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ApplicationAdminService appAdminService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected FeaturesService featuresService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected LogReaderService logReaderService; private final Logger log = getLogger(getClass()); private SecurityBundleListener securityBundleListener = new SecurityBundleListener(); private SecurityApplicationListener securityApplicationListener = new SecurityApplicationListener(); private SecurityLogListener securityLogListener = new SecurityLogListener(); private Bundle bundle = null; private BundleContext bundleContext = null; private PermissionAdmin permissionAdmin = null; private HashMap<String, ApplicationId> appTracker = null; private HashMap<Permission, Set<String>> serviceDirectory = null; @Activate public void activate() { if (System.getSecurityManager() == null) { log.warn("J2EE security manager is disabled."); deactivate(); return; } bundle = FrameworkUtil.getBundle(this.getClass()); bundleContext = bundle.getBundleContext(); bundleContext.addBundleListener(securityBundleListener); appAdminService.addListener(securityApplicationListener); logReaderService.addLogListener(securityLogListener); appTracker = new FastHashMap(); permissionAdmin = getPermissionAdmin(bundleContext); if (permissionAdmin == null) { log.warn("Permission Admin not found."); this.deactivate(); return; } serviceDirectory = PolicyBuilder.getServiceDirectory(); PermissionInfo[] allPerm = { new PermissionInfo(AllPermission.class.getName(), "", ""), }; permissionAdmin.setPermissions(bundle.getLocation(), allPerm); log.warn("Security-Mode Started"); } @Deactivate public void deactivate() { bundleContext.removeBundleListener(securityBundleListener); appAdminService.removeListener(securityApplicationListener); logReaderService.removeLogListener(securityLogListener); log.info("Stopped"); } private class SecurityApplicationListener implements ApplicationListener { @Override public void event(ApplicationEvent event) { //App needs to be restarted if (event.type() == ApplicationEvent.Type.APP_PERMISSIONS_CHANGED) { if (appAdminService.getState(event.subject().id()) == ApplicationState.ACTIVE) { appAdminService.deactivate(event.subject().id()); print("Permissions updated (%s). Deactivating...", event.subject().id().name()); } } } } private class SecurityBundleListener implements BundleListener { @Override public void bundleChanged(BundleEvent event) { switch (event.getType()) { case BundleEvent.INSTALLED: setPermissions(event); break; case BundleEvent.UNINSTALLED: clearPermissions(event); break; default: break; } } } private void clearPermissions(BundleEvent bundleEvent) { if (appTracker.containsKey(bundleEvent.getBundle().getLocation())) { permissionAdmin.setPermissions(bundleEvent.getBundle().getLocation(), new PermissionInfo[]{}); appTracker.remove(bundleEvent.getBundle().getLocation()); } } // find the location of the installed bundle and enforce policy private void setPermissions(BundleEvent bundleEvent) { for (Application app : appAdminService.getApplications()) { if (getBundleLocations(app).contains(bundleEvent.getBundle().getLocation())) { String location = bundleEvent.getBundle().getLocation(); Set<org.onosproject.core.Permission> permissions = appAdminService.getPermissions(app.id()); //Permissions granted by user overrides the permissions specified in App.Xml file if (permissions == null) { permissions = app.permissions(); } if (permissions.isEmpty()) { print("Application %s has not been granted any permission.", app.id().name()); } PermissionInfo[] perms = null; switch (app.role()) { case ADMIN: perms = PolicyBuilder.getAdminApplicationPermissions(serviceDirectory); break; case REGULAR: perms = PolicyBuilder.getApplicationPermissions(serviceDirectory, permissions); break; case UNSPECIFIED: default: //no role has been assigned. perms = PolicyBuilder.getDefaultPerms(); log.warn("Application %s has no role assigned.", app.id().name()); break; } permissionAdmin.setPermissions(location, perms); appTracker.put(location, app.id()); break; } } } //TODO: dispatch security policy violation event via distributed store //immediately notify and deactivate the application upon policy violation private class SecurityLogListener implements LogListener { @Override public void logged(LogEntry entry) { if (entry != null) { if (entry.getException() != null) { ApplicationId applicationId = appTracker.get(entry.getBundle().getLocation()); if (applicationId != null) { if (appAdminService.getState(applicationId).equals(ApplicationState.ACTIVE)) { if (entry.getException() instanceof AccessControlException) { java.security.Permission permission = ((AccessControlException) entry.getException()).getPermission(); handleException(applicationId.name(), permission); appAdminService.deactivate(applicationId); } } } } } } } private void handleException(String name, java.security.Permission perm) { if (perm instanceof ServicePermission || perm instanceof PackagePermission) { print("%s has attempted to %s %s.", name, perm.getActions(), perm.getName()); } else if (perm instanceof AppPermission) { print("%s has attempted to call an NB API that requires %s permission.", name, perm.getName().toUpperCase()); } else { print("%s has attempted to perform an action that requires %s", name, perm.toString()); } print("POLICY VIOLATION: Deactivating %s.", name); } private void print(String format, Object... args) { System.out.println(String.format("SM-ONOS: " + format, args)); log.warn(String.format(format, args)); } private List<String> getBundleLocations(Application app) { List<String> locations = new ArrayList(); for (String name : app.features()) { try { Feature feature = featuresService.getFeature(name); locations.addAll( feature.getBundles().stream().map(BundleInfo::getLocation).collect(Collectors.toList())); } catch (Exception e) { return locations; } } return locations; } private PermissionAdmin getPermissionAdmin(BundleContext context) { return (PermissionAdmin) context.getService(context.getServiceReference(PermissionAdmin.class.getName())); } }
package mage.cards.a; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.DiesSourceTriggeredAbility; import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.continuous.GainControlTargetEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.SubType; import mage.filter.StaticFilters; import mage.game.Game; import mage.game.permanent.Permanent; import mage.target.targetpointer.FixedTarget; import java.util.UUID; /** * * @author nick.myers */ public final class AuraThief extends CardImpl { public AuraThief(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{U}"); this.subtype.add(SubType.ILLUSION); this.power = new MageInt(2); this.toughness = new MageInt(2); // Flying this.addAbility(FlyingAbility.getInstance()); // When Aura Thief dies, you gain control of all enchantments. You don't get // to move Auras. this.addAbility(new DiesSourceTriggeredAbility(new AuraThiefDiesTriggeredEffect())); } private AuraThief(final AuraThief card) { super(card); } @Override public AuraThief copy() { return new AuraThief(this); } } class AuraThiefDiesTriggeredEffect extends OneShotEffect { public AuraThiefDiesTriggeredEffect() { super(Outcome.Benefit); this.staticText = "gain control of all enchantments. <i>(You don't get to move Auras.)</i>"; } public AuraThiefDiesTriggeredEffect(final AuraThiefDiesTriggeredEffect effect) { super(effect); } @Override public AuraThiefDiesTriggeredEffect copy() { return new AuraThiefDiesTriggeredEffect(this); } @Override public boolean apply(Game game, Ability source) { boolean ret = false; for(Permanent enchantment : game.getBattlefield().getActivePermanents(StaticFilters.FILTER_PERMANENT_ENCHANTMENT, source.getControllerId(), source.getControllerId(), game)) { ContinuousEffect gainControl = new GainControlTargetEffect(Duration.EndOfGame); gainControl.setTargetPointer(new FixedTarget(enchantment.getId(), game)); game.addEffect(gainControl, source); ret = true; } return ret; } }
package cn.iocoder.yudao.adminserver.modules.system.service.user; import cn.hutool.core.collection.CollUtil; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.profile.SysUserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.profile.SysUserProfileUpdateReqVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.user.SysUserCreateReqVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.user.SysUserExportReqVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.user.SysUserImportExcelVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.user.SysUserImportRespVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.user.SysUserPageReqVO; import cn.iocoder.yudao.adminserver.modules.system.controller.user.vo.user.SysUserUpdateReqVO; import cn.iocoder.yudao.adminserver.modules.system.dal.dataobject.user.SysUserDO; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户 Service 接口 * * @author 芋道源码 */ public interface SysUserService { /** * 创建用户 * * @param reqVO 用户信息 * @return 用户编号 */ Long createUser(SysUserCreateReqVO reqVO); /** * 修改用户 * * @param reqVO 用户信息 */ void updateUser(SysUserUpdateReqVO reqVO); /** * 修改用户个人信息 * * @param id 用户编号 * @param reqVO 用户个人信息 */ void updateUserProfile(Long id, SysUserProfileUpdateReqVO reqVO); /** * 修改用户个人密码 * * @param id 用户编号 * @param reqVO 更新用户个人密码 */ void updateUserPassword(Long id, SysUserProfileUpdatePasswordReqVO reqVO); /** * 更新用户头像 * * @param id 用户 id * @param avatarFile 头像文件 */ String updateUserAvatar(Long id, InputStream avatarFile); /** * 修改密码 * * @param id 用户编号 * @param password 密码 */ void updateUserPassword(Long id, String password); /** * 修改状态 * * @param id 用户编号 * @param status 状态 */ void updateUserStatus(Long id, Integer status); /** * 删除用户 * * @param id 用户编号 */ void deleteUser(Long id); /** * 通过用户名查询用户 * * @param username 用户名 * @return 用户对象信息 */ SysUserDO getUserByUsername(String username); /** * 通过用户 ID 查询用户 * * @param id 用户ID * @return 用户对象信息 */ SysUserDO getUser(Long id); /** * 获得用户分页列表 * * @param reqVO 分页条件 * @return 分页列表 */ PageResult<SysUserDO> getUserPage(SysUserPageReqVO reqVO); /** * 获得用户列表 * * @param reqVO 列表请求 * @return 用户列表 */ List<SysUserDO> getUsers(SysUserExportReqVO reqVO); /** * 获得用户列表 * * @param ids 用户编号数组 * @return 用户列表 */ List<SysUserDO> getUsers(Collection<Long> ids); /** * 获得用户 Map * * @param ids 用户编号数组 * @return 用户 Map */ default Map<Long, SysUserDO> getUserMap(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return new HashMap<>(); } return CollectionUtils.convertMap(getUsers(ids), SysUserDO::getId); } /** * 获得用户列表,基于昵称模糊匹配 * * @param nickname 昵称 * @return 用户列表 */ List<SysUserDO> getUsersByNickname(String nickname); /** * 获得用户列表,基于用户账号模糊匹配 * * @param username 用户账号 * @return 用户列表 */ List<SysUserDO> getUsersByUsername(String username); /** * 批量导入用户 * * @param importUsers 导入用户列表 * @param isUpdateSupport 是否支持更新 * @return 导入结果 */ SysUserImportRespVO importUsers(List<SysUserImportExcelVO> importUsers, boolean isUpdateSupport); }
/* * nimbus-jose-jwt * * Copyright 2012-2016, Connect2id Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.nimbusds.jwt; import java.net.URI; import java.text.ParseException; import java.util.*; import com.nimbusds.jose.util.Base64URL; import junit.framework.TestCase; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; /** * Tests JWT claims set serialisation and parsing. * * @author Vladimir Dzhuvinov * @author Justin Richer * @version 2018-08-23 */ public class JWTClaimsSetTest extends TestCase { public void testReservedNames() { Set<String> names = JWTClaimsSet.getRegisteredNames(); assertTrue(names.contains("iss")); assertTrue(names.contains("sub")); assertTrue(names.contains("aud")); assertTrue(names.contains("exp")); assertTrue(names.contains("nbf")); assertTrue(names.contains("iat")); assertTrue(names.contains("jti")); assertEquals(7, names.size()); } public void testRun() { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); // JWT time claim precision is seconds final Date NOW = new Date(new Date().getTime() / 1000 * 1000); // iss assertNull("iss init check", builder.build().getIssuer()); builder.issuer("http://issuer.com"); assertEquals("iss set check", "http://issuer.com", builder.build().getIssuer()); // sub assertNull("sub init check", builder.build().getSubject()); builder.subject("http://subject.com"); assertEquals("sub set check", "http://subject.com", builder.build().getSubject()); // aud assertTrue("aud init check", builder.build().getAudience().isEmpty()); builder.audience(Collections.singletonList("http://audience.com")); assertEquals("aud set check", "http://audience.com", builder.build().getAudience().get(0)); // exp assertNull("exp init check", builder.build().getExpirationTime()); builder.expirationTime(NOW); assertEquals("exp set check", NOW, builder.build().getExpirationTime()); // nbf assertNull("nbf init check", builder.build().getNotBeforeTime()); builder.notBeforeTime(NOW); assertEquals("nbf set check", NOW, builder.build().getNotBeforeTime()); // iat assertNull("iat init check", builder.build().getIssueTime()); builder.issueTime(NOW); assertEquals("iat set check", NOW, builder.build().getIssueTime()); // jti assertNull("jti init check", builder.build().getJWTID()); builder.jwtID("123"); assertEquals("jti set check", "123", builder.build().getJWTID()); // no custom claims assertEquals(7, builder.build().getClaims().size()); // x-custom builder.claim("x-custom", "abc"); assertEquals("abc", (String) builder.build().getClaim("x-custom")); // serialise JSONObject json = builder.build().toJSONObject(); assertEquals(8, json.size()); // parse back JWTClaimsSet claimsSet = null; try { claimsSet = JWTClaimsSet.parse(json); } catch (java.text.ParseException e) { fail(e.getMessage()); } assertEquals("iss parse check", "http://issuer.com", claimsSet.getIssuer()); assertEquals("sub parse check", "http://subject.com", claimsSet.getSubject()); assertEquals("aud parse check", "http://audience.com", claimsSet.getAudience().get(0)); assertEquals("exp parse check", NOW, claimsSet.getExpirationTime()); assertEquals("nbf parse check", NOW, claimsSet.getNotBeforeTime()); assertEquals("iat parse check", NOW, claimsSet.getIssueTime()); assertEquals("jti parse check", "123", claimsSet.getJWTID()); assertEquals("abc", (String)claimsSet.getClaim("x-custom")); assertEquals(8, claimsSet.getClaims().size()); Map<String,Object> all = claimsSet.getClaims(); assertEquals("iss parse check map", "http://issuer.com", (String)all.get("iss")); assertEquals("sub parse check map", "http://subject.com", (String)all.get("sub")); assertEquals("aud parse check map", "http://audience.com", (String)((List)all.get("aud")).get(0)); assertEquals("exp parse check map", NOW, all.get("exp")); assertEquals("nbf parse check map", NOW, all.get("nbf")); assertEquals("iat parse check map", NOW, all.get("iat")); assertEquals("jti parse check map", "123", (String)all.get("jti")); assertEquals("abc", (String)all.get("x-custom")); } public void testDateConversion() { final Date ONE_MIN_AFTER_EPOCH = new Date(1000*60); JWTClaimsSet cs = new JWTClaimsSet.Builder() .issueTime(ONE_MIN_AFTER_EPOCH) .notBeforeTime(ONE_MIN_AFTER_EPOCH) .expirationTime(ONE_MIN_AFTER_EPOCH) .build(); JSONObject json = cs.toJSONObject(); assertEquals(new Long(60L), json.get("iat")); assertEquals(new Long(60L), json.get("nbf")); assertEquals(new Long(60L), json.get("exp")); } public void testCustomClaim() { JWTClaimsSet cs = new JWTClaimsSet.Builder().claim("locale", "bg-BG").build(); assertEquals(1, cs.getClaims().size()); cs = new JWTClaimsSet.Builder().claim("locale", null).build(); assertNull(cs.getClaim("locale")); assertEquals(1, cs.getClaims().size()); } public void testNullCustomClaim() { JWTClaimsSet cs = new JWTClaimsSet.Builder().claim("locale", null).build(); assertNull(cs.getClaim("locale")); assertEquals(1, cs.getClaims().size()); } public void testSetCustomClaims() { JWTClaimsSet cs = new JWTClaimsSet.Builder() .claim("locale", "bg-BG") .claim("locale", "es-ES") .claim("ip", "127.0.0.1") .build(); assertEquals(2, cs.getClaims().size()); assertEquals("es-ES", (String)cs.getClaims().get("locale")); assertEquals("127.0.0.1", (String)cs.getClaims().get("ip")); } public void testGetClaimValueNotSpecified() { JWTClaimsSet cs = new JWTClaimsSet.Builder().build(); assertNull(cs.getClaim("xyz")); } public void testSetClaimNull() { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); builder.issuer("http://example.com"); assertEquals("http://example.com", builder.build().getIssuer()); builder = builder.claim("iss", null); assertNull(builder.build().getIssuer()); builder.subject("alice"); assertEquals("alice", builder.build().getSubject()); builder.claim("sub", null); assertNull(builder.build().getSubject()); List<String> audList = new ArrayList<>(); audList.add("http://client.example.com"); builder.audience(audList); assertEquals("http://client.example.com", builder.build().getAudience().get(0)); builder = builder.claim("aud", null); assertTrue(builder.build().getAudience().isEmpty()); Date now = new Date(); builder.expirationTime(now); assertEquals(now, builder.build().getExpirationTime()); builder = builder.claim("exp", null); assertNull(builder.build().getExpirationTime()); builder.notBeforeTime(now); assertEquals(now, builder.build().getNotBeforeTime()); builder = builder.claim("nbf", null); assertNull(builder.build().getNotBeforeTime()); builder.issueTime(now); assertEquals(now, builder.build().getIssueTime()); builder = builder.claim("iat", null); assertNull(builder.build().getIssueTime()); builder.jwtID("123"); assertEquals("123", builder.build().getJWTID()); builder = builder.claim("jti", null); assertNull(builder.build().getJWTID()); } public void testGetClaimTyped() throws Exception { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); builder.claim("string", "abc"); assertEquals("abc", builder.build().getStringClaim("string")); builder.claim("boolean", false); assertFalse(builder.build().getBooleanClaim("boolean")); builder.claim("integer", 123); assertEquals(123, builder.build().getIntegerClaim("integer").intValue()); builder.claim("long", 456L); assertEquals(456L, builder.build().getLongClaim("long").longValue()); Date date = new Date(999000L); builder.claim("date", date); assertEquals(date, builder.build().getDateClaim("date")); // Convert Unix timestamp to Java date builder.claim("date-long", 999L); assertEquals(new Date(999000L), builder.build().getDateClaim("date-long")); builder.claim("float", 3.14f); assertEquals(3.14f, builder.build().getFloatClaim("float").floatValue()); builder.claim("double", 3.14d); assertEquals(3.14d, builder.build().getDoubleClaim("double").doubleValue()); } public void testGetClaimTypedNull() throws Exception { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); builder.claim("string", null); assertNull(builder.build().getStringClaim("string")); builder.claim("boolean", null); assertNull(builder.build().getBooleanClaim("boolean")); builder.claim("integer", null); assertNull(builder.build().getIntegerClaim("integer")); builder.claim("long", null); assertNull(builder.build().getLongClaim("long")); builder.claim("date", null); assertNull(builder.build().getDateClaim("date")); builder.claim("float", null); assertNull(builder.build().getFloatClaim("float")); builder.claim("double", null); assertNull(builder.build().getDoubleClaim("double")); } public void testGetClaimTypedParseException() { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); builder.claim("string", 3.14); try { builder.build().getStringClaim("string"); fail("Failed to raise exception"); } catch (ParseException e) { // ok } builder.claim("boolean", "123"); try { builder.build().getBooleanClaim("boolean"); fail("Failed to raise exception"); } catch (ParseException e) { // ok } builder.claim("integer", true); try { builder.build().getIntegerClaim("integer"); fail(); } catch (ParseException e) { // ok } builder.claim("long", "abc"); try { builder.build().getLongClaim("long"); fail(); } catch (ParseException e) { // ok } builder.claim("date", "abc"); try { builder.build().getDateClaim("date"); fail(); } catch (ParseException e) { // ok } builder.claim("float", true); try { builder.build().getFloatClaim("float"); fail("Failed to raise exception"); } catch (ParseException e) { // ok } builder.claim("double", "abc"); try { builder.build().getDoubleClaim("double"); fail("Failed to raise exception"); } catch (ParseException e) { // ok } } public void testStringAudience() throws Exception { JSONObject o = new JSONObject(); o.put("aud", "http://example.com"); JWTClaimsSet jwtClaimsSet = JWTClaimsSet.parse(o.toJSONString()); assertEquals("http://example.com", jwtClaimsSet.getAudience().get(0)); assertEquals(1, jwtClaimsSet.getAudience().size()); } public void testStringArrayAudience() throws Exception { JSONObject o = new JSONObject(); o.put("aud", Collections.singletonList("http://example.com")); JWTClaimsSet jwtClaimsSet = JWTClaimsSet.parse(o.toJSONString()); assertEquals("http://example.com", jwtClaimsSet.getAudience().get(0)); assertEquals(1, jwtClaimsSet.getAudience().size()); } public void testStringArrayMultipleAudience() throws Exception { JSONObject o = new JSONObject(); o.put("aud", Arrays.asList("http://example.com", "http://example2.com")); JWTClaimsSet jwtClaimsSet = JWTClaimsSet.parse(o.toJSONString()); assertEquals("http://example.com", jwtClaimsSet.getAudience().get(0)); assertEquals("http://example2.com", jwtClaimsSet.getAudience().get(1)); assertEquals(2, jwtClaimsSet.getAudience().size()); } public void testParseExampleIDToken() throws Exception { String json = "{\"exp\":1384798159,\"sub\":\"alice\",\"aud\":[\"000001\"],\"iss\":\"https:\\/\\/localhost:8080\\/c2id\",\"login_geo\":{\"long\":\"37.3956\",\"lat\":\"-122.076\"},\"login_ip\":\"185.7.248.1\",\"iat\":1384797259,\"acr\":\"urn:mace:incommon:iap:silver\",\"c_hash\":\"vwVj99I7FizReIt5q3UwhQ\",\"amr\":[\"mfa\"]}"; JWTClaimsSet claimsSet = JWTClaimsSet.parse(json); assertEquals(1384798159L, claimsSet.getExpirationTime().getTime() / 1000); assertEquals(1384797259L, claimsSet.getIssueTime().getTime() / 1000); assertEquals("alice", claimsSet.getSubject()); assertEquals("000001", claimsSet.getAudience().get(0)); assertEquals(1, claimsSet.getAudience().size()); assertEquals("https://localhost:8080/c2id", claimsSet.getIssuer()); assertEquals("urn:mace:incommon:iap:silver", claimsSet.getStringClaim("acr")); assertEquals("vwVj99I7FizReIt5q3UwhQ", claimsSet.getStringClaim("c_hash")); assertEquals("mfa", ((List<String>)claimsSet.getClaim("amr")).get(0)); assertEquals(1, ((List<String>)claimsSet.getClaim("amr")).size()); assertEquals("185.7.248.1", claimsSet.getStringClaim("login_ip")); JSONObject geoLoc = (JSONObject)claimsSet.getClaim("login_geo"); // {"long":"37.3956","lat":"-122.076"} assertEquals("37.3956", (String)geoLoc.get("long")); assertEquals("-122.076", (String)geoLoc.get("lat")); } public void testSingleValuedAudienceSetter() { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().build(); assertTrue(claimsSet.getAudience().isEmpty()); claimsSet = new JWTClaimsSet.Builder().audience("123").build(); assertEquals("123", claimsSet.getAudience().get(0)); assertEquals(1, claimsSet.getAudience().size()); claimsSet = new JWTClaimsSet.Builder().audience((String) null).build(); assertTrue(claimsSet.getAudience().isEmpty()); } public void testSerializeSingleValuedAudience() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().audience("123").build(); JSONObject jsonObject = claimsSet.toJSONObject(); assertEquals("123", (String)jsonObject.get("aud")); assertEquals(1, jsonObject.size()); claimsSet = JWTClaimsSet.parse(jsonObject.toJSONString()); assertEquals("123", claimsSet.getAudience().get(0)); assertEquals(1, claimsSet.getAudience().size()); } public void testGetAllClaimsEmpty() { assertTrue(new JWTClaimsSet.Builder().build().getClaims().isEmpty()); } public void testParseOIDCAuthz() throws Exception { String json = "{\"sub\":\"alice\",\"irt\":true,\"rft\":\"YWxpY2U.aHR0cDovL2NsaWVudDEuZXhhbXBsZS5jb20.rsKHqBpyEh-MMtllO7chHg\",\"aud\":[\"http:\\/\\/userinfo.example.com\"],\"iss\":\"http:\\/\\/oidc.example.com\",\"ate\":\"IDENTIFIER\",\"lng\":true,\"iat\":1420544052,\"cid\":\"http:\\/\\/client1.example.com\"}"; JWTClaimsSet.parse(json); } public void testAudienceParsing() throws Exception { JSONObject jsonObject = new JSONObject(); JSONArray aud = new JSONArray(); aud.add("client-1"); aud.add("client-2"); jsonObject.put("aud", aud); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); assertEquals("client-1", claimsSet.getAudience().get(0)); assertEquals("client-2", claimsSet.getAudience().get(1)); assertEquals(2, claimsSet.getAudience().size()); } public void testGetStringArrayClaim() throws Exception { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); jsonArray.add("client-1"); jsonArray.add("client-2"); jsonObject.put("array", jsonArray); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); String[] strings = claimsSet.getStringArrayClaim("array"); assertEquals("client-1", strings[0]); assertEquals("client-2", strings[1]); assertEquals(2, strings.length); } public void testGetInvalidStringArrayClaim() throws Exception { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); jsonArray.add("client-1"); jsonArray.add(0); jsonObject.put("array", jsonArray); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); try { claimsSet.getStringArrayClaim("array"); fail(); } catch (ParseException e) { // ok } } public void testGetNullStringArrayClaim() throws Exception { JSONObject jsonObject = new JSONObject(); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); assertNull(claimsSet.getStringArrayClaim("array")); } public void testGetStringListClaim() throws Exception { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); jsonArray.add("client-1"); jsonArray.add("client-2"); jsonObject.put("array", jsonArray); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); List<String> strings = claimsSet.getStringListClaim("array"); assertEquals("client-1", strings.get(0)); assertEquals("client-2", strings.get(1)); assertEquals(2, strings.size()); } public void testGetInvalidStringListClaim() throws Exception { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); jsonArray.add("client-1"); jsonArray.add(0); jsonObject.put("array", jsonArray); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); try { claimsSet.getStringListClaim("array"); fail(); } catch (ParseException e) { // ok } } public void testGetNullStringListClaim() throws Exception { JSONObject jsonObject = new JSONObject(); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jsonObject); assertNull(claimsSet.getStringListClaim("array")); } public void testExtendedCyrillicChars() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("Владимир Джувинов").build(); String json = claimsSet.toJSONObject().toJSONString(); claimsSet = JWTClaimsSet.parse(json); assertEquals("Владимир Джувинов", claimsSet.getSubject()); } public void testExtendedLatinChars() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("fullName", "João").build(); String json = claimsSet.toJSONObject().toJSONString(); Base64URL base64URL = Base64URL.encode(json); claimsSet = JWTClaimsSet.parse(base64URL.decodeToString()); assertEquals("João", claimsSet.getStringClaim("fullName")); } public void testURIClaim() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("uri", URI.create("https://example.com").toString()).build(); String json = claimsSet.toJSONObject().toJSONString(); claimsSet = JWTClaimsSet.parse(json); assertEquals(URI.create("https://example.com"), claimsSet.getURIClaim("uri")); assertNull(claimsSet.getURIClaim("no-such-uri-claim")); } public void testParseInvalidURIClaim() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("uri", "a b c").build(); String json = claimsSet.toJSONObject().toJSONString(); claimsSet = JWTClaimsSet.parse(json); try { claimsSet.getURIClaim("uri"); fail(); } catch (ParseException e) { assertEquals("The \"uri\" claim is not a URI: Illegal character in path at index 1: a b c", e.getMessage()); } } public void testSerializeIgnoreNullValues() { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .issuer(null) .subject(null) .audience((String)null) .expirationTime(null) .issueTime(null) .notBeforeTime(null) .jwtID(null) .claim("locale", null) .build(); assertTrue(claimsSet.toJSONObject().isEmpty()); } public void testTransformer() { JWTClaimsSetTransformer<String> transformer = new JWTClaimsSetTransformer<String>() { @Override public String transform(JWTClaimsSet claimsSet) { return claimsSet.getSubject(); } }; JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("alice").build(); assertEquals("alice", claimsSet.toType(transformer)); } // https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/154/list-of-strings-as-custom-claim-will-add public void testParseListOfStrings() throws ParseException { String json = "{ \"alg\":\"HS256\", \"aud\":[\"a\",\"b\"],\"test\":[\"a\",\"b\"] }"; JWTClaimsSet claimsSet = JWTClaimsSet.parse(json); assertEquals("HS256", claimsSet.getStringClaim("alg")); List<String> audList = claimsSet.getStringListClaim("aud"); assertEquals("a", audList.get(0)); assertEquals("b", audList.get(1)); assertEquals(2, audList.size()); List<String> testList = claimsSet.getStringListClaim("test"); assertEquals("a", testList.get(0)); assertEquals("b", testList.get(1)); assertEquals(2, testList.size()); assertEquals(3, claimsSet.getClaims().size()); } // https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/154/list-of-strings-as-custom-claim-will-add public void testListOfStrings() { List<String> audList = new LinkedList<>(); audList.add("a"); audList.add("b"); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("aud", audList) .build(); assertEquals("{\"aud\":[\"a\",\"b\"]}", claimsSet.toJSONObject().toString()); } public void testJSONObjectClaim() throws Exception { JSONObject actor = new JSONObject(); actor.put("sub", "claire"); actor.put("iss", "https://openid.c2id.com"); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("act", actor) .build(); JSONObject out = claimsSet.getJSONObjectClaim("act"); assertEquals("claire", out.get("sub")); assertEquals("https://openid.c2id.com", out.get("iss")); assertEquals(2, out.size()); } public void testJSONObjectClaim_convertFromMap() throws Exception { Map<Object,Object> actor = new HashMap<>(); actor.put("sub", "claire"); actor.put("iss", "https://openid.c2id.com"); actor.put(1, 1000); // must be ignored JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("act", actor) .build(); JSONObject out = claimsSet.getJSONObjectClaim("act"); assertEquals("claire", out.get("sub")); assertEquals("https://openid.c2id.com", out.get("iss")); assertEquals(2, out.size()); } public void testJSONObjectClaim_Null() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().build(); assertNull(claimsSet.getJSONObjectClaim("act")); } public void testJSONObjectClaim_invalidType() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("act", "claire") .build(); try { claimsSet.getJSONObjectClaim("act"); fail(); } catch (ParseException e) { assertEquals("The \"act\" claim is not a JSON object or Map", e.getMessage()); } } public void testClaimAsJSONObject() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", "value"); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("prm", jsonObject) .build(); jsonObject = claimsSet.getJSONObjectClaim("prm"); assertEquals("value", jsonObject.get("key")); assertEquals(1, jsonObject.size()); JSONObject claimsJSONObject = claimsSet.toJSONObject(); jsonObject = (JSONObject) claimsJSONObject.get("prm"); assertEquals("value", jsonObject.get("key")); assertEquals(1, jsonObject.size()); JWT plainJWT = new PlainJWT(claimsSet); String compactEncodedJWT = plainJWT.serialize(); plainJWT = PlainJWT.parse(compactEncodedJWT); claimsSet = plainJWT.getJWTClaimsSet(); jsonObject = claimsSet.getJSONObjectClaim("prm"); assertEquals("value", jsonObject.get("key")); assertEquals(1, jsonObject.size()); } // https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/236 public void testGetAudienceFromStringClaim() { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("aud", "1") .build(); assertEquals(Collections.singletonList("1"), claimsSet.getAudience()); } // https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/236 public void testAudienceStringToJSONObject() throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .claim("aud", "1") .build(); JSONObject jsonObject = claimsSet.toJSONObject(); assertEquals("1", jsonObject.get("aud")); assertEquals(1, jsonObject.size()); } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.preferences; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.View.AccessibilityDelegate; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.BaseAdapter; import android.widget.RadioButton; import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ContextUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader; import org.chromium.chrome.browser.preferences.website.ContentSetting; import org.chromium.chrome.browser.preferences.website.GeolocationInfo; import org.chromium.chrome.browser.preferences.website.SingleWebsitePreferences; import org.chromium.chrome.browser.preferences.website.WebsitePreferenceBridge; import org.chromium.chrome.browser.search_engines.TemplateUrlService; import org.chromium.chrome.browser.search_engines.TemplateUrlService.LoadListener; import org.chromium.chrome.browser.search_engines.TemplateUrlService.TemplateUrl; import org.chromium.components.location.LocationUtils; import org.chromium.ui.text.SpanApplier; import org.chromium.ui.text.SpanApplier.SpanInfo; import java.util.List; /** * A custom adapter for listing search engines. */ public class SearchEngineAdapter extends BaseAdapter implements LoadListener, OnClickListener { /** * A callback for reporting progress to the owner. */ public interface SelectSearchEngineCallback { /** * Called when the search engine data has loaded and we've determined the currently active * one. * @param name Provides the name of it (with a simplified URL in parenthesis). */ void currentSearchEngineDetermined(int selectedIndex); } // The current context. private Context mContext; // The layout inflater to use for the custom views. private LayoutInflater mLayoutInflater; // The callback to use for notifying caller of progress. private SelectSearchEngineCallback mCallback; // The list of available search engines. private List<TemplateUrl> mSearchEngines; // The position (index into mSearchEngines) of the currently selected search engine. Can be -1 // if current search engine is managed and set to something other than the pre-populated values. private int mSelectedSearchEnginePosition = -1; // The position of the default search engine before user's action. private int mInitialEnginePosition = -1; /** * Construct a SearchEngineAdapter. * @param context The current context. * @param callback The callback to use to communicate back. */ public SearchEngineAdapter(Context context, SelectSearchEngineCallback callback) { mContext = context; mLayoutInflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mCallback = callback; initEntries(); } /** * @return The index of the selected engine before user's action. */ public int getInitialSearchEnginePosition() { return mInitialEnginePosition; } // Used for testing. String getValueForTesting() { return Integer.toString(mSelectedSearchEnginePosition); } void setValueForTesting(String value) { searchEngineSelected(Integer.parseInt(value)); } /** * Initialize the search engine list. */ private void initEntries() { TemplateUrlService templateUrlService = TemplateUrlService.getInstance(); if (!templateUrlService.isLoaded()) { templateUrlService.registerLoadListener(this); templateUrlService.load(); return; // Flow continues in onTemplateUrlServiceLoaded below. } // Fetch all the search engine info and the currently active one. mSearchEngines = templateUrlService.getLocalizedSearchEngines(); int searchEngineIndex = templateUrlService.getDefaultSearchEngineIndex(); // Convert the TemplateUrl index into an index into mSearchEngines. mSelectedSearchEnginePosition = -1; for (int i = 0; i < mSearchEngines.size(); ++i) { if (mSearchEngines.get(i).getIndex() == searchEngineIndex) { mSelectedSearchEnginePosition = i; } } mInitialEnginePosition = mSelectedSearchEnginePosition; // Report back what is selected. mCallback.currentSearchEngineDetermined(toIndex(mSelectedSearchEnginePosition)); } private int toIndex(int position) { return mSearchEngines.get(position).getIndex(); } // BaseAdapter: @Override public int getCount() { return mSearchEngines == null ? 0 : mSearchEngines.size(); } @Override public Object getItem(int pos) { TemplateUrl templateUrl = mSearchEngines.get(pos); return templateUrl.getShortName(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (convertView == null) { view = mLayoutInflater.inflate(R.layout.search_engine, null); } view.setOnClickListener(this); view.setTag(position); // TODO(finnur): There's a tinting bug in the AppCompat lib (see http://crbug.com/474695), // which causes the first radiobox to always appear selected, even if it is not. It is being // addressed, but in the meantime we should use the native RadioButton instead. RadioButton radioButton = (RadioButton) view.findViewById(R.id.radiobutton); // On Lollipop this removes the redundant animation ring on selection but on older versions // it would cause the radio button to disappear. // TODO(finnur): Remove the encompassing if statement once we go back to using the AppCompat // control. final boolean selected = position == mSelectedSearchEnginePosition; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { radioButton.setBackgroundResource(0); } radioButton.setChecked(selected); TextView description = (TextView) view.findViewById(R.id.description); TemplateUrl templateUrl = mSearchEngines.get(position); Resources resources = mContext.getResources(); description.setText(templateUrl.getShortName()); // To improve the explore-by-touch experience, the radio button is hidden from accessibility // and instead, "checked" or "not checked" is read along with the search engine's name, e.g. // "google.com checked" or "google.com not checked". radioButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); description.setAccessibilityDelegate(new AccessibilityDelegate() { @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setChecked(selected); } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setCheckable(true); info.setChecked(selected); } }); TextView link = (TextView) view.findViewById(R.id.link); link.setVisibility(selected ? View.VISIBLE : View.GONE); if (selected) { ForegroundColorSpan linkSpan = new ForegroundColorSpan( ApiCompatibilityUtils.getColor(resources, R.color.pref_accent_color)); if (LocationUtils.getInstance().isSystemLocationSettingEnabled()) { String message = mContext.getString( locationEnabled(position, true) ? R.string.search_engine_location_allowed : R.string.search_engine_location_blocked); SpannableString messageWithLink = new SpannableString(message); messageWithLink.setSpan(linkSpan, 0, messageWithLink.length(), 0); link.setText(messageWithLink); } else { link.setText(SpanApplier.applySpans( mContext.getString(R.string.android_location_off), new SpanInfo("<link>", "</link>", linkSpan))); } link.setOnClickListener(this); } return view; } // TemplateUrlService.LoadListener @Override public void onTemplateUrlServiceLoaded() { TemplateUrlService.getInstance().unregisterLoadListener(this); initEntries(); notifyDataSetChanged(); } // OnClickListener: @Override public void onClick(View view) { if (view.getTag() == null) { onLocationLinkClicked(); } else { searchEngineSelected((int) view.getTag()); } } private void searchEngineSelected(int position) { // First clean up any automatically added permissions (if any) for the previously selected // search engine. SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); if (sharedPreferences.getBoolean(PrefServiceBridge.LOCATION_AUTO_ALLOWED, false)) { if (locationEnabled(mSelectedSearchEnginePosition, false)) { String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( toIndex(mSelectedSearchEnginePosition)); WebsitePreferenceBridge.nativeSetGeolocationSettingForOrigin( url, url, ContentSetting.DEFAULT.toInt(), false); } sharedPreferences.edit().remove(PrefServiceBridge.LOCATION_AUTO_ALLOWED).apply(); } // Record the change in search engine. mSelectedSearchEnginePosition = position; // Report the change back. mCallback.currentSearchEngineDetermined(toIndex(mSelectedSearchEnginePosition)); notifyDataSetChanged(); } private void onLocationLinkClicked() { if (!LocationUtils.getInstance().isSystemLocationSettingEnabled()) { mContext.startActivity(LocationUtils.getInstance().getSystemLocationSettingsIntent()); } else { Intent settingsIntent = PreferencesLauncher.createIntentForSettingsPage( mContext, SingleWebsitePreferences.class.getName()); String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( toIndex(mSelectedSearchEnginePosition)); Bundle fragmentArgs = SingleWebsitePreferences.createFragmentArgsForSite(url); fragmentArgs.putBoolean(SingleWebsitePreferences.EXTRA_LOCATION, locationEnabled(mSelectedSearchEnginePosition, true)); settingsIntent.putExtra(Preferences.EXTRA_SHOW_FRAGMENT_ARGUMENTS, fragmentArgs); mContext.startActivity(settingsIntent); } } private boolean locationEnabled(int position, boolean checkGeoHeader) { if (position == -1) return false; String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( toIndex(position)); GeolocationInfo locationSettings = new GeolocationInfo(url, null, false); ContentSetting locationPermission = locationSettings.getContentSetting(); // Handle the case where the geoHeader being sent when no permission has been specified. if (locationPermission == ContentSetting.ASK && checkGeoHeader) { return GeolocationHeader.isGeoHeaderEnabledForUrl(mContext, url, false); } return locationPermission == ContentSetting.ALLOW; } }
/* * 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.camel.component.sql; import org.apache.camel.builder.RouteBuilder; public class SqlProducerInMultiExpressionTest extends SqlProducerInMultiTest { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { // required for the sql component getContext().getComponent("sql", SqlComponent.class).setDataSource(db); from("direct:query") .to("sql:classpath:sql/selectProjectsInMultiExpression.sql") .to("log:query") .to("mock:query"); } }; } }
// 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.execution.application; import com.intellij.execution.jvm.JvmRunLineMarkerContributor; import com.intellij.execution.lineMarker.ExecutorAction; import com.intellij.icons.AllIcons; import com.intellij.lang.jvm.JvmClass; import com.intellij.lang.jvm.JvmElement; import com.intellij.lang.jvm.JvmMethod; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.lang.jvm.util.JvmMainMethodUtil.hasMainMethodInHierarchy; import static com.intellij.lang.jvm.util.JvmMainMethodUtil.isMainMethod; public class JvmApplicationRunLineMarkerContributor extends JvmRunLineMarkerContributor { @Nullable @Override protected Info getInfo(JvmElement element) { return showMarker(element) ? info() : null; } private static boolean showMarker(@NotNull JvmElement declaration) { return declaration instanceof JvmMethod && isMainMethod((JvmMethod)declaration) || declaration instanceof JvmClass && hasMainMethodInHierarchy((JvmClass)declaration); } @NotNull private static Info info() { final AnAction[] actions = ExecutorAction.getActions(); return new Info( AllIcons.RunConfigurations.TestState.Run, actions, element -> StringUtil.join(ContainerUtil.mapNotNull(actions, action -> getText(action, element)), "\n") ); } }
package slimeknights.tconstruct.tools.modifiers.ability.tool; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import slimeknights.tconstruct.library.modifiers.impl.InteractionModifier; import slimeknights.tconstruct.library.tools.helper.ToolDamageUtil; import slimeknights.tconstruct.library.tools.nbt.IToolStackView; import slimeknights.tconstruct.shared.TinkerCommons; public class GlowingModifier extends InteractionModifier.SingleUse { @Override public int getPriority() { return 70; // after bucketing } @Override public InteractionResult afterBlockUse(IToolStackView tool, int level, UseOnContext context, EquipmentSlot slotType) { Player player = context.getPlayer(); if (tool.getCurrentDurability() >= 10) { if (!context.getLevel().isClientSide) { Level world = context.getLevel(); Direction face = context.getClickedFace(); BlockPos pos = context.getClickedPos().relative(face); if (TinkerCommons.glow.get().addGlow(world, pos, face.getOpposite())) { // damage the tool, showing animation if relevant if (ToolDamageUtil.damage(tool, 10, player, context.getItemInHand()) && player != null) { player.broadcastBreakEvent(slotType); } world.playSound(null, pos, world.getBlockState(pos).getSoundType(/*world, pos, player*/).getPlaceSound(), SoundSource.BLOCKS, 1.0f, 1.0f); // TODO: PORT } } return InteractionResult.sidedSuccess(context.getLevel().isClientSide); } return InteractionResult.PASS; } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.maintenance; import com.yahoo.component.Version; import com.yahoo.config.provision.ApplicationId; import com.yahoo.vespa.athenz.api.OktaAccessToken; import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision; import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester; import com.yahoo.vespa.hosted.controller.deployment.JobController; import com.yahoo.vespa.hosted.controller.deployment.Run; import com.yahoo.vespa.hosted.controller.deployment.RunStatus; import com.yahoo.vespa.hosted.controller.deployment.Step; import com.yahoo.vespa.hosted.controller.deployment.Step.Status; import com.yahoo.vespa.hosted.controller.deployment.StepRunner; import com.yahoo.vespa.hosted.controller.deployment.Versions; import org.junit.Test; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import java.util.stream.Collectors; import static com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType.stagingTest; import static com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType.systemTest; import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.aborted; import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.error; import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.running; import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.testFailure; import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed; import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded; import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished; import static com.yahoo.vespa.hosted.controller.deployment.Step.deactivateReal; import static com.yahoo.vespa.hosted.controller.deployment.Step.deactivateTester; import static com.yahoo.vespa.hosted.controller.deployment.Step.deployReal; import static com.yahoo.vespa.hosted.controller.deployment.Step.deployTester; import static com.yahoo.vespa.hosted.controller.deployment.Step.endTests; import static com.yahoo.vespa.hosted.controller.deployment.Step.installReal; import static com.yahoo.vespa.hosted.controller.deployment.Step.installTester; import static com.yahoo.vespa.hosted.controller.deployment.Step.report; import static com.yahoo.vespa.hosted.controller.deployment.Step.startTests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author jonmv */ public class JobRunnerTest { private static final Versions versions = new Versions(Version.fromString("1.2.3"), ApplicationVersion.from(new SourceRevision("repo", "branch", "bada55"), 321), Optional.empty(), Optional.empty()); @Test public void multiThreadedExecutionFinishes() throws InterruptedException { DeploymentTester tester = new DeploymentTester(); JobController jobs = tester.controller().jobController(); StepRunner stepRunner = (step, id) -> id.type() == stagingTest && step.get() == startTests? Optional.of(error) : Optional.of(running); Phaser phaser = new Phaser(1); JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()), phasedExecutor(phaser), stepRunner); ApplicationId id = tester.createApplication("real", "tenant", 1, 1L).id(); jobs.submit(id, versions.targetApplication().source().get(), 2, new byte[0], new byte[0]); jobs.start(id, systemTest, versions); try { jobs.start(id, systemTest, versions); fail("Job is already running, so this should not be allowed!"); } catch (IllegalStateException e) { } jobs.start(id, stagingTest, versions); assertTrue(jobs.last(id, systemTest).get().steps().values().stream().allMatch(unfinished::equals)); assertFalse(jobs.last(id, systemTest).get().hasEnded()); assertTrue(jobs.last(id, stagingTest).get().steps().values().stream().allMatch(unfinished::equals)); assertFalse(jobs.last(id, stagingTest).get().hasEnded()); runner.maintain(); phaser.arriveAndAwaitAdvance(); assertTrue(jobs.last(id, systemTest).get().steps().values().stream().allMatch(succeeded::equals)); assertTrue(jobs.last(id, stagingTest).get().hasEnded()); assertTrue(jobs.last(id, stagingTest).get().hasFailed()); } @Test public void stepLogic() { DeploymentTester tester = new DeploymentTester(); JobController jobs = tester.controller().jobController(); Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class); JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()), inThreadExecutor(), mappedRunner(outcomes)); ApplicationId id = tester.createApplication("real", "tenant", 1, 1L).id(); jobs.submit(id, versions.targetApplication().source().get(), 2, new byte[0], new byte[0]); Supplier<Run> run = () -> jobs.last(id, systemTest).get(); jobs.start(id, systemTest, versions); RunId first = run.get().id(); Map<Step, Status> steps = run.get().steps(); runner.maintain(); assertEquals(steps, run.get().steps()); assertEquals(Arrays.asList(deployReal, deployTester), run.get().readySteps()); outcomes.put(deployReal, running); runner.maintain(); assertEquals(Arrays.asList(installReal, deployTester), run.get().readySteps()); outcomes.put(installReal, running); runner.maintain(); assertEquals(Arrays.asList(deployTester), run.get().readySteps()); outcomes.put(deployTester, running); runner.maintain(); assertEquals(Arrays.asList(installTester), run.get().readySteps()); outcomes.put(installTester, running); runner.maintain(); assertEquals(Arrays.asList(startTests), run.get().readySteps()); outcomes.put(startTests, running); runner.maintain(); assertEquals(Arrays.asList(endTests), run.get().readySteps()); // Failure ending tests fails the run, but run-always steps continue. outcomes.put(endTests, testFailure); runner.maintain(); assertTrue(run.get().hasFailed()); assertEquals(Arrays.asList(deactivateReal, deactivateTester), run.get().readySteps()); // Abortion does nothing, as the run has already failed. jobs.abort(run.get().id()); runner.maintain(); assertEquals(Arrays.asList(deactivateReal, deactivateTester), run.get().readySteps()); outcomes.put(deactivateReal, running); outcomes.put(deactivateTester, running); outcomes.put(report, running); runner.maintain(); assertTrue(run.get().hasFailed()); assertTrue(run.get().hasEnded()); assertTrue(run.get().status() == aborted); // A new run is attempted. jobs.start(id, systemTest, versions); assertEquals(first.number() + 1, run.get().id().number()); // Run fails on tester deployment -- remaining run-always steps succeed, and the run finishes. outcomes.put(deployTester, error); runner.maintain(); assertTrue(run.get().hasEnded()); assertTrue(run.get().hasFailed()); assertFalse(run.get().status() == aborted); assertEquals(failed, run.get().steps().get(deployTester)); assertEquals(unfinished, run.get().steps().get(installTester)); assertEquals(succeeded, run.get().steps().get(report)); assertEquals(2, jobs.runs(id, systemTest).size()); // Start a third run, then unregister and wait for data to be deleted. jobs.start(id, systemTest, versions); jobs.unregister(id); runner.maintain(); assertFalse(jobs.last(id, systemTest).isPresent()); assertTrue(jobs.runs(id, systemTest).isEmpty()); } @Test public void locksAndGarbage() throws InterruptedException, BrokenBarrierException { DeploymentTester tester = new DeploymentTester(); JobController jobs = tester.controller().jobController(); // Hang during tester deployment, until notified. CyclicBarrier barrier = new CyclicBarrier(2); JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()), Executors.newFixedThreadPool(32), waitingRunner(barrier)); ApplicationId id = tester.createApplication("real", "tenant", 1, 1L).id(); jobs.submit(id, versions.targetApplication().source().get(), 2, new byte[0], new byte[0]); RunId runId = new RunId(id, systemTest, 1); jobs.start(id, systemTest, versions); runner.maintain(); barrier.await(); try { jobs.locked(id, systemTest, deactivateTester, step -> { }); fail("deployTester step should still be locked!"); } catch (TimeoutException e) { } // Thread is still trying to deploy tester -- delete application, and see all data is garbage collected. assertEquals(Collections.singletonList(runId), jobs.active().stream().map(run -> run.id()).collect(Collectors.toList())); tester.controller().applications().deleteApplication(id, Optional.of(new OktaAccessToken("okta-token"))); assertEquals(Collections.emptyList(), jobs.active()); assertEquals(runId, jobs.last(id, systemTest).get().id()); // Deployment still ongoing, so garbage is not yet collected. runner.maintain(); assertEquals(runId, jobs.last(id, systemTest).get().id()); // Deployment lets go, deactivation may now run, and trash is thrown out. barrier.await(); runner.maintain(); assertEquals(Optional.empty(), jobs.last(id, systemTest)); } @Test public void historyPruning() { DeploymentTester tester = new DeploymentTester(); JobController jobs = tester.controller().jobController(); JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()), inThreadExecutor(), (id, step) -> Optional.of(running)); ApplicationId id = tester.createApplication("real", "tenant", 1, 1L).id(); jobs.submit(id, versions.targetApplication().source().get(), 2, new byte[0], new byte[0]); for (int i = 0; i < jobs.historyLength(); i++) { jobs.start(id, systemTest, versions); runner.run(); } assertEquals(256, jobs.runs(id, systemTest).size()); assertTrue(jobs.details(new RunId(id, systemTest, 1)).isPresent()); jobs.start(id, systemTest, versions); runner.run(); assertEquals(256, jobs.runs(id, systemTest).size()); assertEquals(2, jobs.runs(id, systemTest).keySet().iterator().next().number()); assertFalse(jobs.details(new RunId(id, systemTest, 1)).isPresent()); assertTrue(jobs.details(new RunId(id, systemTest, 257)).isPresent()); } @Test public void timeout() { DeploymentTester tester = new DeploymentTester(); JobController jobs = tester.controller().jobController(); Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class); JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()), inThreadExecutor(), mappedRunner(outcomes)); ApplicationId id = tester.createApplication("real", "tenant", 1, 1L).id(); jobs.submit(id, versions.targetApplication().source().get(), 2, new byte[0], new byte[0]); jobs.start(id, systemTest, versions); tester.clock().advance(JobRunner.jobTimeout.plus(Duration.ofSeconds(1))); runner.run(); assertTrue(jobs.last(id, systemTest).get().status() == aborted); } public static ExecutorService inThreadExecutor() { return new AbstractExecutorService() { AtomicBoolean shutDown = new AtomicBoolean(false); @Override public void shutdown() { shutDown.set(true); } @Override public List<Runnable> shutdownNow() { shutDown.set(true); return Collections.emptyList(); } @Override public boolean isShutdown() { return shutDown.get(); } @Override public boolean isTerminated() { return shutDown.get(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) { return true; } @Override public void execute(Runnable command) { command.run(); } }; } private static ExecutorService phasedExecutor(Phaser phaser) { return new AbstractExecutorService() { ExecutorService delegate = Executors.newFixedThreadPool(32); @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public void execute(Runnable command) { phaser.register(); delegate.execute(() -> { command.run(); phaser.arriveAndDeregister(); }); } }; } private static StepRunner mappedRunner(Map<Step, RunStatus> outcomes) { return (step, id) -> Optional.ofNullable(outcomes.get(step.get())); } private static StepRunner waitingRunner(CyclicBarrier barrier) { return (step, id) -> { try { if (step.get() == deployTester) { barrier.await(); // Wake up the main thread, which waits for this step to be locked. barrier.reset(); barrier.await(); // Then wait while holding the lock for this step, until the main thread wakes us up. } } catch (InterruptedException | BrokenBarrierException e) { throw new AssertionError(e); } return Optional.of(running); }; } }
package com.planet_ink.coffee_mud.Abilities.interfaces; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2002-2018 Bo Zimmerman 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. */ /** * A Language ability represents both the ability to understand one or more * spoken or written languages, and the ability to speak one or more spoken * languages. A single ability usually represents a single language, but * may support multiple simultaneously. */ public interface Language extends Ability { /** * Returns the name of this language when it is in written form. * This is usually the same as the spoken form. * @return the name of this language when it is in written form. */ public String writtenName(); /** * Returns a list of the languages understood by this ability * @return vector of language ids supported (usually 1 element == ID()) */ public List<String> languagesSupported(); /** * Returns whether the given language is translated by this one * @param language the language to test * @return true if this language translates (usually ID() == language) */ public boolean translatesLanguage(String language); /** * Returns the understanding profficiency in the given supported language * @param language the language to test for (usually ID()) * @return the profficiency of this ability in the language (0-100) */ public int getProficiency(String language); /** * Returns whether this language is currently being spoken * @param language the language to test for (usually ID()) * @return true if spoken */ public boolean beingSpoken(String language); /** * Changes whether this language is currently being spoken * @param language the language to set (usually ID()) * @param beingSpoken whether it is being spoken */ public void setBeingSpoken(String language, boolean beingSpoken); /** * Returns the direct word to word translation hashtable * @param language the language to translate directory (usually ID()) * @return the hashtable of word-word translations */ public Map<String, String> translationHash(String language); /** * Returns the word-length rough-translation vector of string arrays for the given language * The first string array in the vector represents 1 letter words, the second 2, * and so forth. * @param language the language to return the vector for (usually ID()) * @return the vector of word-length rough translation string arrays */ public List<String[]> translationVector(String language); /** * Returns a language translation of the given word in the given language * @param language the language to use (usually ID()) * @param word the word to translate * @return the translated word */ public String translate(String language, String word); }
/** * Spieler.java * * Die Spieler Klasse beinhaltet alle Information zum jeweiligen Spieler. Dazu * gehört der aktuelle Punktestand, die Steuerung, die aktuellen Koordinaten, etc * * @author Anton Makarow (191721) * @author Timo Appenzeller (191382) * * @date 24.06.2016 */ public class MaxSpieler { private String name; private int posX, posY; //aktuelle Position private int punkte; private String up, down, right, left; //Taste für jeweilige Richtung private MaxSpielfeld spielfeld; private int spX, spY; // Spielfeldgröße /** * Konstruktor * @param String n Der Name der Spielers * @param int pX Start X-Koordinate * @param int pY Start Y-Koordinate * @param String up Tastenbelegung für "oben" * @param String down Tastenbelegung für "unten" * @param String left Tastenbelegung für "links" * @param String right Tastenbelegung für "rechts" * @param MaxSpielfeld sp Eine Referenz auf das aktuell gültige Spielfeld */ public MaxSpieler(String n, int pX, int pY, String up, String down, String left, String right, MaxSpielfeld sp) { name = n; posX = pX; posY = pY; this.up = up; this.down = down; this.left = left; this.right = right; spielfeld = sp; String[][] feld = spielfeld.getSpielfeld(); spX = feld.length; spY = feld[0].length; spielfeld.setField(posX, posY, " "); } /** * Setzt die Position des Spielers * @param x neue X-Koordinate * @param y neue Y-Koordinate */ public void spielerPositionSetzen(int x, int y){ spielfeld.setField(x, y, " "); posX = x; posY = y; } /** * Kollisionsabfrage * @return false bei Kollision */ private boolean checkCollision(int pX, int pY) { return (pX < 0 || pX >= spX || pY < 0 || pY >= spY) ? true : false; } /** * Sammel Punke auf aktuellem Feld */ private void collectPoints() { String p = spielfeld.getField(posX, posY); punkte += p.matches("[1-9]") ? Integer.parseInt(p) : 0; } /** * Prüfe ob Siegbedingung erfüllt ist * @return true Falls Siegbedingung erfüllt * @return false Falls Siegbedingung nicht erfüllt */ private boolean winCheck() { if(punkte >= 105) { // System.out.println("Spieler '" + name + "' hat mit " + punkte // + " Punkten GEWONNEN!"); return true; } else { return false; } } /** * Gib die aktuelle X-Koordinate zurück * @return X-Koordinate */ public int getPosX() { return posX; } /** * Gib die aktuelle Y-Koordinate zurück * @return Y-Koordinate */ public int getPosY() { return posY; } /** * Gib den Namen des Spielers zurück * @return Name des Spielers */ public String getName() { return name; } /** * Gib die Punktzahl des Spieler zurück * @return aktuelle Punktzahl */ public int getPunkte(){ return punkte; } /** * Setzt die Punktzahl des Spielers * @param neue Punktzahl */ public void setPunkte(int punkte){ this.punkte = punkte; } /** * update Methode * Ein Spieler ist solange dran bis er einen gültigen Zug ausführt. * Kollision (mit dem Rand) zählt nicht als gültiger Zug. * @return Der neu Zustand für den weiteren Spielverlauf */ public MaxGameState update(String c) { if(c.equals(up)) { if(!checkCollision(posX, posY-1)) { spielfeld.setField(posX, posY, " "); posY--; collectPoints(); return winCheck() ? MaxGameState.QUIT : MaxGameState.NEXT; } else { return MaxGameState.LOOP; } } else if(c.equals(down)) { if(!checkCollision(posX, posY+1)) { spielfeld.setField(posX, posY, " "); posY++; collectPoints(); return winCheck() ? MaxGameState.QUIT : MaxGameState.NEXT; } else { return MaxGameState.LOOP; } } else if(c.equals(left)) { if(!checkCollision(posX-1, posY)) { spielfeld.setField(posX, posY, " "); posX--; collectPoints(); return winCheck() ? MaxGameState.QUIT : MaxGameState.NEXT; } else { return MaxGameState.LOOP; } } else if(c.equals(right)) { if(!checkCollision(posX+1, posY)) { spielfeld.setField(posX, posY, " "); posX++; collectPoints(); return winCheck() ? MaxGameState.QUIT : MaxGameState.NEXT; } else { return MaxGameState.LOOP; } } else { return MaxGameState.LOOP; } } }
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.distributedprimitives.cli; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.apache.karaf.shell.commands.Option; import org.onlab.util.KryoNamespace; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.StorageService; import java.util.HashSet; import java.util.Set; /** * CLI command to get the elements in a distributed set. */ @Command(scope = "onos", name = "set-test-get", description = "Get the elements in a distributed set") public class SetTestGetCommand extends AbstractShellCommand { @Option(name = "-s", aliases = "--size", description = "Also show the size of the set?", required = false, multiValued = false) private boolean size = false; @Argument(index = 0, name = "setName", description = "set name", required = true, multiValued = false) String setName = null; @Argument(index = 1, name = "values", description = "Check if the set contains these value(s)", required = false, multiValued = true) String[] values = null; Set<String> set; Set<String> toCheck = new HashSet<String>(); String output = new String(); Serializer serializer = Serializer.using( new KryoNamespace.Builder().register(KryoNamespaces.BASIC).build()); @Override protected void execute() { StorageService storageService = get(StorageService.class); set = storageService.<String>setBuilder() .withName(setName) .withSerializer(serializer) .build(); // Print the set size if (size) { print("There are %d items in set %s:", set.size(), setName); } else { print("Items in set %s:", setName); } // Print the set if (set.isEmpty()) { print("[]"); } else { for (String e : set.toArray(new String[set.size()])) { if (output.isEmpty()) { output += e; } else { output += ", " + e; } } print("[%s]", output); } // Check if given values are in the set if (values == null) { return; } else if (values.length == 1) { // contains if (set.contains(values[0])) { print("Set %s contains the value %s", setName, values[0]); } else { print("Set %s did not contain the value %s", setName, values[0]); } } else if (values.length > 1) { //containsAll for (String value : values) { toCheck.add(value); } if (set.containsAll(toCheck)) { print("Set %s contains the the subset %s", setName, toCheck); } else { print("Set %s did not contain the the subset %s", setName, toCheck); } } } }
/* * Kubernetes * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1.11.4 * * * 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. */ package io.kubernetes.client.apis; import io.kubernetes.client.ApiCallback; import io.kubernetes.client.ApiClient; import io.kubernetes.client.ApiException; import io.kubernetes.client.ApiResponse; import io.kubernetes.client.Configuration; import io.kubernetes.client.Pair; import io.kubernetes.client.ProgressRequestBody; import io.kubernetes.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import io.kubernetes.client.models.V1APIResourceList; import io.kubernetes.client.models.V1LocalSubjectAccessReview; import io.kubernetes.client.models.V1SelfSubjectAccessReview; import io.kubernetes.client.models.V1SelfSubjectRulesReview; import io.kubernetes.client.models.V1SubjectAccessReview; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class AuthorizationV1Api { private ApiClient apiClient; public AuthorizationV1Api() { this(Configuration.getDefaultApiClient()); } public AuthorizationV1Api(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for createNamespacedLocalSubjectAccessReview * @param namespace object name and auth scope, such as for teams and projects (required) * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createNamespacedLocalSubjectAccessReviewCall(String namespace, V1LocalSubjectAccessReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/apis/authorization.k8s.io/v1/namespaces/{namespace}/localsubjectaccessreviews" .replaceAll("\\{" + "namespace" + "\\}", apiClient.escapeString(namespace.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (pretty != null) localVarQueryParams.addAll(apiClient.parameterToPair("pretty", pretty)); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "application/yaml", "application/vnd.kubernetes.protobuf" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "*/*" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "BearerToken" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createNamespacedLocalSubjectAccessReviewValidateBeforeCall(String namespace, V1LocalSubjectAccessReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'namespace' is set if (namespace == null) { throw new ApiException("Missing the required parameter 'namespace' when calling createNamespacedLocalSubjectAccessReview(Async)"); } // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling createNamespacedLocalSubjectAccessReview(Async)"); } com.squareup.okhttp.Call call = createNamespacedLocalSubjectAccessReviewCall(namespace, body, pretty, progressListener, progressRequestListener); return call; } /** * * create a LocalSubjectAccessReview * @param namespace object name and auth scope, such as for teams and projects (required) * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return V1LocalSubjectAccessReview * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public V1LocalSubjectAccessReview createNamespacedLocalSubjectAccessReview(String namespace, V1LocalSubjectAccessReview body, String pretty) throws ApiException { ApiResponse<V1LocalSubjectAccessReview> resp = createNamespacedLocalSubjectAccessReviewWithHttpInfo(namespace, body, pretty); return resp.getData(); } /** * * create a LocalSubjectAccessReview * @param namespace object name and auth scope, such as for teams and projects (required) * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return ApiResponse&lt;V1LocalSubjectAccessReview&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<V1LocalSubjectAccessReview> createNamespacedLocalSubjectAccessReviewWithHttpInfo(String namespace, V1LocalSubjectAccessReview body, String pretty) throws ApiException { com.squareup.okhttp.Call call = createNamespacedLocalSubjectAccessReviewValidateBeforeCall(namespace, body, pretty, null, null); Type localVarReturnType = new TypeToken<V1LocalSubjectAccessReview>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * (asynchronously) * create a LocalSubjectAccessReview * @param namespace object name and auth scope, such as for teams and projects (required) * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createNamespacedLocalSubjectAccessReviewAsync(String namespace, V1LocalSubjectAccessReview body, String pretty, final ApiCallback<V1LocalSubjectAccessReview> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createNamespacedLocalSubjectAccessReviewValidateBeforeCall(namespace, body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1LocalSubjectAccessReview>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for createSelfSubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createSelfSubjectAccessReviewCall(V1SelfSubjectAccessReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/apis/authorization.k8s.io/v1/selfsubjectaccessreviews"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (pretty != null) localVarQueryParams.addAll(apiClient.parameterToPair("pretty", pretty)); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "application/yaml", "application/vnd.kubernetes.protobuf" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "*/*" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "BearerToken" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createSelfSubjectAccessReviewValidateBeforeCall(V1SelfSubjectAccessReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling createSelfSubjectAccessReview(Async)"); } com.squareup.okhttp.Call call = createSelfSubjectAccessReviewCall(body, pretty, progressListener, progressRequestListener); return call; } /** * * create a SelfSubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return V1SelfSubjectAccessReview * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public V1SelfSubjectAccessReview createSelfSubjectAccessReview(V1SelfSubjectAccessReview body, String pretty) throws ApiException { ApiResponse<V1SelfSubjectAccessReview> resp = createSelfSubjectAccessReviewWithHttpInfo(body, pretty); return resp.getData(); } /** * * create a SelfSubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return ApiResponse&lt;V1SelfSubjectAccessReview&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<V1SelfSubjectAccessReview> createSelfSubjectAccessReviewWithHttpInfo(V1SelfSubjectAccessReview body, String pretty) throws ApiException { com.squareup.okhttp.Call call = createSelfSubjectAccessReviewValidateBeforeCall(body, pretty, null, null); Type localVarReturnType = new TypeToken<V1SelfSubjectAccessReview>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * (asynchronously) * create a SelfSubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createSelfSubjectAccessReviewAsync(V1SelfSubjectAccessReview body, String pretty, final ApiCallback<V1SelfSubjectAccessReview> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createSelfSubjectAccessReviewValidateBeforeCall(body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1SelfSubjectAccessReview>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for createSelfSubjectRulesReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createSelfSubjectRulesReviewCall(V1SelfSubjectRulesReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/apis/authorization.k8s.io/v1/selfsubjectrulesreviews"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (pretty != null) localVarQueryParams.addAll(apiClient.parameterToPair("pretty", pretty)); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "application/yaml", "application/vnd.kubernetes.protobuf" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "*/*" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "BearerToken" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createSelfSubjectRulesReviewValidateBeforeCall(V1SelfSubjectRulesReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling createSelfSubjectRulesReview(Async)"); } com.squareup.okhttp.Call call = createSelfSubjectRulesReviewCall(body, pretty, progressListener, progressRequestListener); return call; } /** * * create a SelfSubjectRulesReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return V1SelfSubjectRulesReview * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public V1SelfSubjectRulesReview createSelfSubjectRulesReview(V1SelfSubjectRulesReview body, String pretty) throws ApiException { ApiResponse<V1SelfSubjectRulesReview> resp = createSelfSubjectRulesReviewWithHttpInfo(body, pretty); return resp.getData(); } /** * * create a SelfSubjectRulesReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return ApiResponse&lt;V1SelfSubjectRulesReview&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<V1SelfSubjectRulesReview> createSelfSubjectRulesReviewWithHttpInfo(V1SelfSubjectRulesReview body, String pretty) throws ApiException { com.squareup.okhttp.Call call = createSelfSubjectRulesReviewValidateBeforeCall(body, pretty, null, null); Type localVarReturnType = new TypeToken<V1SelfSubjectRulesReview>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * (asynchronously) * create a SelfSubjectRulesReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createSelfSubjectRulesReviewAsync(V1SelfSubjectRulesReview body, String pretty, final ApiCallback<V1SelfSubjectRulesReview> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createSelfSubjectRulesReviewValidateBeforeCall(body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1SelfSubjectRulesReview>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for createSubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createSubjectAccessReviewCall(V1SubjectAccessReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/apis/authorization.k8s.io/v1/subjectaccessreviews"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (pretty != null) localVarQueryParams.addAll(apiClient.parameterToPair("pretty", pretty)); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "application/yaml", "application/vnd.kubernetes.protobuf" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "*/*" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "BearerToken" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createSubjectAccessReviewValidateBeforeCall(V1SubjectAccessReview body, String pretty, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling createSubjectAccessReview(Async)"); } com.squareup.okhttp.Call call = createSubjectAccessReviewCall(body, pretty, progressListener, progressRequestListener); return call; } /** * * create a SubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return V1SubjectAccessReview * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public V1SubjectAccessReview createSubjectAccessReview(V1SubjectAccessReview body, String pretty) throws ApiException { ApiResponse<V1SubjectAccessReview> resp = createSubjectAccessReviewWithHttpInfo(body, pretty); return resp.getData(); } /** * * create a SubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @return ApiResponse&lt;V1SubjectAccessReview&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<V1SubjectAccessReview> createSubjectAccessReviewWithHttpInfo(V1SubjectAccessReview body, String pretty) throws ApiException { com.squareup.okhttp.Call call = createSubjectAccessReviewValidateBeforeCall(body, pretty, null, null); Type localVarReturnType = new TypeToken<V1SubjectAccessReview>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * (asynchronously) * create a SubjectAccessReview * @param body (required) * @param pretty If &#39;true&#39;, then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createSubjectAccessReviewAsync(V1SubjectAccessReview body, String pretty, final ApiCallback<V1SubjectAccessReview> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createSubjectAccessReviewValidateBeforeCall(body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1SubjectAccessReview>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for getAPIResources * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call getAPIResourcesCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/apis/authorization.k8s.io/v1/"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "application/yaml", "application/vnd.kubernetes.protobuf" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json", "application/yaml", "application/vnd.kubernetes.protobuf" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "BearerToken" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getAPIResourcesValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { com.squareup.okhttp.Call call = getAPIResourcesCall(progressListener, progressRequestListener); return call; } /** * * get available resources * @return V1APIResourceList * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public V1APIResourceList getAPIResources() throws ApiException { ApiResponse<V1APIResourceList> resp = getAPIResourcesWithHttpInfo(); return resp.getData(); } /** * * get available resources * @return ApiResponse&lt;V1APIResourceList&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<V1APIResourceList> getAPIResourcesWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = getAPIResourcesValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<V1APIResourceList>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * (asynchronously) * get available resources * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getAPIResourcesAsync(final ApiCallback<V1APIResourceList> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getAPIResourcesValidateBeforeCall(progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1APIResourceList>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
/* * This file is part of the L2JServer project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quests.Q226_TestOfTheHealer; import org.l2jserver.commons.util.Rnd; import org.l2jserver.gameserver.model.actor.instance.NpcInstance; import org.l2jserver.gameserver.model.actor.instance.PlayerInstance; import org.l2jserver.gameserver.model.base.ClassId; import org.l2jserver.gameserver.model.quest.Quest; import org.l2jserver.gameserver.model.quest.QuestState; import org.l2jserver.gameserver.model.quest.State; import org.l2jserver.gameserver.network.serverpackets.SocialAction; public class Q226_TestOfTheHealer extends Quest { // Items private static final int REPORT_OF_PERRIN = 2810; private static final int KRISTINA_LETTER = 2811; private static final int PICTURE_OF_WINDY = 2812; private static final int GOLDEN_STATUE = 2813; private static final int WINDY_PEBBLES = 2814; private static final int ORDER_OF_SORIUS = 2815; private static final int SECRET_LETTER_1 = 2816; private static final int SECRET_LETTER_2 = 2817; private static final int SECRET_LETTER_3 = 2818; private static final int SECRET_LETTER_4 = 2819; // Rewards private static final int MARK_OF_HEALER = 2820; private static final int DIMENSIONAL_DIAMOND = 7562; // NPCs private static final int BANDELLOS = 30473; private static final int SORIUS = 30327; private static final int ALLANA = 30424; private static final int PERRIN = 30428; private static final int GUPU = 30658; private static final int ORPHAN_GIRL = 30659; private static final int WINDY_SHAORING = 30660; private static final int MYSTERIOUS_DARKELF = 30661; private static final int PIPER_LONGBOW = 30662; private static final int SLEIN_SHINING_BLADE = 30663; private static final int KAIN_FLYING_KNIFE = 30664; private static final int KRISTINA = 30665; private static final int DAURIN_HAMMERCRUSH = 30674; // Monsters private static final int LETO_LIZARDMAN_LEADER = 27123; private static final int LETO_LIZARDMAN_ASSASSIN = 27124; private static final int LETO_LIZARDMAN_SNIPER = 27125; private static final int LETO_LIZARDMAN_WIZARD = 27126; private static final int LETO_LIZARDMAN_LORD = 27127; private static final int TATOMA = 27134; private NpcInstance _tatoma; private NpcInstance _letoLeader; public Q226_TestOfTheHealer() { super(226, "Test of the Healer"); registerQuestItems(REPORT_OF_PERRIN, KRISTINA_LETTER, PICTURE_OF_WINDY, GOLDEN_STATUE, WINDY_PEBBLES, ORDER_OF_SORIUS, SECRET_LETTER_1, SECRET_LETTER_2, SECRET_LETTER_3, SECRET_LETTER_4); addStartNpc(BANDELLOS); addTalkId(BANDELLOS, SORIUS, ALLANA, PERRIN, GUPU, ORPHAN_GIRL, WINDY_SHAORING, MYSTERIOUS_DARKELF, PIPER_LONGBOW, SLEIN_SHINING_BLADE, KAIN_FLYING_KNIFE, KRISTINA, DAURIN_HAMMERCRUSH); addKillId(LETO_LIZARDMAN_LEADER, LETO_LIZARDMAN_ASSASSIN, LETO_LIZARDMAN_SNIPER, LETO_LIZARDMAN_WIZARD, LETO_LIZARDMAN_LORD, TATOMA); } @Override public String onAdvEvent(String event, NpcInstance npc, PlayerInstance player) { String htmltext = event; final QuestState st = player.getQuestState(getName()); if (st == null) { return htmltext; } // BANDELLOS if (event.equals("30473-04.htm")) { st.setState(State.STARTED); st.set("cond", "1"); st.playSound(QuestState.SOUND_ACCEPT); st.giveItems(REPORT_OF_PERRIN, 1); if (!player.getVariables().getBoolean("secondClassChange39", false)) { htmltext = "30473-04a.htm"; st.giveItems(DIMENSIONAL_DIAMOND, DF_REWARD_39.get(player.getClassId().getId())); player.getVariables().set("secondClassChange39", true); } } else if (event.equals("30473-09.htm")) { st.takeItems(GOLDEN_STATUE, 1); st.giveItems(MARK_OF_HEALER, 1); st.rewardExpAndSp(134839, 50000); player.broadcastPacket(new SocialAction(player.getObjectId(), 3)); st.playSound(QuestState.SOUND_FINISH); st.exitQuest(false); } // PERRIN else if (event.equals("30428-02.htm")) { st.set("cond", "2"); st.playSound(QuestState.SOUND_MIDDLE); if (_tatoma == null) { _tatoma = addSpawn(TATOMA, -93254, 147559, -2679, 0, false, 0); startQuestTimer("tatoma_despawn", 200000, null, player, false); } } // GUPU else if (event.equals("30658-02.htm")) { if (st.getQuestItemsCount(57) >= 100000) { st.set("cond", "7"); st.playSound(QuestState.SOUND_MIDDLE); st.takeItems(57, 100000); st.giveItems(PICTURE_OF_WINDY, 1); } else { htmltext = "30658-05.htm"; } } else if (event.equals("30658-03.htm")) { st.set("gupu", "1"); } else if (event.equals("30658-07.htm")) { st.set("cond", "9"); st.playSound(QuestState.SOUND_MIDDLE); } // WINDY SHAORING else if (event.equals("30660-03.htm")) { st.set("cond", "8"); st.playSound(QuestState.SOUND_MIDDLE); st.takeItems(PICTURE_OF_WINDY, 1); st.giveItems(WINDY_PEBBLES, 1); } // DAURIN HAMMERCRUSH else if (event.equals("30674-02.htm")) { st.set("cond", "11"); st.playSound(QuestState.SOUND_BEFORE_BATTLE); st.takeItems(ORDER_OF_SORIUS, 1); if (_letoLeader == null) { _letoLeader = addSpawn(LETO_LIZARDMAN_LEADER, -97441, 106585, -3405, 0, false, 0); startQuestTimer("leto_leader_despawn", 200000, null, player, false); } } // KRISTINA else if (event.equals("30665-02.htm")) { st.set("cond", "22"); st.playSound(QuestState.SOUND_MIDDLE); st.takeItems(SECRET_LETTER_1, 1); st.takeItems(SECRET_LETTER_2, 1); st.takeItems(SECRET_LETTER_3, 1); st.takeItems(SECRET_LETTER_4, 1); st.giveItems(KRISTINA_LETTER, 1); } // DESPAWNS else if (event.equals("tatoma_despawn")) { _tatoma.deleteMe(); _tatoma = null; return null; } else if (event.equals("leto_leader_despawn")) { _letoLeader.deleteMe(); _letoLeader = null; return null; } return htmltext; } @Override public String onTalk(NpcInstance npc, PlayerInstance player) { final QuestState st = player.getQuestState(getName()); String htmltext = getNoQuestMsg(); if (st == null) { return htmltext; } switch (st.getState()) { case State.CREATED: if ((player.getClassId() != ClassId.KNIGHT) && (player.getClassId() != ClassId.ELVEN_KNIGHT) && (player.getClassId() != ClassId.CLERIC) && (player.getClassId() != ClassId.ORACLE)) { htmltext = "30473-01.htm"; } else if (player.getLevel() < 39) { htmltext = "30473-02.htm"; } else { htmltext = "30473-03.htm"; } break; case State.STARTED: final int cond = st.getInt("cond"); switch (npc.getNpcId()) { case BANDELLOS: if (cond < 23) { htmltext = "30473-05.htm"; } else { if (!st.hasQuestItems(GOLDEN_STATUE)) { htmltext = "30473-06.htm"; st.giveItems(MARK_OF_HEALER, 1); st.rewardExpAndSp(118304, 26250); player.broadcastPacket(new SocialAction(player.getObjectId(), 3)); st.playSound(QuestState.SOUND_FINISH); st.exitQuest(false); } else { htmltext = "30473-07.htm"; } } break; case PERRIN: if (cond < 3) { htmltext = "30428-01.htm"; } else if (cond == 3) { htmltext = "30428-03.htm"; st.set("cond", "4"); st.playSound(QuestState.SOUND_MIDDLE); st.takeItems(REPORT_OF_PERRIN, 1); } else { htmltext = "30428-04.htm"; } break; case ORPHAN_GIRL: htmltext = "30659-0" + Rnd.get(1, 5) + ".htm"; break; case ALLANA: if (cond == 4) { htmltext = "30424-01.htm"; st.set("cond", "5"); st.playSound(QuestState.SOUND_MIDDLE); } else if (cond > 4) { htmltext = "30424-02.htm"; } break; case GUPU: if ((st.getInt("gupu") == 1) && (cond != 9)) { htmltext = "30658-07.htm"; st.set("cond", "9"); st.playSound(QuestState.SOUND_MIDDLE); } else if (cond == 5) { htmltext = "30658-01.htm"; st.set("cond", "6"); st.playSound(QuestState.SOUND_MIDDLE); } else if (cond == 6) { htmltext = "30658-01.htm"; } else if (cond == 7) { htmltext = "30658-04.htm"; } else if (cond == 8) { htmltext = "30658-06.htm"; st.playSound(QuestState.SOUND_ITEMGET); st.takeItems(WINDY_PEBBLES, 1); st.giveItems(GOLDEN_STATUE, 1); } else if (cond > 8) { htmltext = "30658-07.htm"; } break; case WINDY_SHAORING: if (cond == 7) { htmltext = "30660-01.htm"; } else if (st.hasQuestItems(WINDY_PEBBLES)) { htmltext = "30660-04.htm"; } break; case SORIUS: if (cond == 9) { htmltext = "30327-01.htm"; st.set("cond", "10"); st.playSound(QuestState.SOUND_MIDDLE); st.giveItems(ORDER_OF_SORIUS, 1); } else if ((cond > 9) && (cond < 22)) { htmltext = "30327-02.htm"; } else if (cond == 22) { htmltext = "30327-03.htm"; st.set("cond", "23"); st.playSound(QuestState.SOUND_MIDDLE); st.takeItems(KRISTINA_LETTER, 1); } else if (cond == 23) { htmltext = "30327-04.htm"; } break; case DAURIN_HAMMERCRUSH: if (cond == 10) { htmltext = "30674-01.htm"; } else if (cond == 11) { htmltext = "30674-02a.htm"; if (_letoLeader == null) { _letoLeader = addSpawn(LETO_LIZARDMAN_LEADER, -97441, 106585, -3405, 0, false, 0); startQuestTimer("leto_leader_despawn", 200000, null, player, false); } } else if (cond == 12) { htmltext = "30674-03.htm"; st.set("cond", "13"); st.playSound(QuestState.SOUND_MIDDLE); } else if (cond > 12) { htmltext = "30674-04.htm"; } break; case PIPER_LONGBOW: case SLEIN_SHINING_BLADE: case KAIN_FLYING_KNIFE: if ((cond == 13) || (cond == 14)) { htmltext = npc.getNpcId() + "-01.htm"; } else if ((cond > 14) && (cond < 19)) { htmltext = npc.getNpcId() + "-02.htm"; } else if ((cond > 18) && (cond < 22)) { htmltext = npc.getNpcId() + "-03.htm"; st.set("cond", "21"); st.playSound(QuestState.SOUND_MIDDLE); } break; case MYSTERIOUS_DARKELF: if (cond == 13) { htmltext = "30661-01.htm"; st.set("cond", "14"); st.playSound(QuestState.SOUND_BEFORE_BATTLE); addSpawn(LETO_LIZARDMAN_ASSASSIN, player, true, 0); addSpawn(LETO_LIZARDMAN_ASSASSIN, player, true, 0); addSpawn(LETO_LIZARDMAN_ASSASSIN, player, true, 0); } else if (cond == 14) { htmltext = "30661-01.htm"; } else if (cond == 15) { htmltext = "30661-02.htm"; st.set("cond", "16"); st.playSound(QuestState.SOUND_BEFORE_BATTLE); addSpawn(LETO_LIZARDMAN_SNIPER, player, true, 0); addSpawn(LETO_LIZARDMAN_SNIPER, player, true, 0); addSpawn(LETO_LIZARDMAN_SNIPER, player, true, 0); } else if (cond == 16) { htmltext = "30661-02.htm"; } else if (cond == 17) { htmltext = "30661-03.htm"; st.set("cond", "18"); st.playSound(QuestState.SOUND_BEFORE_BATTLE); addSpawn(LETO_LIZARDMAN_WIZARD, player, true, 0); addSpawn(LETO_LIZARDMAN_WIZARD, player, true, 0); addSpawn(LETO_LIZARDMAN_LORD, player, true, 0); } else if (cond == 18) { htmltext = "30661-03.htm"; } else if (cond == 19) { htmltext = "30661-04.htm"; st.set("cond", "20"); st.playSound(QuestState.SOUND_MIDDLE); } else if ((cond == 20) || (cond == 21)) { htmltext = "30661-04.htm"; } break; case KRISTINA: if ((cond > 18) && (cond < 22)) { htmltext = "30665-01.htm"; } else if (cond > 21) { htmltext = "30665-04.htm"; } else { htmltext = "30665-03.htm"; } break; } break; case State.COMPLETED: htmltext = getAlreadyCompletedMsg(); break; } return htmltext; } @Override public String onKill(NpcInstance npc, PlayerInstance player, boolean isPet) { final QuestState st = checkPlayerState(player, npc, State.STARTED); if (st == null) { return null; } final int cond = st.getInt("cond"); switch (npc.getNpcId()) { case TATOMA: if ((cond == 1) || (cond == 2)) { st.set("cond", "3"); st.playSound(QuestState.SOUND_MIDDLE); } _tatoma = null; cancelQuestTimer("tatoma_despawn", null, player); break; case LETO_LIZARDMAN_LEADER: if ((cond == 10) || (cond == 11)) { st.set("cond", "12"); st.playSound(QuestState.SOUND_MIDDLE); st.giveItems(SECRET_LETTER_1, 1); } _letoLeader = null; cancelQuestTimer("leto_leader_despawn", null, player); break; case LETO_LIZARDMAN_ASSASSIN: if ((cond == 13) || (cond == 14)) { st.set("cond", "15"); st.playSound(QuestState.SOUND_MIDDLE); st.giveItems(SECRET_LETTER_2, 1); } break; case LETO_LIZARDMAN_SNIPER: if ((cond == 15) || (cond == 16)) { st.set("cond", "17"); st.playSound(QuestState.SOUND_MIDDLE); st.giveItems(SECRET_LETTER_3, 1); } break; case LETO_LIZARDMAN_LORD: if ((cond == 17) || (cond == 18)) { st.set("cond", "19"); st.playSound(QuestState.SOUND_MIDDLE); st.giveItems(SECRET_LETTER_4, 1); } break; } return null; } }
package org.broadinstitute.hellbender.utils.read; import com.google.api.services.genomics.model.LinearAlignment; import com.google.api.services.genomics.model.Position; import com.google.api.services.genomics.model.Read; import htsjdk.samtools.*; import htsjdk.samtools.util.StringUtil; import htsjdk.variant.variantcontext.Allele; import org.apache.commons.lang3.ArrayUtils; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.utils.Utils; import org.broadinstitute.hellbender.utils.param.ParamUtils; import org.broadinstitute.hellbender.utils.pileup.PileupElement; import java.util.*; public final class ArtificialReadUtils { public static final int DEFAULT_READ_LENGTH = 50; private static final String DEFAULT_READ_GROUP_PREFIX = "ReadGroup"; private static final String DEFAULT_PLATFORM_UNIT_PREFIX = "Lane"; private static final String DEFAULT_PLATFORM_PREFIX = "Platform"; private static final String DEFAULT_SAMPLE_NAME = "SampleX"; /** * Creates an artificial sam header, matching the parameters, chromosomes which will be labeled chr1, chr2, etc * * @param numberOfChromosomes the number of chromosomes to create * @param startingChromosome the starting number for the chromosome (most likely set to 1) * @param chromosomeSize the length of each chromosome * @return */ public static SAMFileHeader createArtificialSamHeader(int numberOfChromosomes, int startingChromosome, int chromosomeSize) { SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); SAMSequenceDictionary dict = new SAMSequenceDictionary(); // make up some sequence records for (int x = startingChromosome; x < startingChromosome + numberOfChromosomes; x++) { SAMSequenceRecord rec = new SAMSequenceRecord( Integer.toString(x), chromosomeSize /* size */); rec.setSequenceLength(chromosomeSize); dict.addSequence(rec); } header.setSequenceDictionary(dict); return header; } /** * Creates an artificial sam header, matching the parameters, chromosomes which will be labeled chr1, chr2, etc * It also adds read groups. * * @param numberOfChromosomes the number of chromosomes to create * @param startingChromosome the starting number for the chromosome (most likely set to 1) * @param chromosomeSize the length of each chromosome * @param groupCount the number of groups to make */ public static SAMFileHeader createArtificialSamHeaderWithGroups(int numberOfChromosomes, int startingChromosome, int chromosomeSize, int groupCount) { final SAMFileHeader header = createArtificialSamHeader(numberOfChromosomes, startingChromosome, chromosomeSize); final List<SAMReadGroupRecord> readGroups = new ArrayList<>(); for (int i = 0; i < groupCount; i++) { SAMReadGroupRecord rec = new SAMReadGroupRecord(DEFAULT_READ_GROUP_PREFIX + i); rec.setSample(DEFAULT_SAMPLE_NAME); readGroups.add(rec); } header.setReadGroups(readGroups); for (int i = 0; i < groupCount; i++) { final SAMReadGroupRecord groupRecord = header.getReadGroup(readGroups.get(i).getId()); groupRecord.setPlatform(DEFAULT_PLATFORM_PREFIX + ((i % 2)+1)); groupRecord.setPlatformUnit(DEFAULT_PLATFORM_UNIT_PREFIX + ((i % 3)+1)); } return header; } /** * Creates an artificial sam header with standard test parameters * * @return the sam header */ public static SAMFileHeader createArtificialSamHeader() { return createArtificialSamHeader(22, 1, 1000000); } public static SAMFileHeader createArtificialSamHeaderWithReadGroup( final SAMReadGroupRecord readGroup ) { final SAMFileHeader header = createArtificialSamHeader(); header.addReadGroup(readGroup); return header; } /** * Create an artificial GATKRead based on the parameters. The cigar string will be *M, where * is the length of the read * * @param header the SAM header to associate the read with * @param name the name of the read * @param refIndex the reference index, i.e. what chromosome to associate it with * @param alignmentStart where to start the alignment * @param length the length of the read * @return the artificial GATKRead */ public static GATKRead createArtificialRead(SAMFileHeader header, String name, int refIndex, int alignmentStart, int length) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, name, refIndex, alignmentStart, length)); } /** * Create an artificial GATKRead based on the parameters. The cigar string will be *M, where * is the length of the read * * @param header the SAM header to associate the read with * @param name the name of the read * @param refIndex the reference index, i.e. what chromosome to associate it with * @param alignmentStart where to start the alignment * @param bases the sequence of the read * @param qual the qualities of the read * @return the artificial GATKRead */ public static GATKRead createArtificialRead(SAMFileHeader header, String name, int refIndex, int alignmentStart, byte[] bases, byte[] qual) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, name, refIndex, alignmentStart, bases, qual)); } /** * Create an artificial GATKRead based on the parameters. The cigar string will be *M, where * is the length of the read * * @param header the SAM header to associate the read with * @param name the name of the read * @param contig the contig to which the read is aligned * @param alignmentStart where to start the alignment * @param bases the sequence of the read * @param qual the qualities of the read * @return the artificial GATKRead */ public static GATKRead createArtificialRead(SAMFileHeader header, String name, String contig, int alignmentStart, byte[] bases, byte[] qual) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, name, header.getSequenceIndex(contig), alignmentStart, bases, qual)); } /** * Create an artificial GATKRead based on the parameters * * @param header the SAM header to associate the read with * @param name the name of the read * @param refIndex the reference index, i.e. what chromosome to associate it with * @param alignmentStart where to start the alignment * @param bases the sequence of the read * @param qual the qualities of the read * @param cigar the cigar string of the read * @return the artificial GATKRead */ public static GATKRead createArtificialRead(SAMFileHeader header, String name, int refIndex, int alignmentStart, byte[] bases, byte[] qual, String cigar) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, name, refIndex, alignmentStart, bases, qual, cigar)); } /** * Create an artificial GATKRead based on the parameters * * @param header the SAM header to associate the read with * @param name the name of the read * @param contig the contig to which the read is aligned * @param alignmentStart where to start the alignment * @param bases the sequence of the read * @param qual the qualities of the read * @param cigar the cigar string of the read * @return the artificial GATKRead */ public static GATKRead createArtificialRead(SAMFileHeader header, String name, String contig, int alignmentStart, byte[] bases, byte[] qual, String cigar) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, name, header.getSequenceIndex(contig), alignmentStart, bases, qual, cigar)); } /** * Create an artificial GATKRead with the following default parameters : * header: * numberOfChromosomes = 1 * startingChromosome = 1 * chromosomeSize = 1000000 * read: * name = "default_read" * refIndex = 0 * alignmentStart = 10000 * * @param header SAM header for the read * @param bases the sequence of the read * @param qual the qualities of the read * @param cigar the cigar string of the read * @return the artificial GATKRead */ public static GATKRead createArtificialRead(final SAMFileHeader header, final byte[] bases, final byte[] qual, final String cigar) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, "default_read", 0, 10000, bases, qual, cigar)); } public static GATKRead createArtificialRead(final byte[] bases, final byte[] qual, final String cigar) { SAMFileHeader header = createArtificialSamHeader(); return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, "default_read", 0, 10000, bases, qual, cigar)); } public static GATKRead createArtificialRead(final SAMFileHeader header, final String cigarString) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, TextCigarCodec.decode(cigarString))); } public static GATKRead createArtificialRead(final SAMFileHeader header, final Cigar cigar) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(header, cigar)); } public static GATKRead createArtificialRead(final Cigar cigar) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(cigar)); } /** * Makes a new read with a name that is unique (so that it will return false to equals(otherRead) */ public static GATKRead createUniqueArtificialRead(final Cigar cigar) { return new SAMRecordToGATKReadAdapter(createUniqueArtificialSAMRecord(cigar)); } public static GATKRead createArtificialRead(final Cigar cigar, final String name) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(createArtificialSamHeader(), cigar, name)); } public static GATKRead createArtificialRead(final String cigarString) { return new SAMRecordToGATKReadAdapter(createArtificialSAMRecord(TextCigarCodec.decode(cigarString))); } public static GATKRead createArtificialUnmappedRead(final SAMFileHeader header, final byte[] bases, final byte[] qual) { final SAMRecord read = new SAMRecord(header); read.setReadUnmappedFlag(true); read.setReadBases(bases); read.setBaseQualities(qual); return new SAMRecordToGATKReadAdapter(read); } public static GATKRead createArtificialUnmappedReadWithAssignedPosition(final SAMFileHeader header, final String contig, final int alignmentStart, final byte[] bases, final byte[] qual) { final SAMRecord read = new SAMRecord(header); read.setReferenceName(contig); read.setAlignmentStart(alignmentStart); read.setReadUnmappedFlag(true); read.setReadBases(bases); read.setBaseQualities(qual); return new SAMRecordToGATKReadAdapter(read); } /** * Makes a new read with a name that is unique (so that it will return false to equals(otherRead) */ public static GATKRead createUniqueArtificialRead(final String cigarString) { return new SAMRecordToGATKReadAdapter(createUniqueArtificialSAMRecord(TextCigarCodec.decode(cigarString))); } /** * Creates an artificial GATKRead backed by a SAMRecord. * * The read will consist of the specified number of Q30 'A' bases, and will be * mapped to contig "1" at the specified start position. * * @param name name of the new read * @param start start position of the new read * @param length number of bases in the new read * @return an artificial GATKRead backed by a SAMRecord. */ public static GATKRead createSamBackedRead( final String name, final int start, final int length ) { return createSamBackedRead(name, "1", start, length); } /** * Creates an artificial GATKRead backed by a SAMRecord. * * The read will consist of the specified number of Q30 'A' bases, and will be * mapped to the specified contig at the specified start position. * * @param name name of the new read * @param contig contig the new read is mapped to * @param start start position of the new read * @param length number of bases in the new read * @return an artificial GATKRead backed by a SAMRecord. */ public static GATKRead createSamBackedRead( final String name, final String contig, final int start, final int length ) { final SAMFileHeader header = createArtificialSamHeader(); final byte[] bases = Utils.dupBytes((byte)'A', length); final byte[] quals = Utils.dupBytes((byte) 30, length); final SAMRecord sam = createArtificialSAMRecord(header, bases, quals, length + "M"); sam.setReadName(name); sam.setReferenceName(contig); sam.setAlignmentStart(start); return new SAMRecordToGATKReadAdapter(sam); } /** * Creates an artificial GATKRead backed by a SAMRecord with no header. * * The read will consist of the specified number of Q30 'A' bases, and will be * mapped to the specified contig at the specified start position. * * @param name name of the new read * @param contig contig the new read is mapped to * @param start start position of the new read * @param length number of bases in the new read * @return an artificial GATKRead backed by a SAMRecord. */ public static GATKRead createHeaderlessSamBackedRead( final String name, final String contig, final int start, final int length ) { GATKRead read = createSamBackedRead(name, contig, start, length); ((SAMRecordToGATKReadAdapter) read).getEncapsulatedSamRecord().setHeaderStrict(null); return read; } /** * Creates an artificial GATKRead backed by a Google Genomics read. * * The read will consist of the specified number of Q30 'A' bases, and will be * mapped to the specified contig at the specified start position. * * @param name name of the new read * @param contig contig the new read is mapped to * @param start start position of the new read * @param length number of bases in the new read * @return an artificial GATKRead backed by a Google Genomics read. */ public static GATKRead createGoogleBackedRead( final String name, final String contig, final int start, final int length ) { final byte[] bases = Utils.dupBytes((byte) 'A', length); final byte[] quals = Utils.dupBytes((byte) 30, length); final Read googleRead = createArtificialGoogleGenomicsRead(name, contig, start, bases, quals, length + "M"); return new GoogleGenomicsReadToGATKReadAdapter(googleRead); } /** * Create an artificial SAMRecord based on the parameters. The cigar string will be *M, where * is the length of the read * * @param header the SAM header to associate the read with * @param name the name of the read * @param refIndex the reference index, i.e. what chromosome to associate it with * @param alignmentStart where to start the alignment * @param length the length of the read * @return the artificial SAMRecord */ public static SAMRecord createArtificialSAMRecord(SAMFileHeader header, String name, int refIndex, int alignmentStart, int length) { if ((refIndex == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX && alignmentStart != SAMRecord.NO_ALIGNMENT_START) || (refIndex != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX && alignmentStart == SAMRecord.NO_ALIGNMENT_START)) throw new IllegalArgumentException("Invalid alignment start for artificial read, start = " + alignmentStart); SAMRecord record = new SAMRecord(header); record.setReadName(name); record.setReferenceIndex(refIndex); record.setAlignmentStart(alignmentStart); List<CigarElement> elements = new ArrayList<>(); elements.add(new CigarElement(length, CigarOperator.characterToEnum('M'))); record.setCigar(new Cigar(elements)); record.setProperPairFlag(false); // our reads and quals are all 'A's by default byte[] c = new byte[length]; byte[] q = new byte[length]; for (int x = 0; x < length; x++) c[x] = q[x] = 'A'; record.setReadBases(c); record.setBaseQualities(q); if (refIndex == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { record.setReadUnmappedFlag(true); } return record; } /** * Create an artificial SAMRecord based on the parameters. The cigar string will be *M, where * is the length of the read * * @param header the SAM header to associate the read with * @param name the name of the read * @param refIndex the reference index, i.e. what chromosome to associate it with * @param alignmentStart where to start the alignment * @param bases the sequence of the read * @param qual the qualities of the read * @return the artificial SAMRecord */ public static SAMRecord createArtificialSAMRecord(SAMFileHeader header, String name, int refIndex, int alignmentStart, byte[] bases, byte[] qual) { if (bases.length != qual.length) { throw new IllegalArgumentException("Passed in read string is different length then the quality array"); } SAMRecord rec = createArtificialSAMRecord(header, name, refIndex, alignmentStart, bases.length); rec.setReadBases(Arrays.copyOf(bases, bases.length)); rec.setBaseQualities(Arrays.copyOf(qual, qual.length)); rec.setAttribute(SAMTag.PG.name(), new SAMReadGroupRecord("x").getId()); if (refIndex == -1) { rec.setReadUnmappedFlag(true); } return rec; } /** * Create an artificial SAMRecord based on the parameters * * @param header the SAM header to associate the read with * @param name the name of the read * @param refIndex the reference index, i.e. what chromosome to associate it with * @param alignmentStart where to start the alignment * @param bases the sequence of the read * @param qual the qualities of the read * @param cigar the cigar string of the read * @return the artificial SAMRecord */ public static SAMRecord createArtificialSAMRecord(SAMFileHeader header, String name, int refIndex, int alignmentStart, byte[] bases, byte[] qual, String cigar) { SAMRecord rec = createArtificialSAMRecord(header, name, refIndex, alignmentStart, bases, qual); rec.setCigarString(cigar); return rec; } /** * Create an artificial SAMRecord with the following default parameters : * header: * numberOfChromosomes = 1 * startingChromosome = 1 * chromosomeSize = 1000000 * read: * name = "default_read" * refIndex = 0 * alignmentStart = 10000 * * @param header SAM header for the read * @param bases the sequence of the read * @param qual the qualities of the read * @param cigar the cigar string of the read * @return the artificial SAMRecord */ public static SAMRecord createArtificialSAMRecord(final SAMFileHeader header, final byte[] bases, final byte[] qual, final String cigar) { return createArtificialSAMRecord(header, "default_read", 0, 10000, bases, qual, cigar); } public static SAMRecord createArtificialSAMRecord(final byte[] bases, final byte[] qual, final String cigar) { SAMFileHeader header = createArtificialSamHeader(); return createArtificialSAMRecord(header, "default_read", 0, 10000, bases, qual, cigar); } public static SAMRecord createArtificialSAMRecord(final SAMFileHeader header, final Cigar cigar, final String name) { int length = cigar.getReadLength(); byte base = 'A'; byte qual = 30; byte [] bases = Utils.dupBytes(base, length); byte [] quals = Utils.dupBytes(qual, length); return createArtificialSAMRecord(header, name, 0, 10000, bases, quals, cigar.toString()); } public static SAMRecord createArtificialSAMRecord(final SAMFileHeader header, final Cigar cigar) { return createArtificialSAMRecord(header, cigar, "default_read"); } public static SAMRecord createArtificialSAMRecord(final Cigar cigar) { final SAMFileHeader header = createArtificialSamHeader(); return createArtificialSAMRecord(header, cigar, "default_read"); } /** * Makes a new read with a name that is unique (so that it will return false to equals(otherRead) */ public static SAMRecord createUniqueArtificialSAMRecord(final Cigar cigar) { final SAMFileHeader header = createArtificialSamHeader(); return createArtificialSAMRecord(header, cigar, UUID.randomUUID().toString()); } public static Read createArtificialGoogleGenomicsRead( final String name, final String contig, final int start, final byte[] bases, final byte[] quals, final String cigar ) { Read googleRead = new Read(); googleRead.setFragmentName(name); googleRead.setAlignment(new LinearAlignment()); googleRead.getAlignment().setPosition(new Position()); googleRead.getAlignment().getPosition().setReferenceName(contig); googleRead.getAlignment().getPosition().setPosition((long) start - 1); googleRead.setAlignedSequence(StringUtil.bytesToString(bases)); googleRead.getAlignment().setCigar(CigarConversionUtils.convertSAMCigarToCigarUnitList(TextCigarCodec.decode(cigar))); List<Integer> convertedQuals = new ArrayList<>(); for ( byte b : quals ) { convertedQuals.add((int)b); } googleRead.setAlignedQuality(convertedQuals); // Create a fully formed read that can be wrapped by a GATKRead and have a valid // SAMString without GATKRead throwing missing field exceptions. googleRead.setFailedVendorQualityChecks(false); googleRead.setSecondaryAlignment(false); googleRead.setSupplementaryAlignment(false); googleRead.setDuplicateFragment(false); Position matePos = new Position(); matePos.setReverseStrand(false); googleRead.setNextMatePosition(matePos); return googleRead; } public static List<GATKRead> createPair(SAMFileHeader header, String name, int readLen, int leftStart, int rightStart, boolean leftIsFirst, boolean leftIsNegative) { return createPair(header, name, readLen, 0, leftStart, rightStart, leftIsFirst, leftIsNegative); } public static List<GATKRead> createPair(SAMFileHeader header, String name, int readLen, int refIndex, int leftStart, int rightStart, boolean leftIsFirst, boolean leftIsNegative) { GATKRead left = createArtificialRead(header, name, refIndex, leftStart, readLen); GATKRead right = createArtificialRead(header, name, refIndex, rightStart, readLen); left.setIsPaired(true); right.setIsPaired(true); left.setIsProperlyPaired(true); right.setIsProperlyPaired(true); if ( leftIsFirst ) { left.setIsFirstOfPair(); right.setIsSecondOfPair(); } else { left.setIsSecondOfPair(); right.setIsFirstOfPair(); } left.setIsReverseStrand(leftIsNegative); left.setMateIsReverseStrand(!leftIsNegative); right.setIsReverseStrand(!leftIsNegative); right.setMateIsReverseStrand(leftIsNegative); left.setMatePosition(header.getSequence(refIndex).getSequenceName(), right.getStart()); right.setMatePosition(header.getSequence(refIndex).getSequenceName(), left.getStart()); int isize = rightStart + readLen - leftStart; left.setFragmentLength(isize); right.setFragmentLength(-isize); return Arrays.asList(left, right); } /** * Create a collection of identical artificial reads based on the parameters. The cigar string for each * read will be *M, where * is the length of the read. * * Useful for testing things like positional downsampling where you care only about the position and * number of reads, and not the other attributes. * * @param size number of identical reads to create * @param header the SAM header to associate each read with * @param name name associated with each read * @param refIndex the reference index, i.e. what chromosome to associate them with * @param alignmentStart where to start each alignment * @param length the length of each read * * @return a collection of stackSize reads all sharing the above properties */ public static Collection<GATKRead> createIdenticalArtificialReads(final int size, final SAMFileHeader header, final String name, final int refIndex, final int alignmentStart, final int length ) { Utils.validateArg(size >= 0, "size must be non-negative"); final Collection<GATKRead> coll = new ArrayList<>(size); for ( int i = 1; i <= size; i++ ) { coll.add(createArtificialRead(header, name, refIndex, alignmentStart, length)); } return coll; } public static GATKRead createRandomRead(SAMFileHeader header, int length) { List<CigarElement> cigarElements = new LinkedList<>(); cigarElements.add(new CigarElement(length, CigarOperator.M)); Cigar cigar = new Cigar(cigarElements); return createArtificialRead(header, cigar); } public static GATKRead createRandomRead(int length) { SAMFileHeader header = createArtificialSamHeader(); return createRandomRead(header, length); } public static GATKRead createRandomRead(SAMFileHeader header, int length, boolean allowNs) { byte[] quals = createRandomReadQuals(length); byte[] bbases = createRandomReadBases(length, allowNs); return createArtificialRead(bbases, quals, bbases.length + "M"); } public static GATKRead createRandomRead(int length, boolean allowNs) { SAMFileHeader header = createArtificialSamHeader(); return createRandomRead(header, length, allowNs); } /** * Create random read qualities * * @param length the length of the read * @return an array with randomized base qualities between 0 and 50 */ public static byte[] createRandomReadQuals(int length) { Random random = Utils.getRandomGenerator(); byte[] quals = new byte[length]; for (int i = 0; i < length; i++) quals[i] = (byte) random.nextInt(50); return quals; } /** * Create random read qualities * * @param length the length of the read * @param allowNs whether or not to allow N's in the read * @return an array with randomized bases (A-N) with equal probability */ public static byte[] createRandomReadBases(int length, boolean allowNs) { Random random = Utils.getRandomGenerator(); int numberOfBases = allowNs ? 5 : 4; byte[] bases = new byte[length]; for (int i = 0; i < length; i++) { switch (random.nextInt(numberOfBases)) { case 0: bases[i] = 'A'; break; case 1: bases[i] = 'C'; break; case 2: bases[i] = 'G'; break; case 3: bases[i] = 'T'; break; case 4: bases[i] = 'N'; break; default: throw new GATKException("Something went wrong, this is just impossible"); } } return bases; } /** * create an iterator containing the specified read piles * * @param startingChr the chromosome (reference ID) to start from * @param endingChr the id to end with * @param readCount the number of reads per chromosome * @return iterator representing the specified amount of fake data */ public static ArtificialReadQueryIterator mappedReadIterator(int startingChr, int endingChr, int readCount) { SAMFileHeader header = createArtificialSamHeader((endingChr - startingChr) + 1, startingChr, readCount + DEFAULT_READ_LENGTH); return new ArtificialReadQueryIterator(startingChr, endingChr, readCount, 0, header); } /** * create an iterator containing the specified read piles * * @param startingChr the chromosome (reference ID) to start from * @param endingChr the id to end with * @param readCount the number of reads per chromosome * @param unmappedReadCount the count of unmapped reads to place at the end of the iterator, like in a sorted bam file * @return iterator representing the specified amount of fake data */ public static ArtificialReadQueryIterator mappedAndUnmappedReadIterator(int startingChr, int endingChr, int readCount, int unmappedReadCount) { SAMFileHeader header = createArtificialSamHeader((endingChr - startingChr) + 1, startingChr, readCount + DEFAULT_READ_LENGTH); return new ArtificialReadQueryIterator(startingChr, endingChr, readCount, unmappedReadCount, header); } /** * Creates an artificial sam header based on the sequence dictionary dict * * @return a new sam header */ public static SAMFileHeader createArtificialSamHeader(final SAMSequenceDictionary dict) { SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.setSequenceDictionary(dict); return header; } /** * Create a pileupElement with the given insertion added to the bases. * * Assumes the insertion is prepended with one "reference" base. * * @param offsetIntoRead the offset into the read where the insertion Allele should appear. As a reminder, the * insertion allele should have a single ref base prepend. Must be 0 - (lengthOfRead-1) * @param insertionAllele the allele as you would see in a VCF for the insertion. So, it is prepended with a ref base. Never {@code null} * @param lengthOfRead the length of the artificial read. Does not include any length differences due to the spliced indel. Must be greater than zero. * @return pileupElement with an artificial read containing the insertion. */ public static PileupElement createSplicedInsertionPileupElement(int offsetIntoRead, final Allele insertionAllele, final int lengthOfRead) { ParamUtils.isPositive(lengthOfRead, "length of read is invalid for creating an artificial read, must be greater than 0."); ParamUtils.inRange(offsetIntoRead, 0, lengthOfRead-1, "offset into read is invalid for creating an artificial read, must be 0-" + (lengthOfRead-1) + "."); Utils.nonNull(insertionAllele); int remainingReadLength = lengthOfRead - ((offsetIntoRead + 1) + (insertionAllele.getBases().length - 1)); String cigarString = (offsetIntoRead + 1) + "M" + (insertionAllele.getBases().length - 1) + "I"; if (remainingReadLength > 0) { cigarString += (remainingReadLength + "M"); } final Cigar cigar = TextCigarCodec.decode(cigarString); final GATKRead gatkRead = ArtificialReadUtils.createArtificialRead(cigar); final PileupElement pileupElement = PileupElement.createPileupForReadAndOffset(gatkRead, offsetIntoRead); // Splice in that insertion. final byte[] bases = gatkRead.getBases(); final int newReadLength = lengthOfRead + insertionAllele.getBases().length - 1; final byte[] destBases = new byte[newReadLength]; final byte[] basesToInsert = ArrayUtils.subarray(insertionAllele.getBases(), 1, insertionAllele.getBases().length); System.arraycopy(bases, 0, destBases, 0, offsetIntoRead); // Make sure that the one prepended "reference base" matches the input. destBases[offsetIntoRead] = insertionAllele.getBases()[0]; System.arraycopy(basesToInsert, 0, destBases, offsetIntoRead+1, basesToInsert.length); if ((offsetIntoRead + 1) < lengthOfRead) { System.arraycopy(bases, offsetIntoRead + 1, destBases, offsetIntoRead + basesToInsert.length + 1, bases.length - 1 - offsetIntoRead); } gatkRead.setBases(destBases); return pileupElement; } /** See {@link ArtificialReadUtils#createSplicedInsertionPileupElement}, except that this method returns a * pileup element containing the specified deletion. * * @param offsetIntoRead See {@link ArtificialReadUtils#createSplicedInsertionPileupElement} * @param referenceAllele the reference allele as you would see in a VCF for the deletion. * In other words, it is the deletion prepended with a single ref base. Never {@code null} * @param lengthOfRead See {@link ArtificialReadUtils#createSplicedInsertionPileupElement} * @return pileupElement with an artificial read containing the deletion. */ public static PileupElement createSplicedDeletionPileupElement(int offsetIntoRead, final Allele referenceAllele, final int lengthOfRead) { ParamUtils.isPositive(lengthOfRead, "length of read is invalid for creating an artificial read, must be greater than 0."); ParamUtils.inRange(offsetIntoRead, 0, lengthOfRead-1, "offset into read is invalid for creating an artificial read, must be 0-" + (lengthOfRead-1) + "."); Utils.nonNull(referenceAllele); // Do not include the prepended "ref" final int numberOfSpecifiedBasesToDelete = referenceAllele.getBases().length - 1; final int numberOfBasesToActuallyDelete = Math.min(numberOfSpecifiedBasesToDelete, lengthOfRead - offsetIntoRead - 1); final int newReadLength = lengthOfRead - numberOfBasesToActuallyDelete; String cigarString = (offsetIntoRead + 1) + "M"; if (numberOfBasesToActuallyDelete > 0) { cigarString += numberOfBasesToActuallyDelete + "D"; } final int remainingBases = lengthOfRead - (offsetIntoRead + 1) - numberOfBasesToActuallyDelete; if (remainingBases > 0) { cigarString += remainingBases + "M"; } final Cigar cigar = TextCigarCodec.decode(cigarString); final GATKRead gatkRead = ArtificialReadUtils.createArtificialRead(cigar); final PileupElement pileupElement = PileupElement.createPileupForReadAndOffset(gatkRead, offsetIntoRead); // The Cigar string has basically already told the initial generation of a read to delete bases. final byte[] bases = gatkRead.getBases(); // Make sure that the one prepended "reference base" matches the input. bases[offsetIntoRead] = referenceAllele.getBases()[0]; gatkRead.setBases(bases); return pileupElement; } /** * See {@link ArtificialReadUtils#createSplicedInsertionPileupElement}, except that this method returns a * pileup element containing base-by-base replacement. As a result, the length of the read will not change. * * @param offsetIntoRead See {@link ArtificialReadUtils#createSplicedInsertionPileupElement} * @param newAllele The new bases that should be in the read at the specified position. If this allele causes the * replacement to extend beyond the end of the read * (i.e. offsetIntoRead + length(newAllele) is greater than length of read), * the replacement will be truncated. * @param lengthOfRead See {@link ArtificialReadUtils#createSplicedInsertionPileupElement} * @return pileupElement with an artificial read containing the new bases specified by te given allele. */ public static PileupElement createNonIndelPileupElement(final int offsetIntoRead, final Allele newAllele, final int lengthOfRead) { ParamUtils.isPositive(lengthOfRead, "length of read is invalid for creating an artificial read, must be greater than 0."); ParamUtils.inRange(offsetIntoRead, 0, lengthOfRead-1, "offset into read is invalid for creating an artificial read, must be 0-" + (lengthOfRead-1) + "."); Utils.nonNull(newAllele); final String cigarString = lengthOfRead + "M"; final Cigar cigar = TextCigarCodec.decode(cigarString); final GATKRead gatkRead = ArtificialReadUtils.createArtificialRead(cigar); final byte[] newBases = gatkRead.getBases(); final int upperBound = Math.min(offsetIntoRead + newAllele.getBases().length, lengthOfRead); for (int i = offsetIntoRead; i < upperBound; i++) { newBases[i] = newAllele.getBases()[i - offsetIntoRead]; } gatkRead.setBases(newBases); return PileupElement.createPileupForReadAndOffset(gatkRead, offsetIntoRead); } }
// 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.cloud.network.dao; import java.util.List; import javax.ejb.Local; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkVO; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; @Local(value=PhysicalNetworkDao.class) @DB(txn=false) public class PhysicalNetworkDaoImpl extends GenericDaoBase<PhysicalNetworkVO, Long> implements PhysicalNetworkDao { final SearchBuilder<PhysicalNetworkVO> ZoneSearch; protected final PhysicalNetworkTrafficTypeDaoImpl _trafficTypeDao = ComponentLocator.inject(PhysicalNetworkTrafficTypeDaoImpl.class); protected PhysicalNetworkDaoImpl() { super(); ZoneSearch = createSearchBuilder(); ZoneSearch.and("dataCenterId", ZoneSearch.entity().getDataCenterId(), Op.EQ); ZoneSearch.done(); } @Override public List<PhysicalNetworkVO> listByZone(long zoneId) { SearchCriteria<PhysicalNetworkVO> sc = ZoneSearch.create(); sc.setParameters("dataCenterId", zoneId); return search(sc, null); } @Override public List<PhysicalNetworkVO> listByZoneIncludingRemoved(long zoneId) { SearchCriteria<PhysicalNetworkVO> sc = ZoneSearch.create(); sc.setParameters("dataCenterId", zoneId); return listIncludingRemovedBy(sc); } @Override public List<PhysicalNetworkVO> listByZoneAndTrafficType(long dataCenterId, TrafficType trafficType) { SearchBuilder<PhysicalNetworkTrafficTypeVO> trafficTypeSearch = _trafficTypeDao.createSearchBuilder(); PhysicalNetworkTrafficTypeVO trafficTypeEntity = trafficTypeSearch.entity(); trafficTypeSearch.and("trafficType", trafficTypeSearch.entity().getTrafficType(), SearchCriteria.Op.EQ); SearchBuilder<PhysicalNetworkVO> pnSearch = createSearchBuilder(); pnSearch.and("dataCenterId", pnSearch.entity().getDataCenterId(), Op.EQ); pnSearch.join("trafficTypeSearch", trafficTypeSearch, pnSearch.entity().getId(), trafficTypeEntity.getPhysicalNetworkId(), JoinBuilder.JoinType.INNER); SearchCriteria<PhysicalNetworkVO> sc = pnSearch.create(); sc.setJoinParameters("trafficTypeSearch", "trafficType", trafficType); sc.setParameters("dataCenterId", dataCenterId); return listBy(sc); } }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.api.minecraft.world.level.block.piston; import org.spongepowered.api.block.entity.Piston; import org.spongepowered.api.data.value.Value; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.mixin.api.minecraft.world.level.block.entity.BlockEntityMixin_API; import java.util.Set; import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; @Mixin(PistonMovingBlockEntity.class) public abstract class PistonMovingBlockEntityMixin_API extends BlockEntityMixin_API implements Piston { @Override protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.blockState().asImmutable()); values.add(this.extending().asImmutable()); return values; } }
/** * Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.mit.ll.dcds.dcdsdao; import java.util.List; import edu.mit.ll.dcds.common.entity.Form; import edu.mit.ll.dcds.common.entity.FormType; public interface FormDAO extends BaseDAO { public Form getForm(int incidentid, int usersessionid); public Form getForm(long formId); public Form getForm(long seqnum, long seqtime, long incidentid, long formtypeid); public int getFormTypeId(String typename); public List<Form> getForms(int incidentid, int formtypeid); public List<FormType> getFormTypes(); public int updateFormMessage(Form form); }
/** * Ejercicio 09 tema 05 * * Nos dice cuantos dígitos tiene un numero introducido. * * @author José Robles Bastidas */ public class Ejercicio09 { public static void main(String[] args) { int numeroDeDigitos = 1; System.out.print("Introduzca un número entero >>"); int numero = Integer.parseInt(System.console().readLine()); int n = numero; while (n > 10) { n /= 10; numeroDeDigitos++; } System.out.println(numero + " tiene " + numeroDeDigitos + " dígito/s."); } }
/** * Copyright 2014 Brian Sensale * * 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.sensale.qp.quickbooks; /** * Represents an object on a line in a IIF entry. * * @param <T> The type of data the Object represents. */ public class QBObject<T> { T mValue; /** * @return the toString value of the Stored data wrapped in quotes, or "" if empty. */ @Override public String toString() { if(mValue == null || mValue.equals("")) { return ""; } return "\"" + mValue.toString() + "\""; } }
/* Generated By:JJTree: Do not edit this line. AnyKindTest.java Version 6.0 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=true,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package com.brentcroft.util.xpath.ast; import com.brentcroft.util.xpath.gob.Gob; import com.brentcroft.util.xpath.SimpleNode; import com.brentcroft.util.xpath.XParser; import com.brentcroft.util.xpath.XParserVisitor; import com.brentcroft.util.xpath.gob.Selection; public class AnyKindTest extends SimpleNode { public AnyKindTest( int id ) { super( id ); } public AnyKindTest( XParser p, int id ) { super( p, id ); } public Selection accept( XParserVisitor visitor, Gob gob, Selection axis ) { return visitor.visit( this, gob, axis ); } } /* JavaCC - OriginalChecksum=af3bd13a1281b2c9f3c9594c995ff7bd (do not edit this line) */
/** * */ package com.safframework.saf.orm; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.safframework.saf.orm.annotation.Column; import java.lang.reflect.Field; import java.util.List; /** * * @author Tony Shen * */ public class DBDomain { @Column(name = "Id") private Long mId = null; private TableInfo mTableInfo; public Long getId() { return mId; } public DBDomain() { mTableInfo = DBManager.getTableInfo(getClass()); } public int count() { SQLiteDatabase db = DBManager.openDatabase(); Cursor cursor = db.rawQuery("select count(*) from "+mTableInfo.getTableName(),null); int count = 0; if (cursor.moveToNext()) { count = cursor.getInt(0); } return count; } public void save() { final SQLiteDatabase db = DBManager.openDatabase(); final ContentValues values = new ContentValues(); for (Field field : mTableInfo.getFields()) { final String fieldName = mTableInfo.getColumnName(field); Class<?> fieldType = field.getType(); field.setAccessible(true); try { Object value = field.get(this); if (value == null) { values.putNull(fieldName); } else if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) { values.put(fieldName, (Byte) value); } else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) { values.put(fieldName, (Short) value); } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) { values.put(fieldName, (Integer) value); } else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) { values.put(fieldName, (Long) value); } else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) { values.put(fieldName, (Float) value); } else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) { values.put(fieldName, (Double) value); } else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) { values.put(fieldName, (Boolean) value); } else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) { values.put(fieldName, value.toString()); } else if (fieldType.equals(String.class)) { values.put(fieldName, value.toString()); } else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) { values.put(fieldName, (byte[]) value); } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } } if (mId == null) { mId = db.insert(mTableInfo.getTableName(), null, values); } else { db.update(mTableInfo.getTableName(), values, "Id=" + mId, null); } } public void delete() { SQLiteDatabase db = DBManager.openDatabase(); if (mId!=null) { db.delete(mTableInfo.getTableName(), "Id=" + mId, null); } } public void delete(int id) { SQLiteDatabase db = DBManager.openDatabase(); db.delete(mTableInfo.getTableName(), "Id=" + id, null); } public <T extends DBDomain>T get(int id) { return SQLiteUtils.rawQuerySingle(getClass(),"select * from "+mTableInfo.getTableName()+" where Id="+id,null); } public <T extends DBDomain> List<T> getAll() { return executeQuery("select * from "+mTableInfo.getTableName()); } public <T extends DBDomain> List<T> executeQuery(String query) { return SQLiteUtils.rawQuery(getClass() , query ,null); } /** * 支持类似于new Autocomplete().executeQuery("select * from autocomplete where KEY_WORDS = ? and Id = ?","testtest","1");的查询</br> * 表示查询select * from autocomplete where KEY_WORDS = 'testtest' and Id = '1' * @param query * @param args * @return */ public <T extends DBDomain> List<T> executeQuery(String query, String...args) { int length = args.length; if (length==0) { return executeQuery(query); } for(int i=0;i<length;i++) { query = query.replaceFirst("\\?", "'"+args[i]+"'"); } return SQLiteUtils.rawQuery(getClass() , query ,null); } public final void loadFromCursor(Cursor cursor) { for (Field field : mTableInfo.getFields()) { final String fieldName = mTableInfo.getColumnName(field); Class<?> fieldType = field.getType(); final int columnIndex = cursor.getColumnIndex(fieldName); if (columnIndex < 0) { continue; } field.setAccessible(true); try { boolean columnIsNull = cursor.isNull(columnIndex); Object value = null; if (columnIsNull) { field = null; } else if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) { value = cursor.getInt(columnIndex); } else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) { value = cursor.getInt(columnIndex); } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) { value = cursor.getInt(columnIndex); } else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) { value = cursor.getLong(columnIndex); } else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) { value = cursor.getFloat(columnIndex); } else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) { value = cursor.getDouble(columnIndex); } else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) { value = cursor.getInt(columnIndex) != 0; } else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) { value = cursor.getString(columnIndex).charAt(0); } else if (fieldType.equals(String.class)) { value = cursor.getString(columnIndex); } else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) { value = cursor.getBlob(columnIndex); } // Set the field value if (value != null) { field.set(this, value); } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (SecurityException e) { } } if (mId != null) { DBManager.addEntity(this); } } @Override public String toString() { return mTableInfo.getTableName() + "@" + getId(); } @Override public boolean equals(Object obj) { final DBDomain other = (DBDomain) obj; return this.mId != null && (this.mTableInfo.getTableName().equals(other.mTableInfo.getTableName())) && (this.mId.equals(other.mId)); } @Override public int hashCode() { int result = mId.hashCode(); result = 31 * result + mTableInfo.hashCode(); return result; } }
package com.thealgorithms.dynamicprogramming; import java.util.Scanner; /** * Given a string containing just the characters '(' and ')', find the length of * the longest valid (well-formed) parentheses substring. * 给定一个括号序列A,求其最长合法括号子串的长度。 * * 考虑一个括号序列合法的充要条件。它含两个条件: * 1、左右括号个数相等; * 2、任意前缀中左括号个数不小于右括号个数。 * * @author Libin Yang (https://github.com/yanglbme) * @since 2018/10/5 */ public class LongestValidParentheses { public static int getLongestValidParentheses(String s) { if (s == null || s.length() < 2) { return 0; } char[] chars = s.toCharArray(); int n = chars.length; int[] res = new int[n]; res[0] = 0; res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; int max = res[1]; for (int i = 2; i < n; ++i) { if (chars[i] == ')') { if (chars[i - 1] == '(') { res[i] = res[i - 2] + 2; } else { int index = i - res[i - 1] - 1; if (index >= 0 && chars[index] == '(') { // ()(()) res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); } } } max = Math.max(max, res[i]); } return max; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { String str = sc.nextLine(); if ("quit".equals(str)) { break; } System.out.println("Len is: " + getLongestValidParentheses(str)); } sc.close(); } }
package de.soderer.utilities; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import javax.crypto.Cipher; import de.soderer.utilities.collection.CaseInsensitiveMap; public class SystemUtilities { private static final boolean isWindows = getOsName().toLowerCase().contains("windows"); private static final boolean isLinux = getOsName().toLowerCase().contains("unix") || getOsName().toLowerCase().contains("linux"); public static final String SYSTEM_PARAMETER_NAME_CURRENT_RUNNING_JAR = "process.jar"; public static String getOsName() { return System.getProperty("os.name"); } public static boolean isWindowsSystem() { return isWindows; } public static boolean isLinuxSystem() { return isLinux; } public static int getProcessId() { final String data = ManagementFactory.getRuntimeMXBean().getName(); if (data.contains("@")) { return Integer.parseInt(data.substring(0, data.indexOf("@"))); } else if (isLinuxSystem()) { return Integer.parseInt(data); } else { return -1; } } public static String getJavaBinPath() { final String javaHomePath = System.getProperty("java.home"); if (javaHomePath == null) { return null; } else { File javaBinFile; if (SystemUtilities.isLinuxSystem()) { javaBinFile = new File(javaHomePath + File.separator + "bin" + File.separator + "java"); } else if (System.console() == null) { javaBinFile = new File(javaHomePath + File.separator + "bin" + File.separator + "java.exe"); } else { javaBinFile = new File(javaHomePath + File.separator + "bin" + File.separator + "javaw.exe"); } if (javaBinFile.exists() && !javaBinFile.isDirectory()) { return javaBinFile.getAbsolutePath(); } else { return null; } } } public static long getUptimeInMillis() { return ManagementFactory.getRuntimeMXBean().getUptime(); } public static Date getStarttime() { return new Date(ManagementFactory.getRuntimeMXBean().getStartTime()); } public static List<String> getJavaStartupArguments() { return ManagementFactory.getRuntimeMXBean().getInputArguments(); } public static Map<String, String> getRuntimeProperties(final boolean humanReadable) { final Runtime runtime = Runtime.getRuntime(); final Map<String, String> resultMap = new CaseInsensitiveMap<>(); if (humanReadable) { resultMap.put("memory.total", Utilities.getHumanReadableNumber(runtime.totalMemory(), "Byte", false, 5, false, Locale.ENGLISH)); resultMap.put("memory.free", Utilities.getHumanReadableNumber(runtime.freeMemory(), "Byte", false, 5, false, Locale.ENGLISH)); resultMap.put("memory.used", Utilities.getHumanReadableNumber(runtime.totalMemory() - runtime.freeMemory(), "Byte", false, 5, false, Locale.ENGLISH)); resultMap.put("memory.max", Utilities.getHumanReadableNumber(runtime.maxMemory(), "Byte", false, 5, false, Locale.ENGLISH)); } else { resultMap.put("memory.total", Long.toString(runtime.totalMemory())); resultMap.put("memory.free", Long.toString(runtime.freeMemory())); resultMap.put("memory.used", Long.toString(runtime.totalMemory() - runtime.freeMemory())); resultMap.put("memory.max", Long.toString(runtime.maxMemory())); } resultMap.put("processors.available", Long.toString(runtime.availableProcessors())); resultMap.put("process.id", Integer.toString(SystemUtilities.getProcessId())); resultMap.put("process.uptime", Long.toString(getUptimeInMillis())); resultMap.put("process.starttime", getStarttime().toString()); resultMap.put("process.javastartuparguments", getJavaStartupArguments().toString()); resultMap.put("process.jar", System.getProperty(SYSTEM_PARAMETER_NAME_CURRENT_RUNNING_JAR) == null ? "<unknown>" : System.getProperty(SYSTEM_PARAMETER_NAME_CURRENT_RUNNING_JAR)); resultMap.put("cryptography.unlimitedKeyStrength", isUnlimitedKeyStrengthAllowed() ? "true" : "false"); return resultMap; } public static List<String> getProcessListRaw() { try { final List<String> data = new ArrayList<>(); Process p; if (getOsName().toLowerCase().contains("windows")) { p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe"); } else { p = Runtime.getRuntime().exec("ps -e"); } try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = input.readLine()) != null) { data.add(line); } } return data; } catch (final Exception e) { e.printStackTrace(); return null; } } public static boolean isJavaWebstartApp() { return System.getProperty("javawebstart.version") != null; } public static boolean isUnlimitedKeyStrengthAllowed() { try { return Cipher.getMaxAllowedKeyLength("AES") == Integer.MAX_VALUE; } catch (@SuppressWarnings("unused") final NoSuchAlgorithmException e) { return false; } } }
package hudson.plugins.jira; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import hudson.EnvVars; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.plugins.jira.extension.ExtendedVersion; import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.powermock.reflect.Whitebox; @RunWith(MockitoJUnitRunner.class) public class VersionReleaserTest { private static final String JIRA_VER = Long.toString(System.currentTimeMillis()); private static final String JIRA_PRJ = "TEST_PRJ"; private static final String JIRA_DES = "TEST_DES"; private static final String JIRA_VER_PARAM = "${JIRA_VER}"; private static final String JIRA_PRJ_PARAM = "${JIRA_PRJ}"; private static final String JIRA_DES_PARAM = "${JIRA_DES}"; private static final Long ANY_ID = System.currentTimeMillis(); private static final DateTime ANY_DATE = new DateTime(); @Mock AbstractBuild build; @Mock BuildListener listener; @Mock PrintStream logger; @Mock EnvVars env; @Mock AbstractProject project; @Mock JiraSite site; @Mock JiraSession session; @Captor ArgumentCaptor<ExtendedVersion> versionCaptor; @Captor ArgumentCaptor<String> projectCaptor; private VersionReleaser versionReleaser = spy(VersionReleaser.class); private ExtendedVersion existingVersion = new ExtendedVersion(null, ANY_ID, JIRA_VER, JIRA_DES, false, false, ANY_DATE, ANY_DATE); @Before public void createMocks() throws Exception { Whitebox.setInternalState(site,"jiraSession", session); when(build.getEnvironment(listener)).thenReturn(env); when(env.expand(Mockito.anyString())).thenAnswer((Answer<String>) invocationOnMock -> { Object[] args = invocationOnMock.getArguments(); String expanded = (String) args[0]; if (expanded.equals(JIRA_PRJ_PARAM)) return JIRA_PRJ; else if (expanded.equals(JIRA_VER_PARAM)) return JIRA_VER; else if (expanded.equals(JIRA_DES_PARAM)) return JIRA_DES; else return expanded; }); when(listener.getLogger()).thenReturn(logger); doReturn(site).when(versionReleaser).getSiteForProject(any()); } @Test public void callsJiraWithSpecifiedParameters() { when(session.getVersions(JIRA_PRJ)).thenReturn(Collections.singletonList(existingVersion)); when(site.getVersions(JIRA_PRJ)).thenReturn(new HashSet<>(Arrays.asList(existingVersion))); when(site.getSession(any())).thenReturn(session); versionReleaser.perform(project, JIRA_PRJ, JIRA_VER, JIRA_DES, build, listener); verify(session).releaseVersion(projectCaptor.capture(), versionCaptor.capture()); assertThat(projectCaptor.getValue(), is(JIRA_PRJ)); assertThat(versionCaptor.getValue().getName(), is(JIRA_VER)); assertThat(versionCaptor.getValue().getDescription(), is(JIRA_DES)); } @Test public void expandsEnvParameters() { when(session.getVersions(JIRA_PRJ)).thenReturn(Collections.singletonList(existingVersion)); when(site.getVersions(JIRA_PRJ)).thenReturn(new HashSet<>(Arrays.asList(existingVersion))); when(site.getSession(any())).thenReturn(session); versionReleaser.perform(project, JIRA_PRJ_PARAM, JIRA_VER_PARAM, JIRA_DES_PARAM, build, listener); verify(session).releaseVersion(projectCaptor.capture(), versionCaptor.capture()); assertThat(projectCaptor.getValue(), is(JIRA_PRJ)); assertThat(versionCaptor.getValue().getName(), is(JIRA_VER)); assertThat(versionCaptor.getValue().getDescription(), is(JIRA_DES)); } @Test public void buildDidNotFailWhenVersionExists() { ExtendedVersion releasedVersion = new ExtendedVersion(null, ANY_ID, JIRA_VER, JIRA_DES, false, true, ANY_DATE, ANY_DATE); when(site.getVersions(JIRA_PRJ)).thenReturn(new HashSet<>(Arrays.asList(releasedVersion))); versionReleaser.perform(project, JIRA_PRJ_PARAM, JIRA_VER_PARAM, JIRA_DES_PARAM, build, listener); verify(session, times(0)) .releaseVersion(projectCaptor.capture(), versionCaptor.capture()); } }
/******************************************************************************* * ___ _ ____ ____ * / _ \ _ _ ___ ___| |_| _ \| __ ) * | | | | | | |/ _ \/ __| __| | | | _ \ * | |_| | |_| | __/\__ \ |_| |_| | |_) | * \__\_\\__,_|\___||___/\__|____/|____/ * * Copyright (c) 2014-2019 Appsicle * Copyright (c) 2019-2020 QuestDB * * 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 io.questdb; import io.questdb.cairo.CommitMode; import io.questdb.cairo.PartitionBy; import io.questdb.cairo.security.AllowAllCairoSecurityContext; import io.questdb.cutlass.json.JsonException; import io.questdb.cutlass.line.*; import io.questdb.log.Log; import io.questdb.log.LogFactory; import io.questdb.network.EpollFacadeImpl; import io.questdb.network.IOOperation; import io.questdb.network.NetworkFacadeImpl; import io.questdb.network.SelectFacadeImpl; import io.questdb.std.FilesFacadeImpl; import io.questdb.std.Misc; import io.questdb.std.datetime.microtime.MicrosecondClockImpl; import io.questdb.std.datetime.millitime.MillisecondClockImpl; import io.questdb.test.tools.TestUtils; import org.junit.*; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class PropServerConfigurationTest { @ClassRule public static final TemporaryFolder temp = new TemporaryFolder(); private final static Log LOG = LogFactory.getLog(PropServerConfigurationTest.class); private static String root; @AfterClass public static void afterClass() { TestUtils.removeTestPath(root); } @BeforeClass public static void setupMimeTypes() throws IOException { File root = new File(temp.getRoot(), "root"); TestUtils.copyMimeTypes(root.getAbsolutePath()); PropServerConfigurationTest.root = root.getAbsolutePath(); } @Test public void testAllDefaults() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); PropServerConfiguration configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertEquals(16, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getConnectionPoolInitialCapacity()); Assert.assertEquals(128, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getConnectionStringPoolCapacity()); Assert.assertEquals(512, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getMultipartHeaderBufferSize()); Assert.assertEquals(10_000, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getMultipartIdleSpinCount()); Assert.assertEquals(1048576, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getRecvBufferSize()); Assert.assertEquals(64448, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getRequestHeaderBufferSize()); Assert.assertFalse(configuration.getHttpServerConfiguration().haltOnError()); Assert.assertFalse(configuration.getHttpServerConfiguration().haltOnError()); Assert.assertEquals(2097152, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getSendBufferSize()); Assert.assertEquals("index.html", configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getIndexFileName()); Assert.assertTrue(configuration.getHttpServerConfiguration().isEnabled()); Assert.assertFalse(configuration.getHttpServerConfiguration().getHttpContextConfiguration().getDumpNetworkTraffic()); Assert.assertFalse(configuration.getHttpServerConfiguration().getHttpContextConfiguration().allowDeflateBeforeSend()); Assert.assertEquals(16, configuration.getHttpServerConfiguration().getQueryCacheRows()); Assert.assertEquals(4, configuration.getHttpServerConfiguration().getQueryCacheBlocks()); // this is going to need interesting validation logic // configuration path is expected to be relative and we need to check if absolute path is good Assert.assertEquals(new File(root, "public").getAbsolutePath(), configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getPublicDirectory()); Assert.assertEquals("Keep-Alive: timeout=5, max=10000" + Misc.EOL, configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getKeepAliveHeader()); Assert.assertEquals(256, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getActiveConnectionLimit()); Assert.assertEquals(1024, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getEventCapacity()); Assert.assertEquals(1024, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getIOQueueCapacity()); Assert.assertEquals(300000, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getIdleConnectionTimeout()); Assert.assertEquals(5000, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getQueuedConnectionTimeout()); Assert.assertEquals(1024, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getInterestQueueCapacity()); Assert.assertEquals(IOOperation.READ, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getInitialBias()); Assert.assertEquals(256, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getListenBacklog()); Assert.assertEquals(2097152, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getSndBufSize()); Assert.assertEquals(2097152, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getRcvBufSize()); Assert.assertEquals(16, configuration.getCairoConfiguration().getTextConfiguration().getDateAdapterPoolCapacity()); Assert.assertEquals(16384, configuration.getCairoConfiguration().getTextConfiguration().getJsonCacheLimit()); Assert.assertEquals(8192, configuration.getCairoConfiguration().getTextConfiguration().getJsonCacheSize()); Assert.assertEquals(0.1222d, configuration.getCairoConfiguration().getTextConfiguration().getMaxRequiredDelimiterStdDev(), 0.000000001); Assert.assertEquals(0.8, configuration.getCairoConfiguration().getTextConfiguration().getMaxRequiredLineLengthStdDev(), 0.000000001); Assert.assertEquals(128, configuration.getCairoConfiguration().getTextConfiguration().getMetadataStringPoolCapacity()); Assert.assertEquals(1024 * 4096, configuration.getCairoConfiguration().getTextConfiguration().getRollBufferLimit()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getTextConfiguration().getRollBufferSize()); Assert.assertEquals(1000, configuration.getCairoConfiguration().getTextConfiguration().getTextAnalysisMaxLines()); Assert.assertEquals(64, configuration.getCairoConfiguration().getTextConfiguration().getTextLexerStringPoolCapacity()); Assert.assertEquals(64, configuration.getCairoConfiguration().getTextConfiguration().getTimestampAdapterPoolCapacity()); Assert.assertEquals(4096, configuration.getCairoConfiguration().getTextConfiguration().getUtf8SinkSize()); Assert.assertEquals(0, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getBindIPv4Address()); Assert.assertEquals(9000, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getBindPort()); Assert.assertEquals(1_000_000, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getConnectionCheckFrequency()); Assert.assertEquals(4, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getFloatScale()); Assert.assertEquals(12, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getDoubleScale()); Assert.assertEquals("Keep-Alive: timeout=5, max=10000" + Misc.EOL, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getKeepAliveHeader()); Assert.assertFalse(configuration.getHttpServerConfiguration().getHttpContextConfiguration().readOnlySecurityContext()); Assert.assertEquals(Long.MAX_VALUE, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getMaxQueryResponseRowLimit()); Assert.assertTrue(configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getInterruptorConfiguration().isEnabled()); Assert.assertEquals(2_000_000, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getInterruptorConfiguration().getCountOfIterationsPerCheck()); Assert.assertEquals(64, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getInterruptorConfiguration().getBufferSize()); Assert.assertEquals(CommitMode.NOSYNC, configuration.getCairoConfiguration().getCommitMode()); Assert.assertEquals(2097152, configuration.getCairoConfiguration().getSqlCopyBufferSize()); Assert.assertEquals(32, configuration.getCairoConfiguration().getCopyPoolCapacity()); Assert.assertEquals(5, configuration.getCairoConfiguration().getCreateAsSelectRetryCount()); Assert.assertEquals("fast", configuration.getCairoConfiguration().getDefaultMapType()); Assert.assertTrue(configuration.getCairoConfiguration().getDefaultSymbolCacheFlag()); Assert.assertEquals(256, configuration.getCairoConfiguration().getDefaultSymbolCapacity()); Assert.assertEquals(30, configuration.getCairoConfiguration().getFileOperationRetryCount()); Assert.assertEquals(300000, configuration.getCairoConfiguration().getIdleCheckInterval()); Assert.assertEquals(120_000, configuration.getCairoConfiguration().getInactiveReaderTTL()); Assert.assertEquals(600_000, configuration.getCairoConfiguration().getInactiveWriterTTL()); Assert.assertEquals(256, configuration.getCairoConfiguration().getIndexValueBlockSize()); Assert.assertEquals(30, configuration.getCairoConfiguration().getMaxSwapFileCount()); Assert.assertEquals(509, configuration.getCairoConfiguration().getMkDirMode()); Assert.assertEquals(8, configuration.getCairoConfiguration().getBindVariablePoolSize()); Assert.assertEquals(100000, configuration.getCairoConfiguration().getParallelIndexThreshold()); Assert.assertEquals(5, configuration.getCairoConfiguration().getReaderPoolMaxSegments()); Assert.assertEquals(1_000_000, configuration.getCairoConfiguration().getSpinLockTimeoutUs()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getSqlCharacterStoreCapacity()); Assert.assertEquals(64, configuration.getCairoConfiguration().getSqlCharacterStoreSequencePoolCapacity()); Assert.assertEquals(4096, configuration.getCairoConfiguration().getSqlColumnPoolCapacity()); Assert.assertEquals(0.7, configuration.getCairoConfiguration().getSqlCompactMapLoadFactor(), 0.000001); Assert.assertEquals(8192, configuration.getCairoConfiguration().getSqlExpressionPoolCapacity()); Assert.assertEquals(0.5, configuration.getCairoConfiguration().getSqlFastMapLoadFactor(), 0.0000001); Assert.assertEquals(64, configuration.getCairoConfiguration().getSqlJoinContextPoolCapacity()); Assert.assertEquals(2048, configuration.getCairoConfiguration().getSqlLexerPoolCapacity()); Assert.assertEquals(2097152, configuration.getCairoConfiguration().getSqlMapKeyCapacity()); Assert.assertEquals(4 * 1024 * 1024, configuration.getCairoConfiguration().getSqlMapPageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlMapMaxPages()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlMapMaxResizes()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getSqlModelPoolCapacity()); Assert.assertEquals(4 * 1024 * 1024, configuration.getCairoConfiguration().getSqlSortKeyPageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlSortKeyMaxPages()); Assert.assertEquals(8 * 1024 * 1024, configuration.getCairoConfiguration().getSqlSortLightValuePageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlSortLightValueMaxPages()); Assert.assertEquals(16 * 1024 * 1024, configuration.getCairoConfiguration().getSqlHashJoinValuePageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlHashJoinValueMaxPages()); Assert.assertEquals(1000, configuration.getCairoConfiguration().getSqlLatestByRowCount()); Assert.assertEquals(1024 * 1024, configuration.getCairoConfiguration().getSqlHashJoinLightValuePageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlHashJoinLightValueMaxPages()); Assert.assertEquals(16 * 1024 * 1024, configuration.getCairoConfiguration().getSqlSortValuePageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlSortValueMaxPages()); Assert.assertEquals(10000, configuration.getCairoConfiguration().getWorkStealTimeoutNanos()); Assert.assertTrue(configuration.getCairoConfiguration().isParallelIndexingEnabled()); Assert.assertEquals(16 * 1024, configuration.getCairoConfiguration().getSqlJoinMetadataPageSize()); Assert.assertEquals(Integer.MAX_VALUE, configuration.getCairoConfiguration().getSqlJoinMetadataMaxResizes()); Assert.assertEquals(64, configuration.getCairoConfiguration().getAnalyticColumnPoolCapacity()); Assert.assertEquals(128, configuration.getCairoConfiguration().getWithClauseModelPoolCapacity()); Assert.assertEquals(16, configuration.getCairoConfiguration().getRenameTableModelPoolCapacity()); Assert.assertEquals(64, configuration.getCairoConfiguration().getInsertPoolCapacity()); Assert.assertEquals(16, configuration.getCairoConfiguration().getColumnCastModelPoolCapacity()); Assert.assertEquals(16, configuration.getCairoConfiguration().getCreateTableModelPoolCapacity()); Assert.assertEquals(0, configuration.getLineUdpReceiverConfiguration().getBindIPv4Address()); Assert.assertEquals(9009, configuration.getLineUdpReceiverConfiguration().getPort()); Assert.assertEquals(-402587133, configuration.getLineUdpReceiverConfiguration().getGroupIPv4Address()); Assert.assertEquals(1000000, configuration.getLineUdpReceiverConfiguration().getCommitRate()); Assert.assertEquals(2048, configuration.getLineUdpReceiverConfiguration().getMsgBufferSize()); Assert.assertEquals(10000, configuration.getLineUdpReceiverConfiguration().getMsgCount()); Assert.assertEquals(8388608, configuration.getLineUdpReceiverConfiguration().getReceiveBufferSize()); Assert.assertSame(AllowAllCairoSecurityContext.INSTANCE, configuration.getLineUdpReceiverConfiguration().getCairoSecurityContext()); Assert.assertTrue(configuration.getLineUdpReceiverConfiguration().isEnabled()); Assert.assertEquals(-1, configuration.getLineUdpReceiverConfiguration().ownThreadAffinity()); Assert.assertFalse(configuration.getLineUdpReceiverConfiguration().ownThread()); // statics Assert.assertSame(FilesFacadeImpl.INSTANCE, configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getFilesFacade()); Assert.assertSame(MillisecondClockImpl.INSTANCE, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getClock()); Assert.assertSame(MillisecondClockImpl.INSTANCE, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getClock()); Assert.assertSame(NetworkFacadeImpl.INSTANCE, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getNetworkFacade()); Assert.assertSame(EpollFacadeImpl.INSTANCE, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getEpollFacade()); Assert.assertSame(SelectFacadeImpl.INSTANCE, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getSelectFacade()); Assert.assertSame(FilesFacadeImpl.INSTANCE, configuration.getCairoConfiguration().getFilesFacade()); Assert.assertSame(MillisecondClockImpl.INSTANCE, configuration.getCairoConfiguration().getMillisecondClock()); Assert.assertSame(MicrosecondClockImpl.INSTANCE, configuration.getCairoConfiguration().getMicrosecondClock()); Assert.assertSame(NetworkFacadeImpl.INSTANCE, configuration.getLineUdpReceiverConfiguration().getNetworkFacade()); Assert.assertEquals("http-server", configuration.getHttpServerConfiguration().getDispatcherConfiguration().getDispatcherLogName()); TestUtils.assertEquals(new File(root, "db").getAbsolutePath(), configuration.getCairoConfiguration().getRoot()); // assert mime types TestUtils.assertEquals("application/json", configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getMimeTypesCache().get("json")); Assert.assertEquals(500000, configuration.getCairoConfiguration().getMaxUncommittedRows()); // influxdb line TCP protocol Assert.assertTrue(configuration.getLineTcpReceiverConfiguration().isEnabled()); Assert.assertEquals(256, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getActiveConnectionLimit()); Assert.assertEquals(0, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getBindIPv4Address()); Assert.assertEquals(9009, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getBindPort()); Assert.assertEquals(1024, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getEventCapacity()); Assert.assertEquals(256, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getIOQueueCapacity()); Assert.assertEquals(0, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getIdleConnectionTimeout()); Assert.assertEquals(5000, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getQueuedConnectionTimeout()); Assert.assertEquals(1024, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getInterestQueueCapacity()); Assert.assertEquals(50_000, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getListenBacklog()); Assert.assertEquals(-1, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getRcvBufSize()); Assert.assertEquals(-1, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getSndBufSize()); Assert.assertEquals(64, configuration.getLineTcpReceiverConfiguration().getConnectionPoolInitialCapacity()); Assert.assertEquals(LineProtoNanoTimestampAdapter.INSTANCE, configuration.getLineTcpReceiverConfiguration().getTimestampAdapter()); Assert.assertEquals(32768, configuration.getLineTcpReceiverConfiguration().getNetMsgBufferSize()); Assert.assertEquals(4096, configuration.getLineTcpReceiverConfiguration().getMaxMeasurementSize()); Assert.assertEquals(128, configuration.getLineTcpReceiverConfiguration().getWriterQueueCapacity()); Assert.assertEquals(1, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getWorkerCount()); Assert.assertEquals(10, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getYieldThreshold()); Assert.assertEquals(10_000, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getSleepThreshold()); Assert.assertArrayEquals(new int[]{-1}, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getWorkerAffinity()); Assert.assertFalse(configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().haltOnError()); Assert.assertEquals(10, configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().getYieldThreshold()); Assert.assertEquals(10_000, configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().getSleepThreshold()); Assert.assertFalse(configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().haltOnError()); Assert.assertEquals(10_000_000, configuration.getLineTcpReceiverConfiguration().getNUpdatesPerLoadRebalance()); Assert.assertEquals(1.9, configuration.getLineTcpReceiverConfiguration().getMaxLoadRatio(), 0.001); Assert.assertEquals(30_000, configuration.getLineTcpReceiverConfiguration().getMaintenanceInterval()); Assert.assertEquals(PartitionBy.DAY, configuration.getLineTcpReceiverConfiguration().getDefaultPartitionBy()); Assert.assertEquals(0, configuration.getLineTcpReceiverConfiguration().getAggressiveReadRetryCount()); Assert.assertEquals(10_000, configuration.getLineTcpReceiverConfiguration().getWriterIdleTimeout()); Assert.assertEquals(0, configuration.getCairoConfiguration().getSampleByIndexSearchPageSize()); Assert.assertTrue(configuration.getHttpServerConfiguration().getHttpContextConfiguration().getServerKeepAlive()); Assert.assertEquals("HTTP/1.1 ", configuration.getHttpServerConfiguration().getHttpContextConfiguration().getHttpVersion()); Assert.assertEquals(16777216, configuration.getCairoConfiguration().getAppendPageSize()); Assert.assertEquals("Unknown Version", configuration.getCairoConfiguration().getBuildInformation().getQuestDbVersion()); Assert.assertEquals("Unknown Version", configuration.getCairoConfiguration().getBuildInformation().getJdkVersion()); Assert.assertEquals("Unknown Version", configuration.getCairoConfiguration().getBuildInformation().getCommitHash()); Assert.assertFalse(configuration.getMetricsConfiguration().isEnabled()); } @Test public void testEnvOverrides() throws ServerConfigurationException, JsonException { final Properties properties = new Properties(); final Map<String, String> env = new HashMap<>(); // double properties.setProperty("http.text.max.required.delimiter.stddev", "1.2"); env.put("QDB_HTTP_TEXT_MAX_REQUIRED_DELIMITER_STDDEV", "1.5"); // int properties.setProperty("http.connection.string.pool.capacity", "1200"); env.put("QDB_HTTP_CONNECTION_STRING_POOL_CAPACITY", "3000"); // string properties.setProperty("http.version", "1.0"); env.put("QDB_HTTP_VERSION", "2.0"); // affinity properties.setProperty("shared.worker.count", "2"); properties.setProperty("shared.worker.affinity", "2,3"); env.put("QDB_SHARED_WORKER_COUNT", "3"); env.put("QDB_SHARED_WORKER_AFFINITY", "5,6,7"); // int size properties.setProperty("http.send.buffer.size", "4k"); env.put("QDB_HTTP_SEND_BUFFER_SIZE", "12k"); // long properties.setProperty("http.multipart.idle.spin.count", "400"); env.put("QDB_HTTP_MULTIPART_IDLE_SPIN_COUNT", "900"); // boolean properties.setProperty("http.security.readonly", "true"); env.put("QDB_HTTP_SECURITY_READONLY", "false"); // long size properties.setProperty("cairo.sql.append.page.size", "3G"); env.put("QDB_CAIRO_SQL_APPEND_PAGE_SIZE", "9G"); PropServerConfiguration configuration = new PropServerConfiguration(root, properties, env, LOG, new BuildInformationHolder()); Assert.assertEquals(1.5, configuration.getCairoConfiguration().getTextConfiguration().getMaxRequiredDelimiterStdDev(), 0.000001); Assert.assertEquals(3000, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getConnectionStringPoolCapacity()); Assert.assertEquals("2.0 ", configuration.getHttpServerConfiguration().getHttpContextConfiguration().getHttpVersion()); Assert.assertEquals(3, configuration.getWorkerPoolConfiguration().getWorkerCount()); Assert.assertArrayEquals(new int[]{5, 6, 7}, configuration.getWorkerPoolConfiguration().getWorkerAffinity()); Assert.assertEquals(12288, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getSendBufferSize()); Assert.assertEquals(900, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getMultipartIdleSpinCount()); Assert.assertFalse(configuration.getHttpServerConfiguration().getHttpContextConfiguration().readOnlySecurityContext()); Assert.assertEquals(9663676416L, configuration.getCairoConfiguration().getAppendPageSize()); } @Test public void testHttpDisabled() throws IOException, ServerConfigurationException, JsonException { try (InputStream is = PropServerConfigurationTest.class.getResourceAsStream("/server-http-disabled.conf")) { Properties properties = new Properties(); properties.load(is); PropServerConfiguration configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertFalse(configuration.getHttpServerConfiguration().isEnabled()); } } @Test(expected = ServerConfigurationException.class) public void testInvalidBindToAddress() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.bind.to", "10.5.6:8990"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidBindToMissingColon() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.bind.to", "10.5.6.1"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidBindToPort() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.bind.to", "10.5.6.1:"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidDouble() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.text.max.required.delimiter.stddev", "abc"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidIPv4Address() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("line.udp.join", "12a.990.00"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidInt() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.connection.string.pool.capacity", "1234a"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidIntSize() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.request.header.buffer.size", "22g"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test(expected = ServerConfigurationException.class) public void testInvalidLong() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("cairo.idle.check.interval", "1234a"); new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); } @Test public void testLineUdpTimestamp() throws ServerConfigurationException, JsonException { Properties properties = new Properties(); properties.setProperty("http.enabled", "false"); properties.setProperty("line.udp.timestamp", ""); PropServerConfiguration configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoNanoTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); properties.setProperty("line.udp.timestamp", "n"); configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoNanoTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); properties.setProperty("line.udp.timestamp", "u"); configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoMicroTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); properties.setProperty("line.udp.timestamp", "ms"); configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoMilliTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); properties.setProperty("line.udp.timestamp", "s"); configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoSecondTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); properties.setProperty("line.udp.timestamp", "m"); configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoMinuteTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); properties.setProperty("line.udp.timestamp", "h"); configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertSame(LineProtoHourTimestampAdapter.INSTANCE, configuration.getLineUdpReceiverConfiguration().getTimestampAdapter()); } @Test public void testSetAllFromFile() throws IOException, ServerConfigurationException, JsonException { try (InputStream is = PropServerConfigurationTest.class.getResourceAsStream("/server.conf")) { Properties properties = new Properties(); properties.load(is); PropServerConfiguration configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertEquals(64, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getConnectionPoolInitialCapacity()); Assert.assertEquals(512, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getConnectionStringPoolCapacity()); Assert.assertEquals(256, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getMultipartHeaderBufferSize()); Assert.assertEquals(100_000, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getMultipartIdleSpinCount()); Assert.assertEquals(4096, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getRecvBufferSize()); Assert.assertEquals(2048, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getRequestHeaderBufferSize()); Assert.assertEquals(6, configuration.getHttpServerConfiguration().getWorkerCount()); Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5, 6}, configuration.getHttpServerConfiguration().getWorkerAffinity()); Assert.assertTrue(configuration.getHttpServerConfiguration().haltOnError()); Assert.assertEquals(128, configuration.getHttpServerConfiguration().getHttpContextConfiguration().getSendBufferSize()); Assert.assertEquals("index2.html", configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getIndexFileName()); Assert.assertEquals(32, configuration.getHttpServerConfiguration().getQueryCacheRows()); Assert.assertEquals(16, configuration.getHttpServerConfiguration().getQueryCacheBlocks()); Assert.assertTrue(configuration.getHttpServerConfiguration().getHttpContextConfiguration().readOnlySecurityContext()); Assert.assertEquals(50000, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getMaxQueryResponseRowLimit()); Assert.assertFalse(configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getInterruptorConfiguration().isEnabled()); Assert.assertEquals(500, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getInterruptorConfiguration().getCountOfIterationsPerCheck()); Assert.assertEquals(32, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getInterruptorConfiguration().getBufferSize()); Assert.assertEquals(new File(root, "public_ok").getAbsolutePath(), configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getPublicDirectory()); Assert.assertEquals("Keep-Alive: timeout=10, max=50000" + Misc.EOL, configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getKeepAliveHeader()); Assert.assertTrue(configuration.getHttpServerConfiguration().getHttpContextConfiguration().allowDeflateBeforeSend()); Assert.assertEquals(64, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getActiveConnectionLimit()); Assert.assertEquals(2048, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getEventCapacity()); Assert.assertEquals(64, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getIOQueueCapacity()); Assert.assertEquals(7000000, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getIdleConnectionTimeout()); Assert.assertEquals(1001, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getQueuedConnectionTimeout()); Assert.assertEquals(512, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getInterestQueueCapacity()); Assert.assertEquals(IOOperation.READ, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getInitialBias()); Assert.assertEquals(64, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getListenBacklog()); Assert.assertEquals(4194304, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getSndBufSize()); Assert.assertEquals(8388608, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getRcvBufSize()); Assert.assertEquals(32, configuration.getCairoConfiguration().getTextConfiguration().getDateAdapterPoolCapacity()); Assert.assertEquals(65536, configuration.getCairoConfiguration().getTextConfiguration().getJsonCacheLimit()); Assert.assertEquals(8388608, configuration.getCairoConfiguration().getTextConfiguration().getJsonCacheSize()); Assert.assertEquals(0.3d, configuration.getCairoConfiguration().getTextConfiguration().getMaxRequiredDelimiterStdDev(), 0.000000001); Assert.assertEquals(0.9d, configuration.getCairoConfiguration().getTextConfiguration().getMaxRequiredLineLengthStdDev(), 0.000000001); Assert.assertEquals(512, configuration.getCairoConfiguration().getTextConfiguration().getMetadataStringPoolCapacity()); Assert.assertEquals(6144, configuration.getCairoConfiguration().getTextConfiguration().getRollBufferLimit()); Assert.assertEquals(3072, configuration.getCairoConfiguration().getTextConfiguration().getRollBufferSize()); Assert.assertEquals(400, configuration.getCairoConfiguration().getTextConfiguration().getTextAnalysisMaxLines()); Assert.assertEquals(128, configuration.getCairoConfiguration().getTextConfiguration().getTextLexerStringPoolCapacity()); Assert.assertEquals(512, configuration.getCairoConfiguration().getTextConfiguration().getTimestampAdapterPoolCapacity()); Assert.assertEquals(8192, configuration.getCairoConfiguration().getTextConfiguration().getUtf8SinkSize()); Assert.assertEquals(168101918, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getBindIPv4Address()); Assert.assertEquals(9900, configuration.getHttpServerConfiguration().getDispatcherConfiguration().getBindPort()); Assert.assertEquals(2_000, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getConnectionCheckFrequency()); Assert.assertEquals(4, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getFloatScale()); Assert.assertEquals(4194304, configuration.getCairoConfiguration().getSqlCopyBufferSize()); Assert.assertEquals(64, configuration.getCairoConfiguration().getCopyPoolCapacity()); Assert.assertSame(FilesFacadeImpl.INSTANCE, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getFilesFacade()); Assert.assertEquals("Keep-Alive: timeout=10, max=50000" + Misc.EOL, configuration.getHttpServerConfiguration().getJsonQueryProcessorConfiguration().getKeepAliveHeader()); Assert.assertEquals(8, configuration.getCairoConfiguration().getDoubleToStrCastScale()); Assert.assertEquals(3, configuration.getCairoConfiguration().getFloatToStrCastScale()); Assert.assertEquals(CommitMode.ASYNC, configuration.getCairoConfiguration().getCommitMode()); Assert.assertEquals(12, configuration.getCairoConfiguration().getCreateAsSelectRetryCount()); Assert.assertEquals("compact", configuration.getCairoConfiguration().getDefaultMapType()); Assert.assertTrue(configuration.getCairoConfiguration().getDefaultSymbolCacheFlag()); Assert.assertEquals(512, configuration.getCairoConfiguration().getDefaultSymbolCapacity()); Assert.assertEquals(10, configuration.getCairoConfiguration().getFileOperationRetryCount()); Assert.assertEquals(20_000, configuration.getCairoConfiguration().getIdleCheckInterval()); Assert.assertEquals(600_000, configuration.getCairoConfiguration().getInactiveReaderTTL()); Assert.assertEquals(400_000, configuration.getCairoConfiguration().getInactiveWriterTTL()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getIndexValueBlockSize()); Assert.assertEquals(23, configuration.getCairoConfiguration().getMaxSwapFileCount()); Assert.assertEquals(509, configuration.getCairoConfiguration().getMkDirMode()); Assert.assertEquals(1000000, configuration.getCairoConfiguration().getParallelIndexThreshold()); Assert.assertEquals(10, configuration.getCairoConfiguration().getReaderPoolMaxSegments()); Assert.assertEquals(5_000_000, configuration.getCairoConfiguration().getSpinLockTimeoutUs()); Assert.assertEquals(2048, configuration.getCairoConfiguration().getSqlCharacterStoreCapacity()); Assert.assertEquals(128, configuration.getCairoConfiguration().getSqlCharacterStoreSequencePoolCapacity()); Assert.assertEquals(2048, configuration.getCairoConfiguration().getSqlColumnPoolCapacity()); Assert.assertEquals(0.8, configuration.getCairoConfiguration().getSqlCompactMapLoadFactor(), 0.000001); Assert.assertEquals(1024, configuration.getCairoConfiguration().getSqlExpressionPoolCapacity()); Assert.assertEquals(0.3, configuration.getCairoConfiguration().getSqlFastMapLoadFactor(), 0.0000001); Assert.assertEquals(32, configuration.getCairoConfiguration().getSqlJoinContextPoolCapacity()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getSqlLexerPoolCapacity()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getSqlMapKeyCapacity()); Assert.assertEquals(6 * 1024 * 1024, configuration.getCairoConfiguration().getSqlMapPageSize()); Assert.assertEquals(1026, configuration.getCairoConfiguration().getSqlMapMaxPages()); Assert.assertEquals(128, configuration.getCairoConfiguration().getSqlMapMaxResizes()); Assert.assertEquals(256, configuration.getCairoConfiguration().getSqlModelPoolCapacity()); Assert.assertEquals(10 * 1024 * 1024, configuration.getCairoConfiguration().getSqlSortKeyPageSize()); Assert.assertEquals(256, configuration.getCairoConfiguration().getSqlSortKeyMaxPages()); Assert.assertEquals(3 * 1024 * 1024, configuration.getCairoConfiguration().getSqlSortLightValuePageSize()); Assert.assertEquals(1027, configuration.getCairoConfiguration().getSqlSortLightValueMaxPages()); Assert.assertEquals(8 * 1024 * 1024, configuration.getCairoConfiguration().getSqlHashJoinValuePageSize()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getSqlHashJoinValueMaxPages()); Assert.assertEquals(10000, configuration.getCairoConfiguration().getSqlLatestByRowCount()); Assert.assertEquals(2 * 1024 * 1024, configuration.getCairoConfiguration().getSqlHashJoinLightValuePageSize()); Assert.assertEquals(1025, configuration.getCairoConfiguration().getSqlHashJoinLightValueMaxPages()); Assert.assertEquals(4 * 1024 * 1024, configuration.getCairoConfiguration().getSqlSortValuePageSize()); Assert.assertEquals(1028, configuration.getCairoConfiguration().getSqlSortValueMaxPages()); Assert.assertEquals(1000000, configuration.getCairoConfiguration().getWorkStealTimeoutNanos()); Assert.assertFalse(configuration.getCairoConfiguration().isParallelIndexingEnabled()); Assert.assertEquals(8 * 1024, configuration.getCairoConfiguration().getSqlJoinMetadataPageSize()); Assert.assertEquals(10_000, configuration.getCairoConfiguration().getSqlJoinMetadataMaxResizes()); Assert.assertEquals(16, configuration.getCairoConfiguration().getBindVariablePoolSize()); Assert.assertEquals(256, configuration.getCairoConfiguration().getAnalyticColumnPoolCapacity()); Assert.assertEquals(1024, configuration.getCairoConfiguration().getWithClauseModelPoolCapacity()); Assert.assertEquals(512, configuration.getCairoConfiguration().getRenameTableModelPoolCapacity()); Assert.assertEquals(128, configuration.getCairoConfiguration().getInsertPoolCapacity()); Assert.assertEquals(256, configuration.getCairoConfiguration().getColumnCastModelPoolCapacity()); Assert.assertEquals(64, configuration.getCairoConfiguration().getCreateTableModelPoolCapacity()); Assert.assertEquals(2001, configuration.getCairoConfiguration().getSampleByIndexSearchPageSize()); Assert.assertEquals(2_000_000, configuration.getCairoConfiguration().getCommitLag()); Assert.assertEquals(100000, configuration.getCairoConfiguration().getMaxUncommittedRows()); Assert.assertEquals(256, configuration.getCairoConfiguration().getSqlDistinctTimestampKeyCapacity()); Assert.assertEquals(0.4, configuration.getCairoConfiguration().getSqlDistinctTimestampLoadFactor(), 0.001); Assert.assertEquals(167903521, configuration.getLineUdpReceiverConfiguration().getBindIPv4Address()); Assert.assertEquals(9915, configuration.getLineUdpReceiverConfiguration().getPort()); Assert.assertEquals(-536805119, configuration.getLineUdpReceiverConfiguration().getGroupIPv4Address()); Assert.assertEquals(100_000, configuration.getLineUdpReceiverConfiguration().getCommitRate()); Assert.assertEquals(4 * 1024 * 1024, configuration.getLineUdpReceiverConfiguration().getMsgBufferSize()); Assert.assertEquals(4000, configuration.getLineUdpReceiverConfiguration().getMsgCount()); Assert.assertEquals(512, configuration.getLineUdpReceiverConfiguration().getReceiveBufferSize()); Assert.assertFalse(configuration.getLineUdpReceiverConfiguration().isEnabled()); Assert.assertEquals(2, configuration.getLineUdpReceiverConfiguration().ownThreadAffinity()); Assert.assertTrue(configuration.getLineUdpReceiverConfiguration().ownThread()); // influxdb line TCP protocol Assert.assertTrue(configuration.getLineTcpReceiverConfiguration().isEnabled()); Assert.assertEquals(11, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getActiveConnectionLimit()); Assert.assertEquals(167903521, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getBindIPv4Address()); Assert.assertEquals(9916, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getBindPort()); Assert.assertEquals(1025, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getEventCapacity()); Assert.assertEquals(1026, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getIOQueueCapacity()); Assert.assertEquals(400_000, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getIdleConnectionTimeout()); Assert.assertEquals(1_002, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getQueuedConnectionTimeout()); Assert.assertEquals(1027, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getInterestQueueCapacity()); Assert.assertEquals(55555, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getListenBacklog()); Assert.assertEquals(32768, configuration.getLineTcpReceiverConfiguration().getNetDispatcherConfiguration().getRcvBufSize()); Assert.assertEquals(32, configuration.getLineTcpReceiverConfiguration().getConnectionPoolInitialCapacity()); Assert.assertEquals(LineProtoMicroTimestampAdapter.INSTANCE, configuration.getLineTcpReceiverConfiguration().getTimestampAdapter()); Assert.assertEquals(2049, configuration.getLineTcpReceiverConfiguration().getNetMsgBufferSize()); Assert.assertEquals(128, configuration.getLineTcpReceiverConfiguration().getMaxMeasurementSize()); Assert.assertEquals(256, configuration.getLineTcpReceiverConfiguration().getWriterQueueCapacity()); Assert.assertEquals(2, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getWorkerCount()); Assert.assertArrayEquals(new int[]{1, 2}, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getWorkerAffinity()); Assert.assertEquals(20, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getYieldThreshold()); Assert.assertEquals(10_002, configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().getSleepThreshold()); Assert.assertTrue(configuration.getLineTcpReceiverConfiguration().getWriterWorkerPoolConfiguration().haltOnError()); Assert.assertEquals(3, configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().getWorkerCount()); Assert.assertArrayEquals(new int[]{3, 4, 5}, configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().getWorkerAffinity()); Assert.assertEquals(30, configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().getYieldThreshold()); Assert.assertEquals(10_003, configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().getSleepThreshold()); Assert.assertTrue(configuration.getLineTcpReceiverConfiguration().getIOWorkerPoolConfiguration().haltOnError()); Assert.assertEquals(100_000, configuration.getLineTcpReceiverConfiguration().getNUpdatesPerLoadRebalance()); Assert.assertEquals(1.5, configuration.getLineTcpReceiverConfiguration().getMaxLoadRatio(), 0.001); Assert.assertEquals(1000, configuration.getLineTcpReceiverConfiguration().getMaintenanceInterval()); Assert.assertEquals(PartitionBy.MONTH, configuration.getLineTcpReceiverConfiguration().getDefaultPartitionBy()); Assert.assertEquals(10_000, configuration.getLineTcpReceiverConfiguration().getAggressiveReadRetryCount()); Assert.assertEquals(5_000, configuration.getLineTcpReceiverConfiguration().getWriterIdleTimeout()); Assert.assertTrue(configuration.getCairoConfiguration().getTelemetryConfiguration().getEnabled()); Assert.assertEquals(512, configuration.getCairoConfiguration().getTelemetryConfiguration().getQueueCapacity()); Assert.assertFalse(configuration.getHttpServerConfiguration().getHttpContextConfiguration().getServerKeepAlive()); Assert.assertEquals("HTTP/1.0 ", configuration.getHttpServerConfiguration().getHttpContextConfiguration().getHttpVersion()); Assert.assertEquals(33554432L, configuration.getCairoConfiguration().getAppendPageSize()); Assert.assertTrue(configuration.getMetricsConfiguration().isEnabled()); } } @Test public void testSetAllInternalProperties() throws ServerConfigurationException, JsonException { final BuildInformation buildInformation = new BuildInformationHolder("5.0.6", "11.0.9.1", "0fff7d46fd13b4705770f1fb126dd9b889768643"); final PropServerConfiguration configuration = new PropServerConfiguration(root, new Properties(), null, LOG, buildInformation); Assert.assertEquals("5.0.6", configuration.getCairoConfiguration().getBuildInformation().getQuestDbVersion()); Assert.assertEquals("11.0.9.1", configuration.getCairoConfiguration().getBuildInformation().getJdkVersion()); Assert.assertEquals("0fff7d46fd13b4705770f1fb126dd9b889768643", configuration.getCairoConfiguration().getBuildInformation().getCommitHash()); } @Test public void testSetZeroKeepAlive() throws IOException, ServerConfigurationException, JsonException { try (InputStream is = PropServerConfigurationTest.class.getResourceAsStream("/server-keep-alive.conf")) { Properties properties = new Properties(); properties.load(is); PropServerConfiguration configuration = new PropServerConfiguration(root, properties, null, LOG, new BuildInformationHolder()); Assert.assertNull(configuration.getHttpServerConfiguration().getStaticContentProcessorConfiguration().getKeepAliveHeader()); } } }
package domain.player; import domain.card.Card; import domain.common.Entity; import java.util.stream.Stream; public class Player extends Entity { private final String name; private final HandCardList handCards; public Player(String name, HandCardList handCards){ super(); this.name = name; this.handCards = handCards; } public String getName() { return name; } public Stream<Card> getHandCards() { return this.handCards.getCardStream(); } public void addToHandCards(Card card){ handCards.addCard(card); } public boolean removePlayedCard(Card card) { return handCards.removeCard(card); } public boolean hasHandCard(Card card) { return this.handCards.hasCard(card); } public ImmutablePlayer toImmutable() { return new ImmutablePlayer(this); } }
package com.konex.adimo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class KonexAdimoApplicationTests { @Test void contextLoads() { } }
package org.spongepowered.asm.lib; public class Label { static final int DEBUG = 1; static final int RESOLVED = 2; static final int RESIZED = 4; static final int PUSHED = 8; static final int TARGET = 16; static final int STORE = 32; static final int REACHABLE = 64; static final int JSR = 128; static final int RET = 256; static final int SUBROUTINE = 512; static final int VISITED = 1024; static final int VISITED2 = 2048; public Object info; int status; int line; int position; private int referenceCount; private int[] srcAndRefPositions; int inputStackTop; int outputStackMax; Frame frame; Label successor; Edge successors; Label next; public int getOffset() { if ((this.status & 2) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } else { return this.position; } } void put(MethodWriter var1, ByteVector var2, int var3, boolean var4) { if ((this.status & 2) == 0) { if (var4) { this.addReference(-1 - var3, var2.length); var2.putInt(-1); } else { this.addReference(var3, var2.length); var2.putShort(-1); } } else if (var4) { var2.putInt(this.position - var3); } else { var2.putShort(this.position - var3); } } private void addReference(int var1, int var2) { if (this.srcAndRefPositions == null) { this.srcAndRefPositions = new int[6]; } if (this.referenceCount >= this.srcAndRefPositions.length) { int[] var3 = new int[this.srcAndRefPositions.length + 6]; System.arraycopy(this.srcAndRefPositions, 0, var3, 0, this.srcAndRefPositions.length); this.srcAndRefPositions = var3; } this.srcAndRefPositions[this.referenceCount++] = var1; this.srcAndRefPositions[this.referenceCount++] = var2; } boolean resolve(MethodWriter var1, int var2, byte[] var3) { boolean var4 = false; this.status |= 2; this.position = var2; int var5 = 0; while(true) { while(var5 < this.referenceCount) { int var6 = this.srcAndRefPositions[var5++]; int var7 = this.srcAndRefPositions[var5++]; int var8; if (var6 >= 0) { var8 = var2 - var6; if (var8 < -32768 || var8 > 32767) { int var9 = var3[var7 - 1] & 255; if (var9 <= 168) { var3[var7 - 1] = (byte)(var9 + 49); } else { var3[var7 - 1] = (byte)(var9 + 20); } var4 = true; } var3[var7++] = (byte)(var8 >>> 8); var3[var7] = (byte)var8; } else { var8 = var2 + var6 + 1; var3[var7++] = (byte)(var8 >>> 24); var3[var7++] = (byte)(var8 >>> 16); var3[var7++] = (byte)(var8 >>> 8); var3[var7] = (byte)var8; } } return var4; } } Label getFirst() { return this.frame == null ? this : this.frame.owner; } boolean inSubroutine(long var1) { if ((this.status & 1024) != 0) { return (this.srcAndRefPositions[(int)(var1 >>> 32)] & (int)var1) != 0; } else { return false; } } boolean inSameSubroutine(Label var1) { if ((this.status & 1024) != 0 && (var1.status & 1024) != 0) { for(int var2 = 0; var2 < this.srcAndRefPositions.length; ++var2) { if ((this.srcAndRefPositions[var2] & var1.srcAndRefPositions[var2]) != 0) { return true; } } return false; } else { return false; } } void addToSubroutine(long var1, int var3) { if ((this.status & 1024) == 0) { this.status |= 1024; this.srcAndRefPositions = new int[var3 / 32 + 1]; } int[] var10000 = this.srcAndRefPositions; var10000[(int)(var1 >>> 32)] |= (int)var1; } void visitSubroutine(Label var1, long var2, int var4) { Label var5 = this; while(true) { Label var6; Edge var7; while(true) { if (var5 == null) { return; } var6 = var5; var5 = var5.next; var6.next = null; if (var1 != null) { if ((var6.status & 2048) == 0) { var6.status |= 2048; if ((var6.status & 256) != 0 && !var6.inSameSubroutine(var1)) { var7 = new Edge(); var7.info = var6.inputStackTop; var7.successor = var1.successors.successor; var7.next = var6.successors; var6.successors = var7; } break; } } else if (!var6.inSubroutine(var2)) { var6.addToSubroutine(var2, var4); break; } } for(var7 = var6.successors; var7 != null; var7 = var7.next) { if (((var6.status & 128) == 0 || var7 != var6.successors.next) && var7.successor.next == null) { var7.successor.next = var5; var5 = var7.successor; } } } } public String toString() { return "L" + System.identityHashCode(this); } }
/* * Copyright 2016-2021 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.connect.model.transform; import java.util.Map; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.connect.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * CreateAgentStatusRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateAgentStatusRequestMarshaller { private static final MarshallingInfo<String> INSTANCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("InstanceId").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build(); private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("State").build(); private static final MarshallingInfo<Integer> DISPLAYORDER_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DisplayOrder").build(); private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Tags").build(); private static final CreateAgentStatusRequestMarshaller instance = new CreateAgentStatusRequestMarshaller(); public static CreateAgentStatusRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(CreateAgentStatusRequest createAgentStatusRequest, ProtocolMarshaller protocolMarshaller) { if (createAgentStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createAgentStatusRequest.getInstanceId(), INSTANCEID_BINDING); protocolMarshaller.marshall(createAgentStatusRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(createAgentStatusRequest.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(createAgentStatusRequest.getState(), STATE_BINDING); protocolMarshaller.marshall(createAgentStatusRequest.getDisplayOrder(), DISPLAYORDER_BINDING); protocolMarshaller.marshall(createAgentStatusRequest.getTags(), TAGS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
/* Copyright (c) 2017 - 2020 BlackBerry 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.good.automated.general.helpers; import com.good.automated.general.utils.AbstractUIAutomatorUtils; import com.good.automated.general.utils.UIAutomatorUtilsFactory; import com.good.automated.test.screens.AbstractBBDUI; import com.good.automated.test.screens.BBDForgotPasswordActivationUI; import com.good.automated.test.screens.BBDRemoteBlockUI; import com.good.automated.test.screens.BBDRemoteUnlockActivationUI; import com.good.automated.test.screens.BBDUnlockUI; public class BBDAdvancedActivationHelper extends BBDActivationHelper { private static final String TAG = BBDAdvancedActivationHelper.class.getCanonicalName(); private BBDAdvancedActivationHelper() { super(); } /** * Do activation of the app under test despite on displayed screen. * * @return true if activation was successful otherwise false */ protected boolean doEnforceForgotPasswordActivation() { AbstractBBDUI screen = new BBDUnlockUI(packageName); //Enforce Forgot Password UI if (screen.doAction()) { screen = new BBDForgotPasswordActivationUI( packageName, userName, activationPassword); if (screen.doAction()) { return doActivation(); } } printScreensQueue(); return false; } /** * Do remote Unlock and activation of the app under test despite on displayed screen. * * @return true if remote unlock and activation was successful otherwise false */ protected boolean doRemoteUnlockActivation() { AbstractBBDUI screen; //In case if app was Remote Locked while running, flow will start from Remote Block screen if (uiElementsList.indexOf(uiAutomationUtils.getUiElementShown(packageName, uiElementsList)) == 3) { screen = new BBDRemoteBlockUI(packageName); if (!screen.doAction()) { return false; } } screen = new BBDRemoteUnlockActivationUI( packageName, userName, activationPassword); if (screen.doAction()) { return doActivation(); } printScreensQueue(); return false; } /** * Login or activation application using Activation Password and Unlock password of Auth Delegate (Master) app * * @param ui object of UIAutomatorUtils * @param pName AppUnderTest package name * @param uName username * @param aPass activation password * @return EnforceNoPasswordActivationBuilder with set required parameters for simple login or activation logic */ public static EnforceNoPasswordActivationBuilder enforceNoPasswordActivationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { return new BBDAdvancedActivationHelper().new EnforceNoPasswordActivationBuilder(ui, pName, uName, aPass); } /** * Provision application * * @param ui object of UIAutomatorUtils * @param pName AppUnderTest package name * @param uName username * @param aPass activation password * @return ProvisioningProcessBuilder with set required parameters f */ public static ProvisioningProcessBuilder provisioningProcessBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { return new BBDAdvancedActivationHelper().new ProvisioningProcessBuilder(ui, pName, uName, aPass); } /** * Activates slave application via master using Auth Delegation feature. * * @param masterPackageName package name of AuthDelegate(master) application * @param isEAProducerLocked flag that defines whether EA Producer app container is locked * @return true in case of success else false */ public static boolean authDelegateApp(String masterPackageName, boolean isEAProducerLocked) { AbstractUIAutomatorUtils uiAutomationUtils = UIAutomatorUtilsFactory.getUIAutomatorUtils(); return BBDAdvancedActivationHelper.loginOrActivateEnforceAuthDelegationBuilder(uiAutomationUtils, uiAutomationUtils.getAppPackageName(), uiAutomationUtils.getAppVersionName(masterPackageName), uiAutomationUtils.getAccessKey(masterPackageName)) .setAuthDelegatorPackageName(masterPackageName) .setAuthDelegatorPassword(uiAutomationUtils.getAppProvisionPassword(masterPackageName)) .setIsEAProviderLocked(isEAProducerLocked) .doAction(); } /** * Login or activation application using Activation Password and Unlock password of Auth Delegate (Master) app * * @param ui object of UIAutomatorUtils * @param pName AppUnderTest package name * @param uName username * @param aPass activation password * @return LoginOrActivateEnforceAuthDelegationBuilder with set required parameters for simple login or activation logic */ public static LoginOrActivateEnforceAuthDelegationBuilder loginOrActivateEnforceAuthDelegationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { return new BBDAdvancedActivationHelper().new LoginOrActivateEnforceAuthDelegationBuilder(ui, pName, uName, aPass); } /** * Activates slave application via master using Easy Activation feature. * * @param pName package name of delegator(slave) application * @param masterApplicationName application name of delegate(master) application * @param masterPackageName package name of delegate(master) application * @return true in case of success else false */ public static boolean easyActivateApp(String pName, String masterApplicationName, String masterPackageName) { AbstractUIAutomatorUtils uiAutomationUtils = UIAutomatorUtilsFactory.getUIAutomatorUtils(); return BBDAdvancedActivationHelper.loginOrEasyActivateBuilder(uiAutomationUtils, pName, masterPackageName, masterApplicationName, uiAutomationUtils.getAppProvisionPassword(masterPackageName)) .setAppUnderTestPassword(uiAutomationUtils.getAppProvisionPassword(pName)) .doAction(); } /** * Activates slave application via master using Easy Activation feature. * Use this method when App for easy activation is selected automatically * * @param pName package name of delegator(slave) application * @param masterPackageName package name of delegate(master) application * @return true in case of success else false */ public static boolean easyActivateApp(String pName, String masterPackageName){ return easyActivateApp(pName, "", masterPackageName); } /** * Login or activation application using Easy Activation feature and its own Unlock password * * @param ui object of UIAutomatorUtils * @param pName AppUnderTest package name * @param eaPName Easy Activator package name * @param eaN Easy Activator app name * @param eaPass Easy Activator password * @return LoginOrEasyActivateBuilder with set required parameters for simple login or activation logic */ public static LoginOrEasyActivateBuilder loginOrEasyActivateBuilder(AbstractUIAutomatorUtils ui, String pName, String eaPName, String eaN, String eaPass) { return new BBDAdvancedActivationHelper().new LoginOrEasyActivateBuilder(ui, pName, eaPName, eaN, eaPass); } /** * Login or activate application using Easy Activation feature and Unlock password of Auth Delegate (Master) app * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param eaPName Easy Activator package name * @param eaN Easy Activator app name * @param eaPass Easy Activator password * @return LoginOrEasyActivateEnforceAuthDelegationBuilder with set required parameters for simple login or activation logic */ public static LoginOrEasyActivateEnforceAuthDelegationBuilder loginOrEasyActivateEnforceAuthDelegationBuilder(AbstractUIAutomatorUtils ui, String pName, String eaPName, String eaN, String eaPass) { return new BBDAdvancedActivationHelper().new LoginOrEasyActivateEnforceAuthDelegationBuilder(ui, pName, eaPName, eaN, eaPass); } /** * Enforce Forgot Password screen and activate application using Unlock Key and it's own Unlock password * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @return EnforceForgotPasswordActivationBuilder with set required parameters for simple login or activation logic */ public static EnforceForgotPasswordActivationBuilder enforceForgotPasswordActivationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String uKey) { return new BBDAdvancedActivationHelper().new EnforceForgotPasswordActivationBuilder(ui, pName, uName, uKey); } /** * Enforce Remote Unlock screen and activate application using Unlock Key and it's own Unlock password * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @return EnforceRemoteUnlockActivationBuilder with set required parameters for simple login or activation logic */ public static EnforceRemoteUnlockActivationBuilder enforceRemoteUnlockActivationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String uKey) { return new BBDAdvancedActivationHelper().new EnforceRemoteUnlockActivationBuilder(ui, pName, uName, uKey); } public abstract class AbstractEasyActivateBuilder extends AbstractBaseBuilder { /** * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param eaPName Easy Activator package name * @param eaN Easy Activator app name * @param eaPass Easy Activator password */ public AbstractEasyActivateBuilder(AbstractUIAutomatorUtils ui, String pName, String eaPName, String eaN, String eaPass) { super(ui, pName); BBDAdvancedActivationHelper.this.eaPackageName = eaPName; BBDAdvancedActivationHelper.this.eaName = eaN; BBDAdvancedActivationHelper.this.eaPassword = eaPass; } } public abstract class AbstractAuthDelegateBuilder extends AbstractAccessKeyBuilder { /** * Login or activate app under test using Activation Password & AuthDelegation * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param uName user name for activation * @param aPass activation password */ public AbstractAuthDelegateBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { super(ui, pName, uName, aPass); BBDAdvancedActivationHelper.this.userName = uName; BBDAdvancedActivationHelper.this.activationPassword = aPass; } } public class EnforceNoPasswordActivationBuilder extends AbstractAccessKeyBuilder { /** * Login or activate app under test using Activation Password * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param uName user name for activation * @param aPass activation password */ public EnforceNoPasswordActivationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { super(ui, pName, uName, aPass); } @Override public boolean doAction() { BBDActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.userName = BBDAdvancedActivationHelper.this.userName; bb.activationPassword = BBDAdvancedActivationHelper.this.activationPassword; return bb.doActivation(); } } public class ProvisioningProcessBuilder extends AbstractAccessKeyBuilder { /** * Provision app under test using Activation Password * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param uName user name for activation * @param aPass activation password */ public ProvisioningProcessBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { super(ui, pName, uName, aPass); } @Override public boolean doAction() { BBDActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.userName = BBDAdvancedActivationHelper.this.userName; bb.activationPassword = BBDAdvancedActivationHelper.this.activationPassword; return bb.doProvisioning(); } } /** * Login or activate AppUnderTest using Activation Password, unlock AppUnderTest using Auth Delegator app */ public class LoginOrActivateEnforceAuthDelegationBuilder extends AbstractAuthDelegateBuilder { private boolean isEAProviderLocked = true; /** * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param uName user name for activation * @param aPass activation password */ private LoginOrActivateEnforceAuthDelegationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String aPass) { super(ui, pName, uName, aPass); } /** * @param pName AuthDelegatorApp package name * @return LoginOrActivateEnforceAuthDelegatorBuilder object with set AuthDelegatorApp package name */ public LoginOrActivateEnforceAuthDelegationBuilder setAuthDelegatorPackageName(String pName) { BBDAdvancedActivationHelper.this.authDelPackageName = pName; return this; } /** * @param aPass AuthDelegatorApp password * @return LoginOrActivateEnforceAuthDelegatorBuilder object with set AuthDelegatorApp password */ public LoginOrActivateEnforceAuthDelegationBuilder setAuthDelegatorPassword(String aPass) { BBDAdvancedActivationHelper.this.authDelPassword = aPass; return this; } /** * @param isEAProviderLocked flag that defines whether EA Producer app container is locked * @return LoginOrActivateEnforceAuthDelegatorBuilder object with set isEAProviderLocked flag */ public LoginOrActivateEnforceAuthDelegationBuilder setIsEAProviderLocked(boolean isEAProviderLocked) { LoginOrActivateEnforceAuthDelegationBuilder.this.isEAProviderLocked = isEAProviderLocked; return this; } /** * @return true if all actions performed successfully otherwise false */ @Override public boolean doAction() { BBDAdvancedActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.userName = BBDAdvancedActivationHelper.this.userName; bb.activationPassword = BBDAdvancedActivationHelper.this.activationPassword; bb.authDelPackageName = BBDAdvancedActivationHelper.this.authDelPackageName; bb.authDelPassword = isEAProviderLocked ? BBDAdvancedActivationHelper.this.authDelPassword : null; bb.eaPackageName = authDelPackageName; return bb.doActivationWithAuthDelegation(); } } /** * Login or activate AppUnderTest using Easy Activator app, unlock AppUnderTest using its own password */ public class LoginOrEasyActivateBuilder extends AbstractEasyActivateBuilder { /** * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param eaPName Easy Activator package name * @param eaN Easy Activator app name * @param eaPass Easy Activator password */ public LoginOrEasyActivateBuilder(AbstractUIAutomatorUtils ui, String pName, String eaPName, String eaN, String eaPass) { super(ui, pName, eaPName, eaN, eaPass); } /** * @param pass password of AppUnderTest * @return LoginOrEasyActivateBuilder object with set AppUnderTest password */ public LoginOrEasyActivateBuilder setAppUnderTestPassword(String pass) { BBDAdvancedActivationHelper.this.appPassword = pass; return this; } /** * @return true if all actions performed successfully otherwise false */ @Override public boolean doAction() { BBDAdvancedActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.appPassword = BBDAdvancedActivationHelper.this.appPassword; bb.eaName = BBDAdvancedActivationHelper.this.eaName; bb.eaPackageName = BBDAdvancedActivationHelper.this.eaPackageName; bb.eaPassword = BBDAdvancedActivationHelper.this.eaPassword; return bb.doActivation(); } } /** * Login or activate AppUnderTest using Easy Activator app, unlock AppUnderTest using Auth Delegator app */ public class LoginOrEasyActivateEnforceAuthDelegationBuilder extends AbstractEasyActivateBuilder { /** * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param eaPName Easy Activator package name * @param eaN Easy Activator app name * @param eaPass Easy Activator password */ public LoginOrEasyActivateEnforceAuthDelegationBuilder(AbstractUIAutomatorUtils ui, String pName, String eaPName, String eaN, String eaPass) { super(ui, pName, eaPName, eaN, eaPass); } /** * @param pName AuthDelegatorApp package name * @return LoginOrEasyActivateEnforceAuthDelegatorBuilder object with set AuthDelegatorApp package name */ public LoginOrEasyActivateEnforceAuthDelegationBuilder setAuthDelegatorPackageName(String pName) { BBDAdvancedActivationHelper.this.authDelPackageName = pName; return this; } /** * @param aPass AuthDelegatorApp password * @return LoginOrEasyActivateEnforceAuthDelegatorBuilder object with set AuthDelegatorApp password */ public LoginOrEasyActivateEnforceAuthDelegationBuilder setAuthDelegatorPassword(String aPass) { BBDAdvancedActivationHelper.this.authDelPassword = aPass; return this; } /** * @return true if all actions performed successfully otherwise false */ @Override public boolean doAction() { BBDAdvancedActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.eaName = BBDAdvancedActivationHelper.this.eaName; bb.eaPackageName = BBDAdvancedActivationHelper.this.eaPackageName; bb.eaPassword = BBDAdvancedActivationHelper.this.eaPassword; bb.authDelPackageName = BBDAdvancedActivationHelper.this.authDelPackageName; bb.authDelPassword = BBDAdvancedActivationHelper.this.authDelPassword; return bb.doActivationWithAuthDelegation(); } } /** * Enforce Forgot Password screen and activate AppUnderTest using Unlock Key, unlock AppUnderTest using its own password * This logic start working from Unlock password screen by tapping on Forgot Password label. */ public class EnforceForgotPasswordActivationBuilder extends LoginOrActivateBuilder { /** * Activate AppUnderTest using Unlock Key * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param uName user name for activation * @param uKey unlock key (15 characters) */ public EnforceForgotPasswordActivationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String uKey) { super(ui, pName, uName, uKey); } /** * @return true if all actions performed successfully otherwise false */ @Override public boolean doAction() { BBDAdvancedActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.appPassword = BBDAdvancedActivationHelper.this.appPassword; bb.userName = BBDAdvancedActivationHelper.this.userName; bb.activationPassword = BBDAdvancedActivationHelper.this.activationPassword; return bb.doEnforceForgotPasswordActivation(); } } /** * Enforce Remote Unlock screen and activate AppUnderTest using Unlock Key, unlock AppUnderTest using its own password. * If app was running in foreground we will start Unlocking it from RemoteBlock screen * If app was force re-started, then we will start activation process from Unlock Key screen. */ public class EnforceRemoteUnlockActivationBuilder extends LoginOrActivateBuilder { /** * Activate AppUnderTest using Unlock Key * * @param ui object of uiAutomatorUtils * @param pName AppUnderTest package name * @param uName user name for activation * @param uKey unlock key (15 characters) */ public EnforceRemoteUnlockActivationBuilder(AbstractUIAutomatorUtils ui, String pName, String uName, String uKey) { super(ui, pName, uName, uKey); } /** * @return true if all actions performed successfully otherwise false */ @Override public boolean doAction() { BBDAdvancedActivationHelper bb = new BBDAdvancedActivationHelper(); bb.uiAutomationUtils = BBDAdvancedActivationHelper.this.uiAutomationUtils; bb.packageName = BBDAdvancedActivationHelper.this.packageName; bb.appPassword = BBDAdvancedActivationHelper.this.appPassword; bb.userName = BBDAdvancedActivationHelper.this.userName; bb.activationPassword = BBDAdvancedActivationHelper.this.activationPassword; return bb.doRemoteUnlockActivation(); } } }
/* * Copyright 2018 original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.gcp.data.spanner.core; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.google.cloud.Timestamp; import com.google.cloud.spanner.Options.ReadOption; import org.springframework.util.Assert; /** * Encapsulates Cloud Spanner read options. * * @author Chengyuan Zhao * * @since 1.1 */ public class SpannerReadOptions { private List<ReadOption> readOptions = new ArrayList<>(); private Optional<Timestamp> timestamp = Optional.empty(); private Optional<String> index = Optional.empty(); /** * Constructor to create an instance. Use the extension-style add/set functions to add * options and settings. */ public SpannerReadOptions() { } public SpannerReadOptions addReadOption(ReadOption readOption) { Assert.notNull(readOption, "Valid read option is required!"); this.readOptions.add(readOption); return this; } public SpannerReadOptions unsetTimestamp() { this.timestamp = Optional.empty(); return this; } public boolean hasTimestamp() { return this.timestamp.isPresent(); } public Timestamp getTimestamp() { if (!hasTimestamp()) { throw new UnsupportedOperationException( "Cannot get timestamp because it hasn't been set."); } return this.timestamp.get(); } public SpannerReadOptions setTimestamp(Timestamp timestamp) { Assert.notNull(timestamp, "A valid timestamp is required!"); this.timestamp = Optional.of(timestamp); return this; } public SpannerReadOptions unsetIndex() { this.index = Optional.empty(); return this; } public boolean hasIndex() { return this.index.isPresent(); } public String getIndex() { if (!hasIndex()) { throw new UnsupportedOperationException( "Cannot get index because it hasn't been set."); } return this.index.get(); } public SpannerReadOptions setIndex(String index) { Assert.notNull(index, "A valid index is required!"); this.index = Optional.of(index); return this; } public ReadOption[] getReadOptions() { return this.readOptions.toArray(new ReadOption[this.readOptions.size()]); } }
package com.prestoncinema.mqtt; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.prestoncinema.app.R; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.android.service.MqttTraceHandler; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import java.util.UUID; public class MqttManager implements IMqttActionListener, MqttCallback, MqttTraceHandler { // Log private final static String TAG = MqttManager.class.getSimpleName(); // Singleton private static MqttManager mInstance = null; // Types public enum MqqtConnectionStatus { CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED, ERROR, NONE } public static int MqqtQos_AtMostOnce = 0; public static int MqqtQos_AtLeastOnce = 1; public static int MqqtQos_ExactlyOnce = 2; // Data private MqttAndroidClient mMqttClient; private MqttManagerListener mListener; private MqqtConnectionStatus mMqqtClientStatus = MqqtConnectionStatus.NONE; private Context mContext; public static MqttManager getInstance(Context context) { if (mInstance == null) { mInstance = new MqttManager(context); } return mInstance; } public MqttManager(Context context) { mContext = context.getApplicationContext(); } @Override public void finalize() throws Throwable { try { if (mMqttClient != null) { mMqttClient.unregisterResources(); } } finally { super.finalize(); } } public MqqtConnectionStatus getClientStatus() { return mMqqtClientStatus; } public void setListener(MqttManagerListener listener) { mListener = listener; } // region MQTT public void subscribe(String topic, int qos) { if (mMqttClient != null && mMqqtClientStatus == MqqtConnectionStatus.CONNECTED && topic != null) { try { Log.d(TAG, "Mqtt: subscribe to " + topic + " qos:" + qos); mMqttClient.subscribe(topic, qos); } catch (MqttException e) { Log.e(TAG, "Mqtt:x subscribe error: ", e); } } } public void unsubscribe(String topic) { if (mMqttClient != null && mMqqtClientStatus == MqqtConnectionStatus.CONNECTED && topic != null) { try { Log.d(TAG, "Mqtt: unsubscribe from " + topic); mMqttClient.unsubscribe(topic); } catch (MqttException e) { Log.e(TAG, "Mqtt:x unsubscribe error: ", e); } } } public void publish(String topic, String payload, int qos) { if (mMqttClient != null && mMqqtClientStatus == MqqtConnectionStatus.CONNECTED && topic != null) { boolean retained = false; try { Log.d(TAG, "Mqtt: publish " + payload + " for topic " + topic + " qos:" + qos); mMqttClient.publish(topic, payload.getBytes(), qos, retained, null, null); } catch (MqttException e) { Log.e(TAG, "Mqtt:x publish error: ", e); } } } public void disconnect() { if (mMqttClient != null && mMqqtClientStatus == MqqtConnectionStatus.CONNECTED) { try { Log.d(TAG, "Mqtt: disconnect"); // mMqqtClientStatus = MqqtConnectionStatus.DISCONNECTING; mMqqtClientStatus = MqqtConnectionStatus.DISCONNECTED; // Note: it seems that the disconnected callback is never invoked. So we fake here that the final state is disconnected mMqttClient.disconnect(null, this); mMqttClient.unregisterResources(); mMqttClient = null; } catch (MqttException e) { Log.e(TAG, "Mqtt:x disconnection error: ", e); } } } public void connectFromSavedSettings(Context context) { MqttSettings settings = MqttSettings.getInstance(context); String host = settings.getServerAddress(); int port = settings.getServerPort(); String username = settings.getUsername(); String password = settings.getPassword(); boolean cleanSession = settings.isCleanSession(); boolean sslConnection = settings.isSslConnection(); connect(context, host, port, username, password, cleanSession, sslConnection); } public void connect(Context context, String host, int port, String username, String password, boolean cleanSession, boolean sslConnection) { String clientId = "Bluefruit_"+ UUID.randomUUID().toString(); final int timeout = MqttConnectOptions.CONNECTION_TIMEOUT_DEFAULT; final int keepalive = MqttConnectOptions.KEEP_ALIVE_INTERVAL_DEFAULT; String message = null; String topic = null; int qos = 0; boolean retained = false; String uri; if (sslConnection) { uri = "ssl://" + host + ":" + port; } else { uri = "tcp://" + host + ":" + port; } Log.d(TAG, "Mqtt: Create client: "+clientId); mMqttClient = new MqttAndroidClient(context, uri, clientId); mMqttClient.registerResources(mContext); MqttConnectOptions conOpt = new MqttConnectOptions(); Log.d(TAG, "Mqtt: clean session:" +(cleanSession?"yes":"no")); conOpt.setCleanSession(cleanSession); conOpt.setConnectionTimeout(timeout); conOpt.setKeepAliveInterval(keepalive); if (username != null && username.length() > 0) { Log.d(TAG, "Mqtt: username: " + username); conOpt.setUserName(username); } if (password != null && password.length() > 0) { Log.d(TAG, "Mqtt: password: " + password); conOpt.setPassword(password.toCharArray()); } boolean doConnect = true; if ((message != null && message.length() > 0) || (topic != null && topic.length() > 0)) { // need to make a message since last will is set Log.d(TAG, "Mqtt: setwill"); try { conOpt.setWill(topic, message.getBytes(), qos, retained); } catch (Exception e) { Log.e(TAG, "Mqtt: Can't set will", e); doConnect = false; //callback.onFailure(null, e); } } mMqttClient.setCallback(this); mMqttClient.setTraceCallback(this); if (doConnect) { MqttSettings.getInstance(mContext).setConnectedEnabled(true); try { Log.d(TAG, "Mqtt: connect to " + uri); mMqqtClientStatus = MqqtConnectionStatus.CONNECTING; mMqttClient.connect(conOpt, null, this); } catch (MqttException e) { Log.e(TAG, "Mqtt: connection error: ", e); } } } // endregion // region IMqttActionListener @Override public void onSuccess(IMqttToken iMqttToken) { if (mMqqtClientStatus == MqqtConnectionStatus.CONNECTING) { Log.d(TAG, "Mqtt connect onSuccess"); mMqqtClientStatus = MqqtConnectionStatus.CONNECTED; if (mListener != null) mListener.onMqttConnected(); MqttSettings settings = MqttSettings.getInstance(mContext); String topic = settings.getSubscribeTopic(); int topicQos = settings.getSubscribeQos(); if (settings.isSubscribeEnabled() && topic != null) { subscribe(topic, topicQos); } } else if (mMqqtClientStatus == MqqtConnectionStatus.DISCONNECTING) { Log.d(TAG, "Mqtt disconnect onSuccess"); mMqqtClientStatus = MqqtConnectionStatus.DISCONNECTED; if (mListener != null) mListener.onMqttDisconnected(); } else { Log.d(TAG, "Mqtt unknown onSuccess"); } } @Override public void onFailure(IMqttToken iMqttToken, Throwable throwable) { Log.d(TAG, "Mqtt onFailure. " + throwable); // Remove the auto-connect till the failure is solved if (mMqqtClientStatus == MqqtConnectionStatus.CONNECTING) { MqttSettings.getInstance(mContext).setConnectedEnabled(false); } // Set as an error mMqqtClientStatus = MqqtConnectionStatus.ERROR; String errorText = mContext.getString(R.string.mqtt_connection_failed)+". "+throwable.getLocalizedMessage(); Toast.makeText(mContext, errorText, Toast.LENGTH_LONG).show(); // Call listener if (mListener != null) mListener.onMqttDisconnected(); } // endregion // region MqttCallback @Override public void connectionLost(Throwable throwable) { Log.d(TAG, "Mqtt connectionLost. " + throwable); if (throwable != null) { // if disconnected because a reason show toast. Standard disconnect will have a null throwable Toast.makeText(mContext, R.string.mqtt_connection_lost, Toast.LENGTH_LONG).show(); } mMqqtClientStatus = MqqtConnectionStatus.DISCONNECTED; if (mListener != null) { mListener.onMqttDisconnected(); } } @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { String message = new String(mqttMessage.getPayload()); if (message.length() > 0) { // filter cleared messages (to avoid duplicates) Log.d(TAG, "Mqtt messageArrived from topic: " + topic + " message: " + message + " isDuplicate: " + (mqttMessage.isDuplicate() ? "yes" : "no")); if (mListener != null) { mListener.onMqttMessageArrived(topic, mqttMessage); } // Fix duplicated messages clearing the received payload and processing only non null messages mqttMessage.clearPayload(); } } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { Log.d(TAG, "Mqtt deliveryComplete"); } // endregion // region MqttTraceHandler @Override public void traceDebug(String source, String message) { Log.d(TAG, "Mqtt traceDebug"); } @Override public void traceError(String source, String message) { Log.d(TAG, "Mqtt traceError"); } @Override public void traceException(String source, String message, Exception e) { Log.d(TAG, "Mqtt traceException"); } // endregion public interface MqttManagerListener { void onMqttConnected(); void onMqttDisconnected(); void onMqttMessageArrived(String topic, MqttMessage mqttMessage); } }
package org.mockserver.junit.jupiter.integration; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.Test; import org.mockserver.configuration.ConfigurationProperties; import org.mockserver.file.FileReader; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.serialization.ExpectationSerializer; import org.mockserver.serialization.ObjectMapperFactory; import org.mockserver.testing.integration.callback.PrecannedTestExpectationForwardCallbackRequest; import org.mockserver.testing.integration.callback.PrecannedTestExpectationForwardCallbackRequestAndResponse; import org.mockserver.testing.integration.callback.PrecannedTestExpectationResponseCallback; import org.mockserver.uuid.UUIDService; import org.mockserver.verify.VerificationTimes; import org.slf4j.event.Level; import java.util.Arrays; import static io.netty.handler.codec.http.HttpHeaderNames.HOST; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static junit.framework.TestCase.fail; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.mock.Expectation.when; import static org.mockserver.mock.OpenAPIExpectation.openAPIExpectation; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpClassCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpOverrideForwardedRequest.forwardOverriddenRequest; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.*; import static org.mockserver.model.HttpTemplate.template; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.OpenAPIDefinition.openAPI; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.validator.jsonschema.JsonSchemaValidator.OPEN_API_SPECIFICATION_URL; /** * @author jamesdbloom */ public abstract class AbstractBasicMockingIntegrationTest extends AbstractMockingIntegrationTestBase { @Test public void shouldReturnResponseWithOnlyBody() { // when Expectation[] upsertedExpectations = mockServerClient.when(request()).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is(new Expectation(request()).thenRespond(response().withBody("some_body")))); } @Test public void shouldReturnResponseInHttpAndHttps() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingStringBody() { // when mockServerClient .when( request() .withBody(exact("some_random_body")) ) .respond( response() .withBody("some_string_body_response") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotBody() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")) .withBody(Not.not(regex(".+"))) ) .respond( response() .withBody("some_response_body") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")), headersToIgnore) ); assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseFromVelocityTemplate() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")) ) .respond( template( HttpTemplate.TemplateType.VELOCITY, "{" + NEW_LINE + " \"statusCode\": 200," + NEW_LINE + " \"headers\": [ { \"name\": \"name\", \"values\": [ \"$!request.headers['name'][0]\" ] } ]," + NEW_LINE + " \"body\": \"$!request.body\"" + NEW_LINE + "}" + NEW_LINE ) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader("name", "value") .withBody("some_request_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withHeader("name", "value") .withBody("some_request_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(SECONDS, 2)) ); // then long timeBeforeRequest = System.currentTimeMillis(); HttpResponse httpResponse = makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore ); long timeAfterRequest = System.currentTimeMillis(); // and assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), httpResponse ); assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(MILLISECONDS.toMillis(1900))); assertThat(timeAfterRequest - timeBeforeRequest, lessThanOrEqualTo(SECONDS.toMillis(4))); } @Test public void shouldReturnResponseForCallbackClassWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .respond( callback() .withCallbackClass(PrecannedTestExpectationResponseCallback.class) .withDelay(new Delay(SECONDS, 2)) ); // then long timeBeforeRequest = System.currentTimeMillis(); HttpResponse httpResponse = makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ); long timeAfterRequest = System.currentTimeMillis(); // and assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), httpResponse ); assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(MILLISECONDS.toMillis(1900))); assertThat(timeAfterRequest - timeBeforeRequest, lessThanOrEqualTo(SECONDS.toMillis(4))); } @Test public void shouldReturnResponseForCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .respond( callback() .withCallbackClass(PrecannedTestExpectationResponseCallback.class) ); // then assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); } @Test public void shouldReturnResponseByMatchingOpenAPIUrlWithOperationId() { // when Expectation[] upsertedExpectations = mockServerClient .when(openAPI( "org/mockserver/mock/openapi_petstore_example.json", "listPets" )) .respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"), headersToIgnore) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is(new Expectation(openAPI( "org/mockserver/mock/openapi_petstore_example.json", "listPets" )).thenRespond(response().withBody("some_body")))); } @Test public void shouldReturnResponseByMatchingOpenAPISpecWithOperationId() throws JsonProcessingException { // when Expectation[] upsertedExpectations = mockServerClient .when(openAPI( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"), "listPets" )) .respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"), headersToIgnore) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is(new Expectation(openAPI( ObjectMapperFactory.createObjectMapper().readTree(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")).toPrettyString(), "listPets" )).thenRespond(response().withBody("some_body")))); } @Test public void shouldReturnResponseByMatchingOpenAPIUrlWithoutOperationId() { // when Expectation[] upsertedExpectations = mockServerClient .when(openAPI().withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json")) .respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"), headersToIgnore) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is(new Expectation( openAPI() .withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json") ).thenRespond(response().withBody("some_body")))); } @Test public void shouldReturnResponseByMatchingOpenAPIExpectationWithUrl() { // when Expectation[] upsertedExpectations = mockServerClient .upsert(openAPIExpectation( "org/mockserver/mock/openapi_petstore_example.json" )); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader("x-next", "some_string_value") .withHeader("content-type", "application/json") .withBody(json("[ {" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "} ]", MediaType.APPLICATION_JSON)), makeRequest( request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"), headersToIgnore) ); assertEquals( response() .withStatusCode(CREATED_201.code()) .withReasonPhrase(CREATED_201.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath("/pets") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}", MediaType.APPLICATION_JSON)), makeRequest( request() .withMethod("GET") .withPath("/pets/12345") .withHeader("x-request-id", UUIDService.getUUID()), headersToIgnore) ); // and assertThat(upsertedExpectations.length, is(4)); assertThat(upsertedExpectations[0], is( when("org/mockserver/mock/openapi_petstore_example.json", "listPets") .thenRespond( response() .withStatusCode(200) .withHeader("x-next", "some_string_value") .withHeader("content-type", "application/json") .withBody(json("[ {" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "} ]")) ) )); assertThat(upsertedExpectations[1], is( when("org/mockserver/mock/openapi_petstore_example.json", "createPets") .thenRespond( response() .withStatusCode(201) ) )); assertThat(upsertedExpectations[2], is( when("org/mockserver/mock/openapi_petstore_example.json", "showPetById") .thenRespond( response() .withStatusCode(200) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}")) ) )); assertThat(upsertedExpectations[3], is( when("org/mockserver/mock/openapi_petstore_example.json", "somePath") .thenRespond( response() .withStatusCode(200) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}")) ) )); } @Test public void shouldReturnResponseByMatchingOpenAPIExpectationWithSpecAndResponse() throws JsonProcessingException { // when Expectation[] upsertedExpectations = mockServerClient .upsert(openAPIExpectation( FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json"), ImmutableMap.of( "listPets", "500", "createPets", "default", "showPetById", "200" ) )); // then assertEquals( response() .withStatusCode(INTERNAL_SERVER_ERROR_500.code()) .withReasonPhrase(INTERNAL_SERVER_ERROR_500.reasonPhrase()) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"code\" : 0," + NEW_LINE + " \"message\" : \"some_string_value\"" + NEW_LINE + "}", MediaType.APPLICATION_JSON)), makeRequest( request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"code\" : 0," + NEW_LINE + " \"message\" : \"some_string_value\"" + NEW_LINE + "}", MediaType.APPLICATION_JSON)), makeRequest( request() .withMethod("POST") .withPath("/pets") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}", MediaType.APPLICATION_JSON)), makeRequest( request() .withMethod("GET") .withPath("/pets/12345") .withHeader("x-request-id", UUIDService.getUUID()), headersToIgnore) ); // and assertThat(upsertedExpectations.length, is(3)); assertThat(upsertedExpectations[0], is( when(ObjectMapperFactory.createObjectMapper().readTree(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")).toPrettyString(), "listPets") .thenRespond( response() .withStatusCode(500) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"code\" : 0," + NEW_LINE + " \"message\" : \"some_string_value\"" + NEW_LINE + "}")) ) )); assertThat(upsertedExpectations[1], is( when(ObjectMapperFactory.createObjectMapper().readTree(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")).toPrettyString(), "createPets") .thenRespond( response() .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"code\" : 0," + NEW_LINE + " \"message\" : \"some_string_value\"" + NEW_LINE + "}")) ) )); assertThat(upsertedExpectations[2], is( when(ObjectMapperFactory.createObjectMapper().readTree(FileReader.readFileFromClassPathOrPath("org/mockserver/mock/openapi_petstore_example.json")).toPrettyString(), "showPetById") .thenRespond( response() .withStatusCode(200) .withHeader("content-type", "application/json") .withBody(json("{" + NEW_LINE + " \"id\" : 0," + NEW_LINE + " \"name\" : \"some_string_value\"," + NEW_LINE + " \"tag\" : \"some_string_value\"" + NEW_LINE + "}")) ) )); } @Test public void shouldSupportBatchedExpectations() throws Exception { // when HttpResponse httpResponse = httpClient.sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + this.getServerPort()) .withPath(addContextToPath("mockserver/expectation")) .withBody("" + "[" + new ExpectationSerializer(new MockServerLogger()) .serialize( new Expectation(request("/path_one"), once(), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body_one")) ) + "," + new ExpectationSerializer(new MockServerLogger()) .serialize( new Expectation(request("/path_two"), once(), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body_two")) ) + "," + new ExpectationSerializer(new MockServerLogger()) .serialize( new Expectation(request("/path_three"), once(), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body_three")) ) + "]" ) ).get(10, SECONDS); // then Expectation[] upsertedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray(httpResponse.getBodyAsString(), true); assertThat(upsertedExpectations.length, is(3)); assertThat(upsertedExpectations[0], is( new Expectation(request("/path_one"), once(), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body_one")) )); assertThat(upsertedExpectations[1], is( new Expectation(request("/path_two"), once(), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body_two")) )); assertThat(upsertedExpectations[2], is( new Expectation(request("/path_three"), once(), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body_three")) )); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body_one"), makeRequest( request() .withPath(calculatePath("/path_one")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body_two"), makeRequest( request() .withPath(calculatePath("/path_two")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body_three"), makeRequest( request() .withPath(calculatePath("/path_three")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders( header("headerName", "headerValue"), header("set-cookie", "cookieName=cookieValue") ) .withCookies(cookie("cookieName", "cookieValue")), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingOpenAPI() { // when Expectation[] upsertedExpectations = mockServerClient .when(openAPI( "org/mockserver/mock/openapi_petstore_example.json", "listPets" )) .respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("PUT") .withPath("/pets") .withQueryStringParameter("limit", "10"), headersToIgnore) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is(new Expectation(openAPI( "org/mockserver/mock/openapi_petstore_example.json", "listPets" )).thenRespond(response().withBody("some_body")))); } @Test public void shouldVerifyReceivedRequestsSpecificTimesInHttpAndHttps() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // and assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // then mockServerClient.verify(request().withPath(calculatePath("some_path"))); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // when assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // then mockServerClient.verify(request().withPath(calculatePath("some_path"))); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); mockServerClient.verify(request().withPath(calculatePath("some_path")).withSecure(true), VerificationTimes.exactly(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")).withSecure(false), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotReceivedRequestWithEmptyBody() { // when mockServerClient .when( request() .withPath(calculatePath("some_path_no_body")) .withBody(Not.not(regex(".+"))) ) .respond(response()); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path_no_body")), headersToIgnore) ); // and mockServerClient .when( request() .withPath(calculatePath("some_path_with_body")) .withBody("some_request_body") ) .respond( response() .withBody("some_response_body") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response_body"), makeRequest( request() .withPath(calculatePath("some_path_with_body")) .withBody("some_request_body"), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path_no_body"))); mockServerClient.verify(request().withPath(calculatePath("some_path_no_body")).withBody(regex(".+")), VerificationTimes.atMost(0)); mockServerClient.verify(request().withPath(calculatePath("some_path_no_body")).withBody(exact("some_random_body")), VerificationTimes.atMost(0)); mockServerClient.verify(request().withPath(calculatePath("some_path_with_body"))); mockServerClient.verify(request().withPath(calculatePath("some_path_with_body")).withBody("some_request_body")); mockServerClient.verify(request().withPath(calculatePath("some_path_with_body")).withBody(regex(".+"))); mockServerClient.verify(request().withPath(calculatePath("some_path_with_body")).withBody(exact("some_other_body")), VerificationTimes.atMost(0)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient .verify( request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2) ); fail("expected exception to be thrown"); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{")); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveRecordedRequests() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore ) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore ) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore ) ); // then verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveRecordedRequestsByOpenAPI() { // when mockServerClient .when(openAPI().withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json"), exactly(4)) .respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("/pets")) .withQueryStringParameter("limit", "10"), headersToIgnore ) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore ) ); assertEquals( response("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("/pets")) .withHeader("content-type", "application/json") .withBody(json("" + "{" + NEW_LINE + " \"id\": 50, " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + "}" )), headersToIgnore ) ); // then // TODO(jamesdbloom) why is this path not prefixed with context route? verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(openAPI().withSpecUrlOrPayload("org/mockserver/mock/openapi_petstore_example.json")), request() .withMethod("GET") .withPath("/pets") .withQueryStringParameter("limit", "10"), request() .withMethod("POST") .withPath("/pets") .withHeader("content-type", "application/json") .withBody(json("" + "{" + NEW_LINE + " \"id\": 50, " + NEW_LINE + " \"name\": \"scruffles\", " + NEW_LINE + " \"tag\": \"dog\"" + NEW_LINE + "}" )) ); } @Test public void shouldRetrieveActiveExpectations() { // when HttpRequest complexRequest = request() .withPath(calculatePath("some_path.*")) .withHeader("some", "header") .withQueryStringParameter("some", "parameter") .withCookie("some", "parameter") .withBody("some_body"); mockServerClient.when(complexRequest, exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(complexRequest, exactly(4), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(complexRequest, exactly(4), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveActiveExpectations(request()), arrayContaining( new Expectation(complexRequest, exactly(4), TimeToLive.unlimited(), 0) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldRetrieveRecordedExpectations() throws InterruptedException { mockServerClient .when( request() .withPath(calculatePath("some_path.*")), exactly(4) ) .forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); assertEquals( response("some_body_one") .withHeader("some", "header") .withHeader("cookie", "some=parameter") .withHeader("set-cookie", "some=parameter") .withCookie("some", "parameter"), makeRequest( request() .withPath(calculatePath("some_path_one")) .withHeader("some", "header") .withQueryStringParameter("some", "parameter") .withCookie("some", "parameter") .withBody("some_body_one"), headersToIgnore ) ); MILLISECONDS.sleep(500); assertEquals( response("some_body_three"), makeRequest( request() .withPath(calculatePath("some_path_three")) .withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one"))); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new RequestDefinition[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = mockServerClient.retrieveRecordedExpectations(request()); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new RequestDefinition[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = mockServerClient.retrieveRecordedExpectations(null); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new RequestDefinition[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } @Test public void shouldRetrieveRecordedLogMessages() { Level originalLevel = ConfigurationProperties.logLevel(); try { // given ConfigurationProperties.logLevel("INFO"); // when UUIDService.fixedUUID = true; mockServerClient.reset(); mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then String[] actualLogMessages = mockServerClient.retrieveLogMessagesArray(request().withPath(calculatePath(".*"))); Object[] expectedLogMessages = new Object[]{ "resetting all expectations and request logs", "creating expectation:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/some_path.*\"" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }," + NEW_LINE + " \"id\" : \"" + UUIDService.getUUID() + "\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 4" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " with id:" + NEW_LINE + NEW_LINE + " " + UUIDService.getUUID() + NEW_LINE, new String[]{ "received request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/some_path_one\"," + NEW_LINE + " \"headers\" : {" }, new String[]{ "request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/some_path_one\",", " matched expectation:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/some_path.*\"" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }," + NEW_LINE + " \"id\" : \"" + UUIDService.getUUID() + "\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 4" + NEW_LINE + " }" + NEW_LINE + " }" }, new String[]{ "returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/some_path_one\",", " for action:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }" + NEW_LINE }, new String[]{ "received request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/not_found\"," + NEW_LINE + " \"headers\" : {" }, new String[]{ "request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/not_found\",", " didn't match expectation:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/some_path.*\"" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }," + NEW_LINE + " \"id\" : \"" + UUIDService.getUUID() + "\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 3" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " because:" + NEW_LINE + NEW_LINE + " method matched" + NEW_LINE + " path didn't match" + NEW_LINE }, new String[]{ "no expectation for:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/not_found\"," + NEW_LINE, " returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"statusCode\" : 404," + NEW_LINE + " \"reasonPhrase\" : \"Not Found\"" + NEW_LINE + " }" + NEW_LINE }, new String[]{ "received request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/some_path_three\"," + NEW_LINE + " \"headers\" : {" }, new String[]{ "request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/some_path_three\",", " matched expectation:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/some_path.*\"" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }," + NEW_LINE + " \"id\" : \"" + UUIDService.getUUID() + "\"," + NEW_LINE + " \"priority\" : 0," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 3" + NEW_LINE + " }" + NEW_LINE + " }" }, new String[]{ "returning response:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }" + NEW_LINE + NEW_LINE + " for request:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"/some_path_three\",", " for action:" + NEW_LINE + NEW_LINE + " {" + NEW_LINE + " \"body\" : \"some_body\"" + NEW_LINE + " }" + NEW_LINE } }; for (int i = 0; i < expectedLogMessages.length; i++) { if (expectedLogMessages[i] instanceof String) { assertThat("matching log message " + i + "\nActual:" + NEW_LINE + Arrays.toString(actualLogMessages), actualLogMessages[i], endsWith((String) expectedLogMessages[i])); } else if (expectedLogMessages[i] instanceof String[]) { String[] expectedLogMessage = (String[]) expectedLogMessages[i]; for (int j = 0; j < expectedLogMessage.length; j++) { assertThat("matching log message " + i + "-" + j + "\nActual:" + NEW_LINE + Arrays.toString(actualLogMessages), actualLogMessages[i], containsString(expectedLogMessage[j])); } } } } finally { UUIDService.fixedUUID = false; ConfigurationProperties.logLevel(originalLevel.name()); } } @Test public void shouldClearExpectationsAndLogs() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldErrorForInvalidExpectation() throws Exception { // when HttpResponse httpResponse = httpClient.sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + this.getServerPort()) .withPath(addContextToPath("mockserver/expectation")) .withBody("{" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/path_one\"" + NEW_LINE + " }," + NEW_LINE + " \"incorrectField\" : {" + NEW_LINE + " \"body\" : \"some_body_one\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 1" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }" + NEW_LINE + "}") ).get(10, SECONDS); // then assertThat(httpResponse.getStatusCode(), is(400)); assertThat(httpResponse.getBodyAsString(), is("incorrect expectation json format for:" + NEW_LINE + "" + NEW_LINE + " {" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/path_one\"" + NEW_LINE + " }," + NEW_LINE + " \"incorrectField\" : {" + NEW_LINE + " \"body\" : \"some_body_one\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 1" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "" + NEW_LINE + " schema validation errors:" + NEW_LINE + "" + NEW_LINE + " 12 errors:\n" + " - $.httpError: is missing, but is required, if specifying action of type Error\n" + " - $.httpForward: is missing, but is required, if specifying action of type Forward\n" + " - $.httpForwardClassCallback: is missing, but is required, if specifying action of type ForwardClassCallback\n" + " - $.httpForwardObjectCallback: is missing, but is required, if specifying action of type ForwardObjectCallback\n" + " - $.httpForwardTemplate: is missing, but is required, if specifying action of type ForwardTemplate\n" + " - $.httpOverrideForwardedRequest: is missing, but is required, if specifying action of type OverrideForwardedRequest\n" + " - $.httpResponse: is missing, but is required, if specifying action of type Response\n" + " - $.httpResponseClassCallback: is missing, but is required, if specifying action of type ResponseClassCallback\n" + " - $.httpResponseObjectCallback: is missing, but is required, if specifying action of type ResponseObjectCallback\n" + " - $.httpResponseTemplate: is missing, but is required, if specifying action of type ResponseTemplate\n" + " - $.incorrectField: is not defined in the schema and the schema does not allow additional properties\n" + " - oneOf of the following must be specified [httpError, httpForward, httpForwardClassCallback, httpForwardObjectCallback, httpForwardTemplate, httpOverrideForwardedRequest, httpResponse, httpResponseClassCallback, httpResponseObjectCallback, httpResponseTemplate]" + NEW_LINE + " " + NEW_LINE + " " + OPEN_API_SPECIFICATION_URL.replaceAll(NEW_LINE, NEW_LINE + " "))); } @Test public void shouldErrorForInvalidRequest() throws Exception { // when HttpResponse httpResponse = httpClient.sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + this.getServerPort()) .withPath(addContextToPath("mockserver/clear")) .withBody("{" + NEW_LINE + " \"path\" : 500," + NEW_LINE + " \"method\" : true," + NEW_LINE + " \"keepAlive\" : \"false\"" + NEW_LINE + " }") ).get(10, SECONDS); // then assertThat(httpResponse.getStatusCode(), is(400)); assertThat(httpResponse.getBodyAsString(), is("incorrect request matcher json format for:" + NEW_LINE + "" + NEW_LINE + " {" + NEW_LINE + " \"path\" : 500," + NEW_LINE + " \"method\" : true," + NEW_LINE + " \"keepAlive\" : \"false\"" + NEW_LINE + " }" + NEW_LINE + "" + NEW_LINE + " schema validation errors:" + NEW_LINE + "" + NEW_LINE + " 4 errors:\n" + " - $.keepAlive: string found, boolean expected\n" + " - $.method: boolean found, string expected\n" + " - $.path: integer found, string expected\n" + " - $.specUrlOrPayload: is missing but it is required" + NEW_LINE + " " + NEW_LINE + " " + OPEN_API_SPECIFICATION_URL.replaceAll(NEW_LINE, NEW_LINE + " "))); } @Test public void shouldForwardRequestInHTTPWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) .withDelay(new Delay(SECONDS, 2)) ); // then long timeBeforeRequest = System.currentTimeMillis(); HttpResponse httpResponse = makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore); long timeAfterRequest = System.currentTimeMillis(); // and assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), httpResponse ); assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(MILLISECONDS.toMillis(1900))); assertThat(timeAfterRequest - timeBeforeRequest, lessThanOrEqualTo(SECONDS.toMillis(4))); } @Test public void shouldForwardOverriddenRequestWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(false) ) .forward( forwardOverriddenRequest() .withRequestOverride( request() .withHeader("Host", "localhost:" + insecureEchoServer.getPort()) .withBody("some_overridden_body") ) .withDelay(SECONDS, 2) ); // then long timeBeforeRequest = System.currentTimeMillis(); HttpResponse httpResponse = makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ); long timeAfterRequest = System.currentTimeMillis(); // and assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("some_overridden_body"), httpResponse ); assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(MILLISECONDS.toMillis(1900))); assertThat(timeAfterRequest - timeBeforeRequest, lessThanOrEqualTo(SECONDS.toMillis(4))); } @Test public void shouldForwardRequestInHTTP() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); // then assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) ) .thenForward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ) )); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(secureEchoServer.getPort()) .withScheme(HttpForward.Scheme.HTTPS) ); // then assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) ) .thenForward( forward() .withHost("127.0.0.1") .withPort(secureEchoServer.getPort()) .withScheme(HttpForward.Scheme.HTTPS) ) )); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardOverriddenRequest() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(false) ) .forward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + insecureEchoServer.getPort()) .withBody("some_overridden_body") ).withDelay(MILLISECONDS, 10) ); Expectation[] upsertedSecureExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(true) ) .forward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + secureEchoServer.getPort()) .withBody("some_overridden_body") ).withDelay(MILLISECONDS, 10) ); // then // - in http assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) .withSecure(false) ) .thenForward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + insecureEchoServer.getPort()) .withBody("some_overridden_body") ).withDelay(MILLISECONDS, 10) ) )); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("some_overridden_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertThat(upsertedSecureExpectations.length, is(1)); assertThat(upsertedSecureExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) .withSecure(true) ) .thenForward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + secureEchoServer.getPort()) .withBody("some_overridden_body") ).withDelay(MILLISECONDS, 10) ) )); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body_https") ) .withBody("some_overridden_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body_https") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardOverriddenRequestWithOverriddenResponse() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(false) ) .forward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + insecureEchoServer.getPort()) .withBody("some_overridden_body"), response() .withHeader("extra_header", "some_value") .withHeader("content-length", "29") .withBody("some_overridden_response_body") ).withDelay(MILLISECONDS, 10) ); Expectation[] upsertedSecureExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(true) ) .forward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + secureEchoServer.getPort()) .withBody("some_overridden_body"), response() .withHeader("extra_header", "some_value") .withHeader("content-length", "29") .withBody("some_overridden_response_body") ).withDelay(MILLISECONDS, 10) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body"), header("extra_header", "some_value") ) .withBody("some_overridden_response_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) .withSecure(false) ) .thenForward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + insecureEchoServer.getPort()) .withBody("some_overridden_body"), response() .withHeader("extra_header", "some_value") .withHeader("content-length", "29") .withBody("some_overridden_response_body") ).withDelay(MILLISECONDS, 10) ) )); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body_https"), header("extra_header", "some_value") ) .withBody("some_overridden_response_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body_https") ) .withBody("an_example_body_https"), headersToIgnore) ); assertThat(upsertedSecureExpectations.length, is(1)); assertThat(upsertedSecureExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) .withSecure(true) ) .thenForward( forwardOverriddenRequest( request() .withHeader("Host", "localhost:" + secureEchoServer.getPort()) .withBody("some_overridden_body"), response() .withHeader("extra_header", "some_value") .withHeader("content-length", "29") .withBody("some_overridden_response_body") ).withDelay(MILLISECONDS, 10) ) )); } @Test public void shouldForwardOverriddenRequestWithSocketAddress() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(false) ) .forward( forwardOverriddenRequest( request() .withHeader("Host", "incorrect_host:1234") .withBody("some_overridden_body") .withSocketAddress( "localhost", insecureEchoServer.getPort(), SocketAddress.Scheme.HTTP ) ).withDelay(MILLISECONDS, 10) ); Expectation[] upsertedSecureExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) .withSecure(true) ) .forward( forwardOverriddenRequest( request() .withHeader("Host", "incorrect_host:1234") .withBody("some_overridden_body") .withSocketAddress( "localhost", secureEchoServer.getPort(), SocketAddress.Scheme.HTTPS ) ).withDelay(MILLISECONDS, 10) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("some_overridden_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) .withSecure(false) ) .thenForward( forwardOverriddenRequest( request() .withHeader("Host", "incorrect_host:1234") .withBody("some_overridden_body") .withSocketAddress( "localhost", insecureEchoServer.getPort(), SocketAddress.Scheme.HTTP ) ).withDelay(MILLISECONDS, 10) ) )); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body_https") ) .withBody("some_overridden_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body_https") ) .withBody("an_example_body_https"), headersToIgnore) ); assertThat(upsertedSecureExpectations.length, is(1)); assertThat(upsertedSecureExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) .withSecure(true) ) .thenForward( forwardOverriddenRequest( request() .withHeader("Host", "incorrect_host:1234") .withBody("some_overridden_body") .withSocketAddress( "localhost", secureEchoServer.getPort(), SocketAddress.Scheme.HTTPS ) ).withDelay(MILLISECONDS, 10) ) )); } @Test public void shouldForwardTemplateInVelocity() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( template(HttpTemplate.TemplateType.VELOCITY, "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"127.0.0.1:" + insecureEchoServer.getPort() + "\" ]" + NEW_LINE + " }, {" + NEW_LINE + " 'name' : \"x-test\"," + NEW_LINE + " 'values' : [ \"$!request.headers['x-test'][0]\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "}") .withDelay(MILLISECONDS, 10) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("{'name': 'value'}"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) ) .thenForward( template(HttpTemplate.TemplateType.VELOCITY, "{" + NEW_LINE + " 'path' : \"/somePath\"," + NEW_LINE + " 'headers' : [ {" + NEW_LINE + " 'name' : \"Host\"," + NEW_LINE + " 'values' : [ \"127.0.0.1:" + insecureEchoServer.getPort() + "\" ]" + NEW_LINE + " }, {" + NEW_LINE + " 'name' : \"x-test\"," + NEW_LINE + " 'values' : [ \"$!request.headers['x-test'][0]\" ]" + NEW_LINE + " } ]," + NEW_LINE + " 'body': \"{'name': 'value'}\"" + NEW_LINE + "}") .withDelay(MILLISECONDS, 10) ) )); } @Test public void shouldForwardCallbackClassWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( callback() .withCallbackClass(PrecannedTestExpectationForwardCallbackRequest.class) .withDelay(new Delay(SECONDS, 2)) ); // then long timeBeforeRequest = System.currentTimeMillis(); HttpResponse httpResponse = makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body"), header("x-echo-server-port", insecureEchoServer.getPort()) ) .withBody("an_example_body_http"), headersToIgnore ); long timeAfterRequest = System.currentTimeMillis(); // and assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("some_overridden_body"), httpResponse ); assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(MILLISECONDS.toMillis(1900))); assertThat(timeAfterRequest - timeBeforeRequest, lessThanOrEqualTo(SECONDS.toMillis(4))); } @Test public void shouldForwardCallbackClassToOverrideRequestInTestClasspath() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( callback() .withCallbackClass(PrecannedTestExpectationForwardCallbackRequest.class) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("some_overridden_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body"), header("x-echo-server-port", insecureEchoServer.getPort()) ) .withBody("an_example_body_http"), headersToIgnore ) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) ) .thenForward( callback() .withCallbackClass(PrecannedTestExpectationForwardCallbackRequest.class) ) )); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("some_overridden_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body"), header("x-echo-server-port", secureEchoServer.getPort()) ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldForwardCallbackClassToOverrideRequestAndResponseInTestClasspath() { // when Expectation[] upsertedExpectations = mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( callback() .withCallbackClass(PrecannedTestExpectationForwardCallbackRequestAndResponse.class) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-response-test", "x-response-test"), header("x-test", "test_headers_and_body") ) .withBody("some_overidden_response_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body"), header("x-echo-server-port", insecureEchoServer.getPort()) ) .withBody("an_example_body_http"), headersToIgnore ) ); assertThat(upsertedExpectations.length, is(1)); assertThat(upsertedExpectations[0], is( new Expectation( request() .withPath(calculatePath("echo")) ) .thenForward( callback() .withCallbackClass(PrecannedTestExpectationForwardCallbackRequestAndResponse.class) ) )); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-response-test", "x-response-test"), header("x-test", "test_headers_and_body") ) .withBody("some_overidden_response_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body"), header("x-echo-server-port", secureEchoServer.getPort()) ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } }
/* * Copyright 2018 JBoss by Red Hat. * * 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.kie.cloud.integrationtests.persistence; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.guvnor.rest.client.ProjectResponse; import org.guvnor.rest.client.Space; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.kie.cloud.api.DeploymentScenarioBuilderFactory; import org.kie.cloud.api.DeploymentScenarioBuilderFactoryLoader; import org.kie.cloud.api.deployment.Deployment; import org.kie.cloud.api.deployment.Instance; import org.kie.cloud.api.deployment.WorkbenchDeployment; import org.kie.cloud.api.scenario.ClusteredWorkbenchKieServerDatabasePersistentScenario; import org.kie.cloud.api.scenario.KieDeploymentScenario; import org.kie.cloud.api.scenario.WorkbenchKieServerPersistentScenario; import org.kie.cloud.common.provider.WorkbenchClientProvider; import org.kie.cloud.tests.common.AbstractMethodIsolatedCloudIntegrationTest; import org.kie.wb.test.rest.client.WorkbenchClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.xtf.openshift.OpenShiftBinaryClient; @RunWith(Parameterized.class) public class WorkbenchGitHooksPersistenceIntegrationTest extends AbstractMethodIsolatedCloudIntegrationTest<KieDeploymentScenario> { private static final Logger logger = LoggerFactory.getLogger(WorkbenchGitHooksPersistenceIntegrationTest.class); @Parameterized.Parameter(value = 0) public String testScenarioName; @Parameterized.Parameter(value = 1) public KieDeploymentScenario workbenchKieServerScenario; private WorkbenchClient workbenchClient; private WorkbenchDeployment workbenchDeployment; private static final String GIT_HOOKS_REMOTE_DIR = "/opt/eap/standalone/data/kie/git/hooks"; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { List<Object[]> scenarios = new ArrayList<>(); DeploymentScenarioBuilderFactory deploymentScenarioFactory = DeploymentScenarioBuilderFactoryLoader.getInstance(); try { WorkbenchKieServerPersistentScenario workbenchKieServerPersistentScenario = deploymentScenarioFactory.getWorkbenchKieServerPersistentScenarioBuilder() .withGitHooksDir(GIT_HOOKS_REMOTE_DIR) .build(); scenarios.add(new Object[] { "Workbench + KIE Server - Persistent", workbenchKieServerPersistentScenario }); } catch (UnsupportedOperationException ex) { logger.info("Workbench + KIE Server - Persistent is skipped.", ex); } try { ClusteredWorkbenchKieServerDatabasePersistentScenario clusteredWorkbenchKieServerDatabasePersistentScenario = deploymentScenarioFactory.getClusteredWorkbenchKieServerDatabasePersistentScenarioBuilder() .withGitHooksDir(GIT_HOOKS_REMOTE_DIR) .build(); scenarios.add(new Object[]{"Clustered Workbench + KIE Server + Database - Persistent", clusteredWorkbenchKieServerDatabasePersistentScenario}); } catch (UnsupportedOperationException ex) { logger.info("Clustered Workbench + KIE Server + Database - Persistent scenario is skipped.", ex); } return scenarios; } @Override protected KieDeploymentScenario createDeploymentScenario(DeploymentScenarioBuilderFactory deploymentScenarioFactory) { return workbenchKieServerScenario; } @Before public void setUp() { workbenchDeployment = deploymentScenario.getWorkbenchDeployments().get(0); workbenchClient = WorkbenchClientProvider.getWorkbenchClient(workbenchDeployment); } @Test public void testGitHooksPersistence() { List<String> workbenchInstanceNames = workbenchDeployment.getInstances().stream().map(Instance::getName).collect(Collectors.toList()); logger.info("Copy git hooks to the pod"); Path localResourcesDir = Paths.get(ClassLoader.class.getResource("/git-hooks").getPath()); rsync(workbenchInstanceNames.get(0), localResourcesDir, GIT_HOOKS_REMOTE_DIR, true); String projectName = "testGitHooksPersistenceProject"; workbenchClient.createSpace(SPACE_NAME, workbenchDeployment.getUsername()); workbenchClient.createProject(SPACE_NAME, projectName, PROJECT_GROUP_ID, "1.0"); assertSpaceAndProjectExists(SPACE_NAME, projectName); logger.debug("Copy output from git hook back to locat test resources dir"); rsync(workbenchInstanceNames.get(0), localResourcesDir, GIT_HOOKS_REMOTE_DIR, false); long linesOfOutput = checkOutputFile(0); scaleToZeroAndToOne(workbenchDeployment); workbenchInstanceNames = workbenchDeployment.getInstances().stream().map(Instance::getName).collect(Collectors.toList()); assertSpaceAndProjectExists(SPACE_NAME, projectName); String newProjectName = "newTestGitHooksPersistenceProject"; workbenchClient.createProject(SPACE_NAME, newProjectName, PROJECT_GROUP_ID, "1.0"); assertSpaceAndProjectExists(SPACE_NAME, newProjectName); logger.debug("Copy output from git hook back to locat test resources dir"); rsync(workbenchInstanceNames.get(0), localResourcesDir, GIT_HOOKS_REMOTE_DIR, false); checkOutputFile(linesOfOutput); } private void assertSpaceAndProjectExists(String spaceName, String projectName) { Collection<Space> spaces = workbenchClient.getSpaces(); assertThat(spaces.stream().anyMatch(n -> n.getName().equals(spaceName))).as("Space " + spaceName + " not found.").isTrue(); Collection<ProjectResponse> projects = workbenchClient.getProjects(spaceName); assertThat(projects.stream().anyMatch(n -> n.getName().equals(projectName))).as("Project " + projectName + " not found.").isTrue(); } private void scaleToZeroAndToOne(Deployment deployment) { deployment.scale(0); deployment.waitForScale(); deployment.scale(1); deployment.waitForScale(); } private long checkOutputFile(long previousLineCount) { long newLineCount = 0; try { logger.debug("Print out post-commit output file"); Files.lines(Paths.get(ClassLoader.class.getResource("/git-hooks/out.txt").getPath())).forEach((line) -> { logger.debug(line); }); newLineCount = Files.lines(Paths.get(ClassLoader.class.getResource("/git-hooks/out.txt").getPath())).count(); Files.delete(Paths.get(ClassLoader.class.getResource("/git-hooks/out.txt").getPath())); } catch (IOException ex) { throw new RuntimeException("IOException wile reading output file.", ex); } assertThat(newLineCount).isGreaterThan(previousLineCount); return newLineCount; } private void rsync(final String podName, final Path localDir, final String remoteDir, boolean toPod) { OpenShiftBinaryClient oc = OpenShiftBinaryClient.getInstance(); oc.project(deploymentScenario.getNamespace()); List<String> args = new ArrayList<>(); args.add("rsync"); args.add(!toPod ? (podName + ":" + remoteDir + "/") : localDir.toFile() .getAbsoluteFile().getPath() + "/"); args.add(toPod ? (podName + ":" + remoteDir + "/") : localDir.toFile() .getAbsoluteFile().getPath() + "/"); oc.executeCommand("rsync has failed", args.toArray(new String[args.size()])); } }
package com.zzw.github.graphql.crawler.template; import static com.zzw.github.graphql.crawler.template.MetaTemplate.NODE_ID; /** * Created by zzw on 2018/8/31. */ public class PullRequestReviewCommentTemplate { public static final String PULL_REQUEST_REVIEW_COMMENT_INFO = "{\"query\":\"query{\\n" + " node(id:\\\"" + NODE_ID + "\\\"){\\n" + " __typename\\n" + " ... on PullRequestReviewComment{\\n" + " author{\\n" + " __typename\\n" + " ... on Bot{\\n" + " id\\n" + " }\\n" + " ... on Organization{\\n" + " id\\n" + " }\\n" + " ... on User{\\n" + " id\\n" + " }\\n" + " }\\n" + " authorAssociation\\n" + " body\\n" + " bodyHTML\\n" + " bodyText\\n" + " commit{\\n" + " id\\n" + " }\\n" + " createdAt\\n" + " createdViaEmail\\n" + " databaseId\\n" + " diffHunk\\n" + " draftedAt\\n" + " editor{\\n" + " __typename\\n" + " ... on Bot{\\n" + " id\\n" + " }\\n" + " ... on Organization{\\n" + " id\\n" + " }\\n" + " ... on User{\\n" + " id\\n" + " }\\n" + " }\\n" + " id\\n" + " includesCreatedEdit\\n" + " lastEditedAt\\n" + " originalCommit{\\n" + " id\\n" + " }\\n" + " originalPosition\\n" + " path\\n" + " position\\n" + " publishedAt\\n" + " pullRequest{\\n" + " id\\n" + " }\\n" + " pullRequestReview{\\n" + " id\\n" + " }\\n" + " reactionGroups{\\n" + " content\\n" + " createdAt\\n" + " viewerHasReacted\\n" + " }\\n" + " replyTo{\\n" + " id\\n" + " }\\n" + " repository{\\n" + " id\\n" + " }\\n" + " resourcePath\\n" + " updatedAt\\n" + " url\\n" + " }\\n" + " }\\n" + "}\",\"variables\":\"{}\"}"; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package emr.jvm.memory; import emr.jvm.JVMRuntime; import emr.jvm.visualization.MemoryVisualizer; /** * * @author Evan Ross */ public class RAMMemoryModule extends MemoryModule { /** * The following constants are used by the memory allocation processes. * These offsets are negative because the free list pointer points to * the start of the available memory region! */ public static final int BLOCK_HEADER_SIZE_OFFSET = -8; // two words back public static final int BLOCK_HEADER_NEXT_OFFSET = -4; // one word back public static final int BLOCK_REMAINDER_MINIMUM_SIZE = 20; // 5 words public static final int BLOCK_HEADER_SIZE = 8; // 2 words /** * These constants specify the interrupt vector table location */ private static final int INT_VECTOR_TABLE_SIZE = 32; // 8 words RAMMemoryModule(String name, int size, int baseAddress) { super(name, size, baseAddress); // Now setup the initial state of the memory management system // freehead points to single region // | | | | // | size = empty + header | next = itself (2) | ........ empty ............ | // | word 0 | word 1 |^ | // | // freehead ----------------------------------------| // | <- start of RAM address ----> increasing RAM address ----> // Note: memory is allocated at the END of the block, so the first chunk is allocated // at the highest RAM addresses. // The interrupt vector table exists in the first few words (single) of RAM. Initialize it for( int i = baseAddress; i < INT_VECTOR_TABLE_SIZE; i +=4 ) writeWord(i, JVMRuntime.nullregister, MemoryVisualizer.INTERRUPT_VECTOR); ////////////////////////////////////////////////////////////////////////////////////////////// // Setup the initial memory block. The value in this register determines where in memory // objects in RAM are actually stored, i.e. the base offset in RAM. // Offset everthing by the RAM's base address plus size of the interrupt vector table. ////////////////////////////////////////////////////////////////////////////////////////////// JVMRuntime.freehead = baseAddress + INT_VECTOR_TABLE_SIZE + BLOCK_HEADER_SIZE; // start of first word (32-bit) of empty memory. ////////////////////////////////////////////////////////////////////////////////////////////// writeWord(baseAddress + 0 + INT_VECTOR_TABLE_SIZE, size - INT_VECTOR_TABLE_SIZE, MemoryVisualizer.MM); // setup 'size' (word 0) of the block (one block for the whole memory region) writeWord(baseAddress + 4 + INT_VECTOR_TABLE_SIZE, JVMRuntime.freehead, MemoryVisualizer.MM); // 'next' (word 1) points to itself which is the start of the free space (at word 2) } }
package io.swagger.client.api; import io.swagger.client.ApiInvoker; import io.swagger.client.ApiException; import io.swagger.client.Pair; import io.swagger.client.model.*; import java.util.*; import com.android.volley.Response; import com.android.volley.VolleyError; import io.swagger.client.model.Author; import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public class WemediaAuthorApi { String basePath = "http://api.c-f.com:8000/football"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { getInvoker().addDefaultHeader(key, value); } public ApiInvoker getInvoker() { return apiInvoker; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getBasePath() { return basePath; } /** * 创建一个Author * 创建一个Author,其中name必填 * @param key key * @param author 作者 * @return Author */ public Author addAuthor (String key, Author author) throws TimeoutException, ExecutionException, InterruptedException, ApiException { Object postBody = author; // verify the required parameter 'key' is set if (key == null) { VolleyError error = new VolleyError("Missing the required parameter 'key' when calling addAuthor", new ApiException(400, "Missing the required parameter 'key' when calling addAuthor")); } // verify the required parameter 'author' is set if (author == null) { VolleyError error = new VolleyError("Missing the required parameter 'author' when calling addAuthor", new ApiException(400, "Missing the required parameter 'author' when calling addAuthor")); } // create path and map variables String path = "/wemedia/authors".replaceAll("\\{format\\}","json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); headerParams.put("key", ApiInvoker.parameterToString(key)); String[] contentTypes = { "application/json" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] { }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(localVarResponse != null){ return (Author) ApiInvoker.deserialize(localVarResponse, "", Author.class); } else { return null; } } catch (ApiException ex) { throw ex; } catch (InterruptedException ex) { throw ex; } catch (ExecutionException ex) { if(ex.getCause() instanceof VolleyError) { VolleyError volleyError = (VolleyError)ex.getCause(); if (volleyError.networkResponse != null) { throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } } throw ex; } catch (TimeoutException ex) { throw ex; } } /** * 创建一个Author * 创建一个Author,其中name必填 * @param key key * @param author 作者 */ public void addAuthor (String key, Author author, final Response.Listener<Author> responseListener, final Response.ErrorListener errorListener) { Object postBody = author; // verify the required parameter 'key' is set if (key == null) { VolleyError error = new VolleyError("Missing the required parameter 'key' when calling addAuthor", new ApiException(400, "Missing the required parameter 'key' when calling addAuthor")); } // verify the required parameter 'author' is set if (author == null) { VolleyError error = new VolleyError("Missing the required parameter 'author' when calling addAuthor", new ApiException(400, "Missing the required parameter 'author' when calling addAuthor")); } // create path and map variables String path = "/wemedia/authors".replaceAll("\\{format\\}","json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); headerParams.put("key", ApiInvoker.parameterToString(key)); String[] contentTypes = { "application/json" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] { }; try { apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { try { responseListener.onResponse((Author) ApiInvoker.deserialize(localVarResponse, "", Author.class)); } catch (ApiException exception) { errorListener.onErrorResponse(new VolleyError(exception)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } } /** * 获得单个作者 * 查看单个作者的信息 * @param key key * @param authorId 作者的Id * @return Author */ public Author getAuthor (String key, String authorId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { Object postBody = null; // verify the required parameter 'key' is set if (key == null) { VolleyError error = new VolleyError("Missing the required parameter 'key' when calling getAuthor", new ApiException(400, "Missing the required parameter 'key' when calling getAuthor")); } // verify the required parameter 'authorId' is set if (authorId == null) { VolleyError error = new VolleyError("Missing the required parameter 'authorId' when calling getAuthor", new ApiException(400, "Missing the required parameter 'authorId' when calling getAuthor")); } // create path and map variables String path = "/wemedia/authors/{authorId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "authorId" + "\\}", apiInvoker.escapeString(authorId.toString())); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); headerParams.put("key", ApiInvoker.parameterToString(key)); String[] contentTypes = { "application/json" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] { }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(localVarResponse != null){ return (Author) ApiInvoker.deserialize(localVarResponse, "", Author.class); } else { return null; } } catch (ApiException ex) { throw ex; } catch (InterruptedException ex) { throw ex; } catch (ExecutionException ex) { if(ex.getCause() instanceof VolleyError) { VolleyError volleyError = (VolleyError)ex.getCause(); if (volleyError.networkResponse != null) { throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } } throw ex; } catch (TimeoutException ex) { throw ex; } } /** * 获得单个作者 * 查看单个作者的信息 * @param key key * @param authorId 作者的Id */ public void getAuthor (String key, String authorId, final Response.Listener<Author> responseListener, final Response.ErrorListener errorListener) { Object postBody = null; // verify the required parameter 'key' is set if (key == null) { VolleyError error = new VolleyError("Missing the required parameter 'key' when calling getAuthor", new ApiException(400, "Missing the required parameter 'key' when calling getAuthor")); } // verify the required parameter 'authorId' is set if (authorId == null) { VolleyError error = new VolleyError("Missing the required parameter 'authorId' when calling getAuthor", new ApiException(400, "Missing the required parameter 'authorId' when calling getAuthor")); } // create path and map variables String path = "/wemedia/authors/{authorId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "authorId" + "\\}", apiInvoker.escapeString(authorId.toString())); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); headerParams.put("key", ApiInvoker.parameterToString(key)); String[] contentTypes = { "application/json" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] { }; try { apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { try { responseListener.onResponse((Author) ApiInvoker.deserialize(localVarResponse, "", Author.class)); } catch (ApiException exception) { errorListener.onErrorResponse(new VolleyError(exception)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } } /** * 获得Authors列表 * 获得Authors列表 * @param key key * @return List<Author> */ public List<Author> getAuthors (String key) throws TimeoutException, ExecutionException, InterruptedException, ApiException { Object postBody = null; // verify the required parameter 'key' is set if (key == null) { VolleyError error = new VolleyError("Missing the required parameter 'key' when calling getAuthors", new ApiException(400, "Missing the required parameter 'key' when calling getAuthors")); } // create path and map variables String path = "/wemedia/authors".replaceAll("\\{format\\}","json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); headerParams.put("key", ApiInvoker.parameterToString(key)); String[] contentTypes = { "application/json" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] { }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(localVarResponse != null){ return (List<Author>) ApiInvoker.deserialize(localVarResponse, "array", Author.class); } else { return null; } } catch (ApiException ex) { throw ex; } catch (InterruptedException ex) { throw ex; } catch (ExecutionException ex) { if(ex.getCause() instanceof VolleyError) { VolleyError volleyError = (VolleyError)ex.getCause(); if (volleyError.networkResponse != null) { throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } } throw ex; } catch (TimeoutException ex) { throw ex; } } /** * 获得Authors列表 * 获得Authors列表 * @param key key */ public void getAuthors (String key, final Response.Listener<List<Author>> responseListener, final Response.ErrorListener errorListener) { Object postBody = null; // verify the required parameter 'key' is set if (key == null) { VolleyError error = new VolleyError("Missing the required parameter 'key' when calling getAuthors", new ApiException(400, "Missing the required parameter 'key' when calling getAuthors")); } // create path and map variables String path = "/wemedia/authors".replaceAll("\\{format\\}","json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); headerParams.put("key", ApiInvoker.parameterToString(key)); String[] contentTypes = { "application/json" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] { }; try { apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { try { responseListener.onResponse((List<Author>) ApiInvoker.deserialize(localVarResponse, "array", Author.class)); } catch (ApiException exception) { errorListener.onErrorResponse(new VolleyError(exception)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } } }
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class ConfigurationFetcher extends Fetcher<Configuration> { private String uiVersion; /** * Pinned UI version. * * @param uiVersion Pinned UI version * @return this */ public ConfigurationFetcher setUiVersion(final String uiVersion) { this.uiVersion = uiVersion; return this; } /** * Make the request to the Twilio API to perform the fetch. * * @param client TwilioRestClient with which to make the request * @return Fetched Configuration */ @Override @SuppressWarnings("checkstyle:linelength") public Configuration fetch(final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, Domains.FLEXAPI.toString(), "/v1/Configuration", client.getRegion() ); addQueryParams(request); Response response = client.request(request); if (response == null) { throw new ApiConnectionException("Configuration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException( restException.getMessage(), restException.getCode(), restException.getMoreInfo(), restException.getStatus(), null ); } return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } /** * Add the requested query string arguments to the Request. * * @param request Request to add query string arguments to */ private void addQueryParams(final Request request) { if (uiVersion != null) { request.addQueryParam("UiVersion", uiVersion); } } }
/******************************************************************************* * Copyright 2010 Simon Mieth * * 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.kabeja.acis; import java.io.InputStream; import java.util.Map; import org.kabeja.DraftDocument; import org.kabeja.parser.ParseException; import org.kabeja.parser.Parser; public class SATParser implements Parser{ protected DraftDocument doc; public String getName() { // TODO Auto-generated method stub return null; } public DraftDocument parse(InputStream in, Map properties) throws ParseException { // TODO Auto-generated method stub return null; } public void parse(InputStream input, DraftDocument doc, Map properties) throws ParseException { // TODO Auto-generated method stub } public boolean supportedExtension(String extension) { // TODO Auto-generated method stub return false; } }
package com.xavier.nginxlog; import com.xavier.commom.Constant; import com.xavier.commom.NginxLogVariable; import com.xavier.commom.Utils; import com.xavier.nginxlog.structs.EndNode; import com.xavier.nginxlog.structs.FormatNode; import com.xavier.nginxlog.structs.Node; import com.xavier.nginxlog.structs.SeparatorNode; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <strong>This class was used to split every text row of log file.</strong> * <p> * It contains a 'format' linked list that struts is like: <br/> * FormatVarNode -> SplitVarNode -> FormatVarNode -> SplitVarNode ... -> * EndSplitVarNode * </p> * <p> * This linked list represent a single text row of log file. * As we all know, the nginx 'access log file' is formatted by the nginx * config file's 'log_format' directive. At the nginx 'log_format' * directive, every variables spited by some characters, like '-', ' ' * (blank),'~' and so on. <br/> * So, these variety split character be abstracted SplitVarNode instance, * and origin variables that 'log_format' directive were abstracted * FormatVarNode instance, the end of config string that not belong * format variable or split variable was abstracted the EndSplitVarNode. * </p> * * @author xavier * @date 2017-08-22 */ public class LogFormatter { // log format pattern string private static String LOG_FORMAT_CONFIG = null; private static Pattern PATTERN = null; private static Map<String, Integer> FIELD_SEQUENCE_MAP = new HashMap<>(); public static void init(String logFormat) { if (null == LOG_FORMAT_CONFIG || null == PATTERN) { synchronized (LogFormatter.class) { if (null == LOG_FORMAT_CONFIG || null == PATTERN) { LOG_FORMAT_CONFIG = logFormat; initPattern(); } } } } public static AccessLog format(String logText) { if (null == logText || logText.length() == 0) { return null; } Matcher matcher = PATTERN.matcher(logText); matcher.find(); int groupCount = matcher.groupCount(); List<String> groupString = new ArrayList<>(); for (int i = 1; i <= groupCount; i++) { groupString.add(matcher.group(i)); } AccessLog.Builder builder = new AccessLog.Builder(); String timePattern = ""; if (LOG_FORMAT_CONFIG.contains("$time_local")) { timePattern = "dd/MMM/yyyy:HH:mm:ss Z"; } else { timePattern = "yyyy-MM-ddTHH:mm:ssZ"; } builder.setIp(getValue(Constant.IP, groupString)) .setBodyBytesSent(getValue(Constant.BODY_BYTES_SENT, groupString)) .setBytesSent(getValue(Constant.BYTES_SENT, groupString)) .setConnection(getValue(Constant.CONNECTION, groupString)) .setConnectionRequests(getValue(Constant.CONNECTION_REQUESTS, groupString)) .setHttpReferer(getValue(Constant.HTTP_REFERER, groupString)) .setPipe(getValue(Constant.PIPE, groupString)) .setRemoteUser(getValue(Constant.REMOTE_USER, groupString)) .setRequest(getValue(Constant.REQUEST, groupString)) .setRequestDateTime(getValue(Constant.REQUEST_DATE_TIME, groupString), timePattern) .setRequestLength(getValue(Constant.REQUEST_LENGTH, groupString)) .setRequestTime(getValue(Constant.REQUEST_TIME, groupString)) .setStatus(getValue(Constant.STATUS, groupString)) .setUserAgent(getValue(Constant.USER_AGENT, groupString)) .setUpstreamCacheStatus(getValue(Constant.UPSTREAM_CACHE_STATUS, groupString)) .setUpstreamResponseTime(getValue(Constant.UPSTREAM_RESPONSE_TIME, groupString)); return builder.build(); } /** * init PATTERN object, assembly regex expression by sequence of node chain */ private static void initPattern() { Node headNode = headNode(); Node currentNode = headNode; int i = -1; StringBuilder sb = new StringBuilder(); while (true) { i++; if (currentNode == null) break; if (i % 2 != 0) { String splitValue = Utils.replaceEscapeCode(currentNode.nodeValue); sb.append(splitValue); currentNode = currentNode.nextNode; continue; } NginxLogVariable nlv = NginxLogVariable.match(currentNode.nodeValue); if (nlv == null) { throw new IllegalArgumentException("given format string error."); } String extractRegx = nlv.getExtractRegx(); sb.append(extractRegx); currentNode = currentNode.nextNode; } System.out.println("regx: " + sb.toString()); PATTERN = Pattern.compile(sb.toString()); } private static String getValue(String valueName, List<String> groupString) { Integer index = FIELD_SEQUENCE_MAP.getOrDefault(valueName, -1); if (index == -1) { return null; } return groupString.get(index); } private static void initFormatVarSequence(List<String> formatVarList) { int len = formatVarList.size(); for (int i = 0; i < len; i++) { String format = formatVarList.get(i); NginxLogVariable nlv = NginxLogVariable.match(format); String key = nlv.getFieldName(); FIELD_SEQUENCE_MAP.put(key, i); } } /** * create a list that contain some node order by : <br/> * fNode(formatNode), sNode(separatorNode),fNode,sNode,fNode...eNode(endNode) * * @return */ private static List<Node> getNodeList() { List<String> formatVarList = getFormatVariableList(); List<String> configSeparatorList = getSeparatorVariableList(formatVarList); String endingSeparator = getEndingSeparator(formatVarList); initFormatVarSequence(formatVarList); int len = formatVarList.size() - 1; List<Node> nodeInstanceList = new ArrayList<>(); for (int i = 0; i < len; i++) { String formatVar = formatVarList.get(i); Node fvn = new FormatNode(formatVar); nodeInstanceList.add(fvn); String separatorVar = configSeparatorList.get(i); Node svn = new SeparatorNode(separatorVar); nodeInstanceList.add(svn); } Node fvn = new FormatNode(formatVarList.get(len)); nodeInstanceList.add(fvn); Node evn = new EndNode(endingSeparator); nodeInstanceList.add(evn); return nodeInstanceList; } /** * make node chain list by given params that contains some nodes. * @param nodeInstanceList * @return */ private static Node makeNodeChain(List<Node> nodeInstanceList) { int len = nodeInstanceList.size() - 1; for (int i = len; i > 0; i--) { Node node = nodeInstanceList.get(i); Node preNode = nodeInstanceList.get(i - 1); preNode.nextNode = node; } return nodeInstanceList.get(0); } private static Node headNode() { List<Node> nodeList = getNodeList(); return makeNodeChain(nodeList); } /** * get config of log format var's sequence list. * <p> * every variable start with '$', variable's name can contain: * <ul> * <li>Uppercase(A-Z)</li> * <li>Lowercase(a-z)</li> * <li>Number(0-9)</li> * <li>'_'</li> * </ul> * if a var start with '$',then the var was deemed end that the var's * name string are contain none of above list. * In short, a var start with '$' character and end with character * that except A-Z,a-z,0-9 and '_'. * </p> * <p> * e.g: origin format string: ($a...$b~$c - $d$e_f) --> * result list: {$a, $b, $c, $d, $e_f} * </p> * @return list of format variable */ private static List<String> getFormatVariableList() { char[] formatCharArray = LOG_FORMAT_CONFIG.toCharArray(); int start = -1; List<String> formatList = new ArrayList<>(); for (int i = 0; i < formatCharArray.length; i++) { if (Utils.isDollar(formatCharArray[i]) && start == -1) { start = i; } else if ((!Utils.isVariabelName(formatCharArray[i])) && (start != -1)){ String formatVar = LOG_FORMAT_CONFIG.substring(start, i); formatList.add(formatVar); start = -1; i--; } else if (i == formatCharArray.length - 1 && start != -1) { String formatVar = LOG_FORMAT_CONFIG.substring(start, i + 1); formatList.add(formatVar); start = -1; } } return formatList; } /** * get config of log format separator of vars sequence list. * <p> * the function of this method is same as {@link #getFormatVariableList},but * there has a different part that this method get separator that middle * of variables. * </p> * <p> * e.g: origin format string: ($a...$b~$c - $d$e_f&&&) --> * result list: {...,~, - ,,} (NOTE: not contain the last separator) * </p> * * @param formatVarList * @return list of separator * @throws IllegalArgumentException when params is null or empty. */ private static List<String> getSeparatorVariableList(List<String> formatVarList) { if (formatVarList == null || formatVarList.isEmpty()) { throw new IllegalArgumentException("the params is null or empty."); } int iteratorCount = formatVarList.size() - 1; List<String> separatorList = new ArrayList<>(iteratorCount); for (int i = 0; i < iteratorCount; i++) { String formatVar = formatVarList.get(i); int start = LOG_FORMAT_CONFIG.indexOf(formatVar); start = start + formatVar.length(); formatVar = formatVarList.get(i + 1); int end = LOG_FORMAT_CONFIG.indexOf(formatVar); separatorList.add(LOG_FORMAT_CONFIG.substring(start, end)); } return separatorList; } /** * get the last of log format config's identifier. * <p> * it's different with {@link #getSeparatorVariableList}, this method * only get the identifier or symbol (to be precise, is characters * that not a format variable) that end of format string. * </p> * * @param formatVarList * @return string of end separator * @throws IllegalArgumentException when params is null or empty. */ private static String getEndingSeparator(List<String> formatVarList) { if (formatVarList == null || formatVarList.isEmpty()) { throw new IllegalArgumentException("the params is null or empty."); } String endingSeparator = ""; String formatVar = formatVarList.get(formatVarList.size() - 1); int index = LOG_FORMAT_CONFIG.indexOf(formatVar); index = index + formatVar.length(); if (index < LOG_FORMAT_CONFIG.length()) { endingSeparator = LOG_FORMAT_CONFIG.substring(index); } return endingSeparator; } }
/** * Sapelli data collection platform: http://sapelli.org * * Copyright 2012-2016 University College London - ExCiteS group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.ucl.excites.sapelli.storage.model; import java.io.IOException; import uk.ac.ucl.excites.sapelli.storage.model.indexes.PrimaryKey; import uk.ac.ucl.excites.sapelli.storage.queries.constraints.AndConstraint; import uk.ac.ucl.excites.sapelli.storage.queries.constraints.Constraint; import uk.ac.ucl.excites.sapelli.storage.queries.constraints.EqualityConstraint; import uk.ac.ucl.excites.sapelli.storage.util.IncompletePrimaryKeyException; import uk.ac.ucl.excites.sapelli.storage.util.InvalidValueException; /** * Class representing a reference to another {@link Record}, identified by the value(s) of its primary key. * This is equivalent to a foreign key, as used to reference a record of another ("foreign") schema. * * Implemented as {@link RecordValueSet}, with an {@link PrimaryKey} instance (i.e. the primary key of the referenced, or "foreign" schema) as its {@link ColumnSet}. * * @author mstevens */ public class RecordReference extends RecordValueSet<PrimaryKey> { static private final long serialVersionUID = 2L; private final Schema referencedSchema; /** * Creates a new, but "empty", RecordReference which, once the column values have been set, can be used to reference a record of the given schema. * * @param referencedSchema (also called "foreign" schema) * @throws NullPointerException if the recordSchema does not have a primary key */ protected RecordReference(Schema referencedSchema) throws NullPointerException { super(referencedSchema.getPrimaryKey()); this.referencedSchema = referencedSchema; } /** * Creates a new RecordReference, to be used for referencing a record of the given schema, which is initialised with the given key part values. * * @param referencedSchema (also called "foreign" schema) * @param keyPartValues to initialise the recordReference, the number of values must match number of columns in primary key of the referencedSchema * @throws IllegalArgumentException in case of an incorrect number of values * @throws InvalidValueException in case of an invalid value * @throws NullPointerException if the referencedSchema does not have a primary key, of if one of the keyPartValues is null * @throws ClassCastException when a value cannot be converted/casted to the column's type {@code <T>} */ protected RecordReference(Schema referencedSchema, Object... keyPartValues) throws IllegalArgumentException, InvalidValueException, NullPointerException, ClassCastException { super(referencedSchema.getPrimaryKey(), keyPartValues); // We use the recordSchema's primary key as the schema for this record (i.e. for the recordReference, which is "a record" in its own right) this.referencedSchema = referencedSchema; } /** * Creates a new RecordReference, to be used for referencing a record of the given schema, which is initialised with the given serialised key part values. * * @param referencedSchema (also called "foreign" schema) * @param serialisedKeyPartValues to initialise the recordReference, the number of values must match number of columns in primary key of the referencedSchema * @throws NullPointerException if the referencedSchema does not have a primary key * @throws Exception when parsing serialisedValues fails */ protected RecordReference(Schema referencedSchema, String serialisedKeyPartValues) throws NullPointerException, Exception { super(referencedSchema.getPrimaryKey(), serialisedKeyPartValues); this.referencedSchema = referencedSchema; } /** * Creates a new RecordReference, to be used for referencing a record of the given schema, which is initialised with the given serialised key part values. * * @param referencedSchema (also called "foreign" schema) * @param serialisedKeyPartValues byte array to initialise the recordReference with, the number of values must match number of columns in primary key of the referencedSchema, and all values must be encoded losslessly * @throws NullPointerException if the referencedSchema does not have a primary key * @throws IOException when reading serialisedValues fails */ protected RecordReference(Schema referencedSchema, byte[] serialisedKeyPartValues) throws NullPointerException, IOException { super(referencedSchema.getPrimaryKey(), serialisedKeyPartValues, true /*always lossless, as values are part of PK!*/); this.referencedSchema = referencedSchema; } /** * Creates a new RecordReference which points to the given {@link Record}. * * @param record the Record to be referenced ("pointed to"), also called the "foreign" record * @throws NullPointerException if the Schema of the given Record does not have a primary key * @throws IncompletePrimaryKeyException if (part of) the primary key column(s) lacks a value */ public RecordReference(Record record) throws NullPointerException, IncompletePrimaryKeyException { this(record, false); // don't allow blanks! } /*package*/ /** * @param record * @param allowBlank if {@code true}, {@code null} key part values are allowed (note this will produce a RecordReference instance that cannot be used for querying RecordStores directly) * @throws NullPointerException * @throws IncompletePrimaryKeyException when the columns that are part of the primary key have not all been assigned a value, and {@code allowBlanks} is {@code false} */ RecordReference(Record record, boolean allowBlank) throws NullPointerException, IncompletePrimaryKeyException { this(record.getSchema()); // !!! // Copy the key part values: for(Column<?> keyPartCol : this.columnSet.getColumns(false)) { Object keyPartValue = keyPartCol.retrieveValueCopy(record); if(!allowBlank && keyPartValue == null) throw new IncompletePrimaryKeyException("Cannot construct RecordReference from record because key part \"" + keyPartCol.getName() + "\" has not been set"); setValue(keyPartCol, keyPartValue); } } /** * Copy constructor. * * @param another */ public RecordReference(RecordReference another) { super(another); // sets schema and copies values this.referencedSchema = another.referencedSchema; } /** * @return the referencedSchema */ public Schema getReferencedSchema() { return referencedSchema; } @Override protected Schema getSchema() { return getReferencedSchema(); } /** * Returns the RecordReference itself. * * @see uk.ac.ucl.excites.sapelli.storage.model.RecordValueSet#getReference() */ @Override public RecordReference getReference() { return this; } /** * Returns a {@link Constraint} that matches on the referenced record's primary key values. * * @param allowBlanks * @return a Constraint * @throws IncompletePrimaryKeyException when the columns that are part of the primary key (and thus covered by a recordReference) have not all been assigned a value, and {@code allowBlanks} is {@code false} * * @see uk.ac.ucl.excites.sapelli.storage.model.RecordValueSet#getRecordQueryConstraint() * @see uk.ac.ucl.excites.sapelli.storage.model.RecordValueSet#getRecordQueryConstraint(boolean) */ @Override /*package*/ Constraint getRecordQueryConstraint(boolean allowBlanks) throws IncompletePrimaryKeyException { if(!allowBlanks && !isFilled()) throw new IncompletePrimaryKeyException("All values of the key must be set before a record selecting constraint/query can be created!"); // Match for key parts: AndConstraint constraints = new AndConstraint(); int c = 0; for(Object keyPart : values) constraints.addConstraint(new EqualityConstraint(columnSet.getColumn(c++), keyPart)); return constraints.reduce(); } @Override public int hashCode() { int hash = super.hashCode(); hash = 31 * hash + referencedSchema.hashCode(); return hash; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj instanceof RecordReference) return super.equals(obj) && this.referencedSchema.equals(((RecordReference) obj).referencedSchema); return false; } }
package eta.runtime.parallel; import java.util.Deque; import java.util.concurrent.LinkedBlockingDeque; import eta.runtime.Runtime; import eta.runtime.stg.Capability; import eta.runtime.stg.Closure; import eta.runtime.stg.Closures; import eta.runtime.stg.StgContext; import static eta.runtime.RuntimeLogging.barf; import static eta.runtime.RuntimeLogging.debugScheduler; public class Parallel { public static final Deque<Closure> globalSparkPool = new LinkedBlockingDeque<Closure>(Runtime.getMaxLocalSparks()); public static final SparkCounters globalSparkStats = new SparkCounters(); public static Closure getSpark(StgContext context) { Closure spark = findSpark(context.myCapability); if (spark != null) { context.I1 = 1; return spark; } else { context.I1 = 0; return Closures.False; } } public static int numSparks(StgContext context) { return globalSparkPoolSize(); } public static Closure findSpark(Capability cap) { if (!cap.emptyRunQueue()) { return null; } boolean retry; do { retry = false; Closure spark = globalSparkPool.pollLast(); while (spark != null && spark.getEvaluated() != null) { globalSparkStats.fizzled.getAndIncrement(); spark = globalSparkPool.pollLast(); } if (spark != null) { globalSparkStats.converted.getAndIncrement(); return spark; } if (!emptyGlobalSparkPool()) { retry = true; } } while(retry); if (Runtime.debugScheduler()) { debugScheduler("No Sparks stolen."); } return null; } public static boolean emptyGlobalSparkPool() { return globalSparkPool.isEmpty(); } public static int globalSparkPoolSize() { return globalSparkPool.size(); } public static boolean anySparks() { return !emptyGlobalSparkPool(); } public static boolean submitSpark(Closure spark) { return globalSparkPool.offerFirst(spark); } }
/* * 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 io.datavines.engine.spark.executor.parameter; /** * support program types */ public enum ProgramType { /** * 0 JAVA,1 SCALA,2 PYTHON */ JAVA, SCALA, PYTHON }
package com.onlyleo.gankgirl.ui.adapter; import android.content.Context; import android.support.design.widget.Snackbar; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.onlyleo.gankgirl.R; import com.onlyleo.gankgirl.model.entity.Gank; import com.onlyleo.gankgirl.ui.activity.WebActivity; import com.onlyleo.gankgirl.utils.CommonTools; import com.onlyleo.gankgirl.utils.TipsUtil; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import smartisanos.api.OneStepHelper; public class GankDailyAdpter extends RecyclerView.Adapter<GankDailyAdpter.GankDailyHolder> { private List<Gank> list; private Context context; private OneStepHelper mOneStepHelper; public GankDailyAdpter(Context context, List<Gank> list) { mOneStepHelper = OneStepHelper.getInstance(context); this.list = list; this.context = context; } @Override public GankDailyHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gankdaily, parent, false); return new GankDailyHolder(view); } @Override public void onBindViewHolder(GankDailyHolder holder, final int position) { holder.gankllList.setTag(list.get(position)); if (position == 0) { showTitle(true, holder.titleList); } else { if (list.get(position).type.equals(list.get(position - 1).type)) { showTitle(false, holder.titleList); } else { showTitle(true, holder.titleList); } } if (holder.titleList.getVisibility() == View.VISIBLE) { holder.titleList.setText(list.get(position).type); } holder.linkList.setText(CommonTools.getGankStyleStr(list.get(position))); holder.gankllList.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOneStepHelper.isOneStepShowing()) { mOneStepHelper.dragLink(v,list.get(position).url); return true; } return false; } }); } private void showTitle(boolean show, TextView titleList) { if (show) { titleList.setVisibility(View.VISIBLE); } else { titleList.setVisibility(View.GONE); } } @Override public int getItemCount() { return list.size(); } class GankDailyHolder extends RecyclerView.ViewHolder { @BindView(R.id.gankll_list) LinearLayout gankllList; @BindView(R.id.title_list) TextView titleList; @BindView(R.id.link_list) TextView linkList; @OnClick(R.id.gankll_list) void onClick() { if ("休息视频".equals(((Gank) gankllList.getTag()).type)) { if (!CommonTools.isWIFIConnected(context)) { TipsUtil.showTipWithAction(itemView, "你使用的不是wifi网络,要继续吗?", "继续", new View.OnClickListener() { @Override public void onClick(View v) { WebActivity.loadWebViewActivity(context, (Gank) gankllList.getTag()); } }, Snackbar.LENGTH_LONG); } else { WebActivity.loadWebViewActivity(context, (Gank) gankllList.getTag()); } } else WebActivity.loadWebViewActivity(context, (Gank) gankllList.getTag()); } GankDailyHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
package com.qihoo.finance.chronus.metadata.api.group.dto; import com.qihoo.finance.chronus.metadata.api.group.entity.GroupEntity; import java.util.List; public interface GroupDao { void insert(GroupEntity groupEntity); void update(GroupEntity groupEntity); void deleteByGroupName(String groupName); List<GroupEntity> selectListAll(); GroupEntity selectByName(String name); }
import java.awt.*; import java.awt.event.*; public class KeyListenerExample extends Frame implements KeyListener{ Label l; TextArea area; KeyListenerExample(){ l=new Label(); l.setBounds(20,50,200,20); area=new TextArea(); area.setBounds(20,80,300, 300); area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true); } public void keyPressed(KeyEvent e) {System.out.println("KeyEvent");} public void keyReleased(KeyEvent e) { String text=area.getText(); String words[]=text.split("\\s"); l.setText("Words: "+words.length+" Characters:"+text.length()); } public void keyTyped(KeyEvent e) {} public static void main(String[] args) { new KeyListenerExample(); } }
package lebah.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @IdClass(UserTrackerId.class) @Table(name="user_tracker") public class UserTracker { @Id @Column(name="user_login", length=50) private String userLogin; @Id @Column(name="log_date") @Temporal(TemporalType.TIMESTAMP) private Date logDate; @Id @Column(name="remote_add", length=50) private String remoteAdd; @Column(name="log_year") private int logYear; @Column(name="log_month", length=50) private int logMonth; @Column(name="log_day", length=50) private int logDay; @Column(name="module_id", length=50) private String moduleId; @Column(name="module_class", length=100) private String moduleClass; @Column(name="module_name", length=100) private String moduleName; @Column(name="time12", length=50) private String time12; @Column(name="time24", length=50) private String time24; @Column(name="str_date", length=50) private String strDate; public String getUserLogin() { return userLogin; } public void setUserLogin(String userLogin) { this.userLogin = userLogin; } public int getLogYear() { return logYear; } public void setLogYear(int logYear) { this.logYear = logYear; } public int getLogMonth() { return logMonth; } public void setLogMonth(int logMonth) { this.logMonth = logMonth; } public int getLogDay() { return logDay; } public void setLogDay(int logDay) { this.logDay = logDay; } public String getModuleId() { return moduleId; } public void setModuleId(String moduleId) { this.moduleId = moduleId; } public String getModuleClass() { return moduleClass; } public void setModuleClass(String moduleClass) { this.moduleClass = moduleClass; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getTime12() { return time12; } public void setTime12(String time12) { this.time12 = time12; } public String getTime24() { return time24; } public void setTime24(String time24) { this.time24 = time24; } public String getStrDate() { return strDate; } public void setStrDate(String strDate) { this.strDate = strDate; } public String getRemote_add() { return remoteAdd; } public void setRemote_add(String remote_add) { this.remoteAdd = remote_add; } public Date getLogDate() { return logDate; } public void setLogDate(Date logDate) { this.logDate = logDate; } }
package com.huaweicloud.sdk.dds.v3.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.dds.v3.model.CreateInstanceRequestBody; import java.util.function.Consumer; import java.util.Objects; /** * Request Object */ public class CreateInstanceRequest { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="body") private CreateInstanceRequestBody body; public CreateInstanceRequest withBody(CreateInstanceRequestBody body) { this.body = body; return this; } public CreateInstanceRequest withBody(Consumer<CreateInstanceRequestBody> bodySetter) { if(this.body == null ){ this.body = new CreateInstanceRequestBody(); bodySetter.accept(this.body); } return this; } /** * Get body * @return body */ public CreateInstanceRequestBody getBody() { return body; } public void setBody(CreateInstanceRequestBody body) { this.body = body; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateInstanceRequest createInstanceRequest = (CreateInstanceRequest) o; return Objects.equals(this.body, createInstanceRequest.body); } @Override public int hashCode() { return Objects.hash(body); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateInstanceRequest {\n"); sb.append(" body: ").append(toIndentedString(body)).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 "); } }
/* * Copyright © 2019 Apple Inc. and the ServiceTalk project 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 io.servicetalk.http.api; import io.servicetalk.buffer.api.Buffer; import io.servicetalk.concurrent.api.Publisher; import io.servicetalk.encoding.api.ContentCodec; import java.nio.charset.Charset; import javax.annotation.Nullable; import static io.servicetalk.concurrent.api.Publisher.from; import static java.util.Objects.requireNonNull; final class DefaultHttpRequest extends AbstractDelegatingHttpRequest implements HttpRequest, TrailersTransformer<Object, Buffer> { private Buffer payloadBody; @Nullable private HttpHeaders trailers; DefaultHttpRequest(final DefaultStreamingHttpRequest original, final Buffer payloadBody, @Nullable final HttpHeaders trailers) { super(original); this.payloadBody = payloadBody; this.trailers = trailers; } @Override public HttpRequest version(final HttpProtocolVersion version) { original.version(version); return this; } @Override public HttpRequest encoding(final ContentCodec encoding) { original.encoding(encoding); return this; } @Override public HttpRequest method(final HttpRequestMethod method) { original.method(method); return this; } @Override public HttpRequest requestTarget(final String requestTarget) { original.requestTarget(requestTarget); return this; } @Override public HttpRequest requestTarget(final String requestTarget, final Charset encoding) { original.requestTarget(requestTarget, encoding); return this; } @Override public HttpRequest rawPath(final String path) { original.rawPath(path); return this; } @Override public HttpRequest path(final String path) { original.path(path); return this; } @Override public HttpRequest appendPathSegments(final String... segments) { original.appendPathSegments(segments); return this; } @Override public HttpRequest rawQuery(@Nullable final String query) { original.rawQuery(query); return this; } @Override public HttpRequest query(@Nullable final String query) { original.query(query); return this; } @Override public HttpRequest addQueryParameter(final String key, final String value) { original.addQueryParameter(key, value); return this; } @Override public HttpRequest addQueryParameters(final String key, final Iterable<String> values) { original.addQueryParameters(key, values); return this; } @Override public HttpRequest addQueryParameters(final String key, final String... values) { original.addQueryParameters(key, values); return this; } @Override public HttpRequest setQueryParameter(final String key, final String value) { original.setQueryParameter(key, value); return this; } @Override public HttpRequest setQueryParameters(final String key, final Iterable<String> values) { original.setQueryParameters(key, values); return this; } @Override public HttpRequest setQueryParameters(final String key, final String... values) { original.setQueryParameters(key, values); return this; } @Override public HttpRequest addHeader(final CharSequence name, final CharSequence value) { original.addHeader(name, value); return this; } @Override public HttpRequest addHeaders(final HttpHeaders headers) { original.addHeaders(headers); return this; } @Override public HttpRequest setHeader(final CharSequence name, final CharSequence value) { original.setHeader(name, value); return this; } @Override public HttpRequest setHeaders(final HttpHeaders headers) { original.setHeaders(headers); return this; } @Override public HttpRequest addCookie(final HttpCookiePair cookie) { original.addCookie(cookie); return this; } @Override public HttpRequest addCookie(final CharSequence name, final CharSequence value) { original.addCookie(name, value); return this; } @Override public HttpRequest addSetCookie(final HttpSetCookie cookie) { original.addSetCookie(cookie); return this; } @Override public HttpRequest addSetCookie(final CharSequence name, final CharSequence value) { original.addSetCookie(name, value); return this; } @Override public Buffer payloadBody() { return payloadBody; } @Override public HttpRequest payloadBody(final Buffer payloadBody) { this.payloadBody = requireNonNull(payloadBody); original.payloadBody(from(payloadBody)); return this; } @Override public <T> HttpRequest payloadBody(final T pojo, final HttpSerializer<T> serializer) { this.payloadBody = serializer.serialize(headers(), pojo, original.payloadHolder().allocator()); original.payloadBody(from(payloadBody)); return this; } @Override public HttpHeaders trailers() { if (trailers == null) { trailers = original.payloadHolder().headersFactory().newTrailers(); original.transform(this); } return trailers; } @Override public Object newState() { return null; } @Override public Buffer accept(final Object __, final Buffer buffer) { return buffer; } @Override public HttpHeaders payloadComplete(final Object __, final HttpHeaders extTrailers) { return trailers == null ? extTrailers : trailers; } @Override public HttpHeaders catchPayloadFailure(final Object __, final Throwable cause, final HttpHeaders ___) throws Throwable { throw cause; } @Override public StreamingHttpRequest toStreamingRequest() { final DefaultPayloadInfo payloadInfo; final Publisher<Object> payload; if (trailers != null) { payload = from(payloadBody, trailers); payloadInfo = new DefaultPayloadInfo(this).setMayHaveTrailersAndGenericTypeBuffer(true); } else { payload = from(payloadBody); payloadInfo = new DefaultPayloadInfo(this).setMayHaveTrailersAndGenericTypeBuffer(false); } return new DefaultStreamingHttpRequest(method(), requestTarget(), version(), headers(), encoding(), original.payloadHolder().allocator(), payload, payloadInfo, original.payloadHolder().headersFactory()); } @Override public BlockingStreamingHttpRequest toBlockingStreamingRequest() { return toStreamingRequest().toBlockingStreamingRequest(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final DefaultHttpRequest that = (DefaultHttpRequest) o; if (!payloadBody.equals(that.payloadBody)) { return false; } return trailers != null ? trailers.equals(that.trailers) : that.trailers == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + payloadBody.hashCode(); result = 31 * result + (trailers != null ? trailers.hashCode() : 0); return result; } }
package co.yixiang.framework.config; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.Filter; import co.yixiang.framework.shiro.realm.UserRealm; import co.yixiang.framework.shiro.session.OnlineSessionDAO; import co.yixiang.framework.shiro.session.OnlineSessionFactory; import co.yixiang.framework.shiro.web.filter.LogoutFilter; import co.yixiang.framework.shiro.web.filter.captcha.CaptchaValidateFilter; import co.yixiang.framework.shiro.web.filter.kickout.KickoutSessionFilter; import co.yixiang.framework.shiro.web.filter.online.OnlineSessionFilter; import co.yixiang.framework.shiro.web.filter.sync.SyncOnlineSessionFilter; import co.yixiang.framework.shiro.web.session.OnlineWebSessionManager; import co.yixiang.framework.shiro.web.session.SpringSessionValidationScheduler; import org.apache.commons.io.IOUtils; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.config.ConfigurationException; import org.apache.shiro.io.ResourceUtils; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.CookieRememberMeManager; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.servlet.SimpleCookie; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import co.yixiang.common.constant.Constants; import co.yixiang.common.utils.StringUtils; import co.yixiang.common.utils.security.CipherUtils; import co.yixiang.common.utils.spring.SpringUtils; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; /** * 权限配置加载 * * @author ruoyi */ @Configuration public class ShiroConfig { /** * Session超时时间,单位为毫秒(默认30分钟) */ @Value("${shiro.session.expireTime}") private int expireTime; /** * 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟 */ @Value("${shiro.session.validationInterval}") private int validationInterval; /** * 同一个用户最大会话数 */ @Value("${shiro.session.maxSession}") private int maxSession; /** * 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户 */ @Value("${shiro.session.kickoutAfter}") private boolean kickoutAfter; /** * 验证码开关 */ @Value("${shiro.user.captchaEnabled}") private boolean captchaEnabled; /** * 验证码类型 */ @Value("${shiro.user.captchaType}") private String captchaType; /** * 设置Cookie的域名 */ @Value("${shiro.cookie.domain}") private String domain; /** * 设置cookie的有效访问路径 */ @Value("${shiro.cookie.path}") private String path; /** * 设置HttpOnly属性 */ @Value("${shiro.cookie.httpOnly}") private boolean httpOnly; /** * 设置Cookie的过期时间,秒为单位 */ @Value("${shiro.cookie.maxAge}") private int maxAge; /** * 登录地址 */ @Value("${shiro.user.loginUrl}") private String loginUrl; /** * 权限认证失败地址 */ @Value("${shiro.user.unauthorizedUrl}") private String unauthorizedUrl; /** * 缓存管理器 使用Ehcache实现 */ @Bean public EhCacheManager getEhCacheManager() { net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("ruoyi"); EhCacheManager em = new EhCacheManager(); if (StringUtils.isNull(cacheManager)) { em.setCacheManager(new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream())); return em; } else { em.setCacheManager(cacheManager); return em; } } /** * 返回配置文件流 避免ehcache配置文件一直被占用,无法完全销毁项目重新部署 */ protected InputStream getCacheManagerConfigFileInputStream() { String configFile = "classpath:ehcache/ehcache-shiro.xml"; InputStream inputStream = null; try { inputStream = ResourceUtils.getInputStreamForPath(configFile); byte[] b = IOUtils.toByteArray(inputStream); InputStream in = new ByteArrayInputStream(b); return in; } catch (IOException e) { throw new ConfigurationException( "Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e); } finally { IOUtils.closeQuietly(inputStream); } } /** * 自定义Realm */ @Bean public UserRealm userRealm(EhCacheManager cacheManager) { UserRealm userRealm = new UserRealm(); userRealm.setAuthorizationCacheName(Constants.SYS_AUTH_CACHE); userRealm.setCacheManager(cacheManager); return userRealm; } /** * 自定义sessionDAO会话 */ @Bean public OnlineSessionDAO sessionDAO() { OnlineSessionDAO sessionDAO = new OnlineSessionDAO(); return sessionDAO; } /** * 自定义sessionFactory会话 */ @Bean public OnlineSessionFactory sessionFactory() { OnlineSessionFactory sessionFactory = new OnlineSessionFactory(); return sessionFactory; } /** * 会话管理器 */ @Bean public OnlineWebSessionManager sessionManager() { OnlineWebSessionManager manager = new OnlineWebSessionManager(); // 加入缓存管理器 manager.setCacheManager(getEhCacheManager()); // 删除过期的session manager.setDeleteInvalidSessions(true); // 设置全局session超时时间 manager.setGlobalSessionTimeout(expireTime * 60 * 1000); // 去掉 JSESSIONID manager.setSessionIdUrlRewritingEnabled(false); // 定义要使用的无效的Session定时调度器 manager.setSessionValidationScheduler(SpringUtils.getBean(SpringSessionValidationScheduler.class)); // 是否定时检查session manager.setSessionValidationSchedulerEnabled(true); // 自定义SessionDao manager.setSessionDAO(sessionDAO()); // 自定义sessionFactory manager.setSessionFactory(sessionFactory()); return manager; } /** * 安全管理器 */ @Bean public SecurityManager securityManager(UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 设置realm. securityManager.setRealm(userRealm); // 记住我 securityManager.setRememberMeManager(rememberMeManager()); // 注入缓存管理器; securityManager.setCacheManager(getEhCacheManager()); // session管理器 securityManager.setSessionManager(sessionManager()); return securityManager; } /** * 退出过滤器 */ public LogoutFilter logoutFilter() { LogoutFilter logoutFilter = new LogoutFilter(); logoutFilter.setLoginUrl(loginUrl); return logoutFilter; } /** * Shiro过滤器配置 */ @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // Shiro的核心安全接口,这个属性是必须的 shiroFilterFactoryBean.setSecurityManager(securityManager); // 身份认证失败,则跳转到登录页面的配置 shiroFilterFactoryBean.setLoginUrl(loginUrl); // 权限认证失败,则跳转到指定页面 shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl); // Shiro连接约束配置,即过滤链的定义 LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // 对静态资源设置匿名访问 filterChainDefinitionMap.put("/favicon.ico**", "anon"); filterChainDefinitionMap.put("/ruoyi.png**", "anon"); filterChainDefinitionMap.put("/html/**", "anon"); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/docs/**", "anon"); filterChainDefinitionMap.put("/fonts/**", "anon"); filterChainDefinitionMap.put("/img/**", "anon"); filterChainDefinitionMap.put("/ajax/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/ruoyi/**", "anon"); filterChainDefinitionMap.put("/captcha/captchaImage**", "anon"); // 退出 logout地址,shiro去清除session filterChainDefinitionMap.put("/logout", "logout"); // 不需要拦截的访问 filterChainDefinitionMap.put("/login", "anon,captchaValidate"); // 注册相关 filterChainDefinitionMap.put("/register", "anon,captchaValidate"); // 系统权限列表 // filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll()); Map<String, Filter> filters = new LinkedHashMap<String, Filter>(); filters.put("onlineSession", onlineSessionFilter()); filters.put("syncOnlineSession", syncOnlineSessionFilter()); filters.put("captchaValidate", captchaValidateFilter()); filters.put("kickout", kickoutSessionFilter()); // 注销成功,则跳转到指定页面 filters.put("logout", logoutFilter()); shiroFilterFactoryBean.setFilters(filters); // 所有请求需要认证 filterChainDefinitionMap.put("/**", "user,kickout,onlineSession,syncOnlineSession"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * 自定义在线用户处理过滤器 */ public OnlineSessionFilter onlineSessionFilter() { OnlineSessionFilter onlineSessionFilter = new OnlineSessionFilter(); onlineSessionFilter.setLoginUrl(loginUrl); onlineSessionFilter.setOnlineSessionDAO(sessionDAO()); return onlineSessionFilter; } /** * 自定义在线用户同步过滤器 */ public SyncOnlineSessionFilter syncOnlineSessionFilter() { SyncOnlineSessionFilter syncOnlineSessionFilter = new SyncOnlineSessionFilter(); syncOnlineSessionFilter.setOnlineSessionDAO(sessionDAO()); return syncOnlineSessionFilter; } /** * 自定义验证码过滤器 */ public CaptchaValidateFilter captchaValidateFilter() { CaptchaValidateFilter captchaValidateFilter = new CaptchaValidateFilter(); captchaValidateFilter.setCaptchaEnabled(captchaEnabled); captchaValidateFilter.setCaptchaType(captchaType); return captchaValidateFilter; } /** * cookie 属性设置 */ public SimpleCookie rememberMeCookie() { SimpleCookie cookie = new SimpleCookie("rememberMe"); cookie.setDomain(domain); cookie.setPath(path); cookie.setHttpOnly(httpOnly); cookie.setMaxAge(maxAge * 24 * 60 * 60); return cookie; } /** * 记住我 */ public CookieRememberMeManager rememberMeManager() { CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); cookieRememberMeManager.setCipherKey(CipherUtils.generateNewKey(128, "AES").getEncoded()); return cookieRememberMeManager; } /** * 同一个用户多设备登录限制 */ public KickoutSessionFilter kickoutSessionFilter() { KickoutSessionFilter kickoutSessionFilter = new KickoutSessionFilter(); kickoutSessionFilter.setCacheManager(getEhCacheManager()); kickoutSessionFilter.setSessionManager(sessionManager()); // 同一个用户最大的会话数,默认-1无限制;比如2的意思是同一个用户允许最多同时两个人登录 kickoutSessionFilter.setMaxSession(maxSession); // 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序 kickoutSessionFilter.setKickoutAfter(kickoutAfter); // 被踢出后重定向到的地址; kickoutSessionFilter.setKickoutUrl("/login?kickout=1"); return kickoutSessionFilter; } /** * thymeleaf模板引擎和shiro框架的整合 */ @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } /** * 开启Shiro注解通知器 */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( @Qualifier("securityManager") SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.FailoverEndPoint; import org.wso2.developerstudio.eclipse.gmf.esb.FailoverEndPointWestOutputConnector; /** * @generated */ public class FailoverEndPointWestOutputConnector2CreateCommand extends EditElementCommand { /** * @generated */ public FailoverEndPointWestOutputConnector2CreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { FailoverEndPoint container = (FailoverEndPoint) getElementToEdit(); if (container.getWestOutputConnector() != null) { return false; } return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { FailoverEndPointWestOutputConnector newElement = EsbFactory.eINSTANCE .createFailoverEndPointWestOutputConnector(); FailoverEndPoint owner = (FailoverEndPoint) getElementToEdit(); owner.setWestOutputConnector(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(FailoverEndPointWestOutputConnector newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
/* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.core.api.score.buildin.hardmediumsoft; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test; import org.optaplanner.core.api.score.buildin.AbstractScoreTest; import org.optaplanner.core.impl.testdata.util.PlannerAssert; import org.optaplanner.core.impl.testdata.util.PlannerTestUtils; public class HardMediumSoftScoreTest extends AbstractScoreTest { @Test public void of() { assertEquals(HardMediumSoftScore.of(-147, 0, 0), HardMediumSoftScore.ofHard(-147)); assertEquals(HardMediumSoftScore.of(0, -258, 0), HardMediumSoftScore.ofMedium(-258)); assertEquals(HardMediumSoftScore.of(0, 0, -369), HardMediumSoftScore.ofSoft(-369)); } @Test public void parseScore() { assertEquals(HardMediumSoftScore.of(-147, -258, -369), HardMediumSoftScore.parseScore("-147hard/-258medium/-369soft")); assertEquals(HardMediumSoftScore.ofUninitialized(-7, -147, -258, -369), HardMediumSoftScore.parseScore("-7init/-147hard/-258medium/-369soft")); assertEquals(HardMediumSoftScore.of(-147, -258, Integer.MIN_VALUE), HardMediumSoftScore.parseScore("-147hard/-258medium/*soft")); assertEquals(HardMediumSoftScore.of(-147, Integer.MIN_VALUE, -369), HardMediumSoftScore.parseScore("-147hard/*medium/-369soft")); } @Test public void toShortString() { assertEquals("0", HardMediumSoftScore.of(0, 0, 0).toShortString()); assertEquals("-369soft", HardMediumSoftScore.of(0, 0, -369).toShortString()); assertEquals("-258medium", HardMediumSoftScore.of(0, -258, 0).toShortString()); assertEquals("-258medium/-369soft", HardMediumSoftScore.of(0, -258, -369).toShortString()); assertEquals("-147hard/-258medium/-369soft", HardMediumSoftScore.of(-147, -258, -369).toShortString()); assertEquals("-7init/-258medium", HardMediumSoftScore.ofUninitialized(-7, 0, -258, 0).toShortString()); assertEquals("-7init/-147hard/-258medium/-369soft", HardMediumSoftScore.ofUninitialized(-7, -147, -258, -369).toShortString()); } @Test public void testToString() { assertEquals("0hard/-258medium/-369soft", HardMediumSoftScore.of(0, -258, -369).toString()); assertEquals("-147hard/-258medium/-369soft", HardMediumSoftScore.of(-147, -258, -369).toString()); assertEquals("-7init/-147hard/-258medium/-369soft", HardMediumSoftScore.ofUninitialized(-7, -147, -258, -369).toString()); } @Test public void parseScoreIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> HardMediumSoftScore.parseScore("-147")); } @Test public void toInitializedScore() { assertEquals(HardMediumSoftScore.of(-147, -258, -369), HardMediumSoftScore.of(-147, -258, -369).toInitializedScore()); assertEquals(HardMediumSoftScore.of(-147, -258, -369), HardMediumSoftScore.ofUninitialized(-7, -147, -258, -369).toInitializedScore()); } @Test public void withInitScore() { assertEquals(HardMediumSoftScore.ofUninitialized(-7, -147, -258, -369), HardMediumSoftScore.of(-147, -258, -369).withInitScore(-7)); } @Test public void feasible() { assertScoreNotFeasible( HardMediumSoftScore.of(-5, -300, -4000), HardMediumSoftScore.ofUninitialized(-7, -5, -300, -4000), HardMediumSoftScore.ofUninitialized(-7, 0, -300, -4000)); assertScoreFeasible( HardMediumSoftScore.of(0, -300, -4000), HardMediumSoftScore.of(2, -300, -4000), HardMediumSoftScore.ofUninitialized(0, 0, -300, -4000)); } @Test public void add() { assertEquals(HardMediumSoftScore.of(19, -320, 0), HardMediumSoftScore.of(20, -20, -4000).add( HardMediumSoftScore.of(-1, -300, 4000))); assertEquals(HardMediumSoftScore.ofUninitialized(-77, 19, -320, 0), HardMediumSoftScore.ofUninitialized(-70, 20, -20, -4000).add( HardMediumSoftScore.ofUninitialized(-7, -1, -300, 4000))); } @Test public void subtract() { assertEquals(HardMediumSoftScore.of(21, 280, -8000), HardMediumSoftScore.of(20, -20, -4000).subtract( HardMediumSoftScore.of(-1, -300, 4000))); assertEquals(HardMediumSoftScore.ofUninitialized(-63, 21, 280, -8000), HardMediumSoftScore.ofUninitialized(-70, 20, -20, -4000).subtract( HardMediumSoftScore.ofUninitialized(-7, -1, -300, 4000))); } @Test public void multiply() { assertEquals(HardMediumSoftScore.of(6, -6, 6), HardMediumSoftScore.of(5, -5, 5).multiply(1.2)); assertEquals(HardMediumSoftScore.of(1, -2, 1), HardMediumSoftScore.of(1, -1, 1).multiply(1.2)); assertEquals(HardMediumSoftScore.of(4, -5, 4), HardMediumSoftScore.of(4, -4, 4).multiply(1.2)); assertEquals(HardMediumSoftScore.ofUninitialized(-14, 8, -10, 12), HardMediumSoftScore.ofUninitialized(-7, 4, -5, 6).multiply(2.0)); } @Test public void divide() { assertEquals(HardMediumSoftScore.of(5, -5, 5), HardMediumSoftScore.of(25, -25, 25).divide(5.0)); assertEquals(HardMediumSoftScore.of(4, -5, 4), HardMediumSoftScore.of(21, -21, 21).divide(5.0)); assertEquals(HardMediumSoftScore.of(4, -5, 4), HardMediumSoftScore.of(24, -24, 24).divide(5.0)); assertEquals(HardMediumSoftScore.ofUninitialized(-7, 4, -5, 6), HardMediumSoftScore.ofUninitialized(-14, 8, -10, 12).divide(2.0)); } @Test public void power() { assertEquals(HardMediumSoftScore.of(9, 16, 25), HardMediumSoftScore.of(3, -4, 5).power(2.0)); assertEquals(HardMediumSoftScore.of(3, 4, 5), HardMediumSoftScore.of(9, 16, 25).power(0.5)); assertEquals(HardMediumSoftScore.ofUninitialized(-343, 27, -64, 125), HardMediumSoftScore.ofUninitialized(-7, 3, -4, 5).power(3.0)); } @Test public void negate() { assertEquals(HardMediumSoftScore.of(-3, 4, -5), HardMediumSoftScore.of(3, -4, 5).negate()); assertEquals(HardMediumSoftScore.of(3, -4, 5), HardMediumSoftScore.of(-3, 4, -5).negate()); } @Test public void equalsAndHashCode() { PlannerAssert.assertObjectsAreEqual( HardMediumSoftScore.of(-10, -200, -3000), HardMediumSoftScore.of(-10, -200, -3000), HardMediumSoftScore.ofUninitialized(0, -10, -200, -3000)); PlannerAssert.assertObjectsAreEqual( HardMediumSoftScore.ofUninitialized(-7, -10, -200, -3000), HardMediumSoftScore.ofUninitialized(-7, -10, -200, -3000)); PlannerAssert.assertObjectsAreNotEqual( HardMediumSoftScore.of(-10, -200, -3000), HardMediumSoftScore.of(-30, -200, -3000), HardMediumSoftScore.of(-10, -400, -3000), HardMediumSoftScore.of(-10, -400, -5000), HardMediumSoftScore.ofUninitialized(-7, -10, -200, -3000)); } @Test public void compareTo() { PlannerAssert.assertCompareToOrder( HardMediumSoftScore.ofUninitialized(-8, 0, 0, 0), HardMediumSoftScore.ofUninitialized(-7, -20, -20, -20), HardMediumSoftScore.ofUninitialized(-7, -1, -300, -4000), HardMediumSoftScore.ofUninitialized(-7, 0, 0, 0), HardMediumSoftScore.ofUninitialized(-7, 0, 0, 1), HardMediumSoftScore.ofUninitialized(-7, 0, 1, 0), HardMediumSoftScore.of(-20, Integer.MIN_VALUE, Integer.MIN_VALUE), HardMediumSoftScore.of(-20, Integer.MIN_VALUE, -20), HardMediumSoftScore.of(-20, Integer.MIN_VALUE, 1), HardMediumSoftScore.of(-20, -300, -4000), HardMediumSoftScore.of(-20, -300, -300), HardMediumSoftScore.of(-20, -300, -20), HardMediumSoftScore.of(-20, -300, 300), HardMediumSoftScore.of(-20, -20, -300), HardMediumSoftScore.of(-20, -20, 0), HardMediumSoftScore.of(-20, -20, 1), HardMediumSoftScore.of(-1, -300, -4000), HardMediumSoftScore.of(-1, -300, -20), HardMediumSoftScore.of(-1, -20, -300), HardMediumSoftScore.of(1, Integer.MIN_VALUE, -20), HardMediumSoftScore.of(1, -20, Integer.MIN_VALUE)); } @Test public void serializeAndDeserialize() { PlannerTestUtils.serializeAndDeserializeWithAll( HardMediumSoftScore.of(-12, 3400, -56), output -> { assertEquals(0, output.getInitScore()); assertEquals(-12, output.getHardScore()); assertEquals(3400, output.getMediumScore()); assertEquals(-56, output.getSoftScore()); }); PlannerTestUtils.serializeAndDeserializeWithAll( HardMediumSoftScore.ofUninitialized(-7, -12, 3400, -56), output -> { assertEquals(-7, output.getInitScore()); assertEquals(-12, output.getHardScore()); assertEquals(3400, output.getMediumScore()); assertEquals(-56, output.getSoftScore()); }); } }
/* * Copyright 2015-present Open Networking Laboratory * * 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.onosproject.cli.net; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.math.RandomUtils; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onlab.packet.MacAddress; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.Device; import org.onosproject.net.PortNumber; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleOperations; import org.onosproject.net.flow.FlowRuleOperationsContext; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; /** * Installs bulk flows. */ @Command(scope = "onos", name = "add-test-flows", description = "Installs a number of test flow rules - for testing only") public class AddTestFlowsCommand extends AbstractShellCommand { private static final int MAX_OUT_PORT = 65279; private CountDownLatch latch; @Argument(index = 0, name = "flowPerDevice", description = "Number of flows to add per device", required = true, multiValued = false) String flows = null; @Argument(index = 1, name = "numOfRuns", description = "Number of iterations", required = true, multiValued = false) String numOfRuns = null; @Override @java.lang.SuppressWarnings("squid:S1148") protected void execute() { FlowRuleService flowService = get(FlowRuleService.class); DeviceService deviceService = get(DeviceService.class); CoreService coreService = get(CoreService.class); ApplicationId appId = coreService.registerApplication("onos.test.flow.installer"); int flowsPerDevice = Integer.parseInt(flows); int num = Integer.parseInt(numOfRuns); ArrayList<Long> results = Lists.newArrayList(); Iterable<Device> devices = deviceService.getDevices(); TrafficTreatment treatment = DefaultTrafficTreatment.builder() .setOutput(PortNumber.portNumber(RandomUtils.nextInt(MAX_OUT_PORT))).build(); TrafficSelector.Builder sbuilder; FlowRuleOperations.Builder rules = FlowRuleOperations.builder(); FlowRuleOperations.Builder remove = FlowRuleOperations.builder(); for (Device d : devices) { for (int i = 0; i < flowsPerDevice; i++) { sbuilder = DefaultTrafficSelector.builder(); sbuilder.matchEthSrc(MacAddress.valueOf(RandomUtils.nextInt() * i)) .matchEthDst(MacAddress.valueOf((Integer.MAX_VALUE - i) * RandomUtils.nextInt())); int randomPriority = RandomUtils.nextInt(); FlowRule addRule = DefaultFlowRule.builder() .forDevice(d.id()) .withSelector(sbuilder.build()) .withTreatment(treatment) .withPriority(randomPriority) .fromApp(appId) .makeTemporary(10) .build(); FlowRule removeRule = DefaultFlowRule.builder() .forDevice(d.id()) .withSelector(sbuilder.build()) .withTreatment(treatment) .withPriority(randomPriority) .fromApp(appId) .makeTemporary(10) .build(); rules.add(addRule); remove.remove(removeRule); } } for (int i = 0; i < num; i++) { latch = new CountDownLatch(2); flowService.apply(rules.build(new FlowRuleOperationsContext() { private final Stopwatch timer = Stopwatch.createStarted(); @Override public void onSuccess(FlowRuleOperations ops) { timer.stop(); results.add(timer.elapsed(TimeUnit.MILLISECONDS)); if (results.size() == num) { if (outputJson()) { print("%s", json(new ObjectMapper(), true, results)); } else { printTime(true, results); } } latch.countDown(); } })); flowService.apply(remove.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { latch.countDown(); } })); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } private Object json(ObjectMapper mapper, boolean isSuccess, ArrayList<Long> elapsed) { ObjectNode result = mapper.createObjectNode(); result.put("Success", isSuccess); ArrayNode node = result.putArray("elapsed-time"); for (Long v : elapsed) { node.add(v); } return result; } private void printTime(boolean isSuccess, ArrayList<Long> elapsed) { print("Run is %s.", isSuccess ? "success" : "failure"); for (int i = 0; i < elapsed.size(); i++) { print(" Run %s : %s", i, elapsed.get(i)); } } }
package net.redbear.redbearduo.data.communication; import android.bluetooth.BluetoothClass; import android.content.Context; import android.net.nsd.NsdManager; import android.net.nsd.NsdServiceInfo; import android.util.Log; import java.net.InetAddress; /** * Created by dong on 3/22/16. */ public class MDNSManage { private static final String TAG = "MDNSManage"; private NsdManager mNsdManager; private NsdManager.DiscoveryListener mDiscoveryListener; private NsdManager.ResolveListener mResolveListener; private OnMDNSDevicesScanCallback onMDNSDevicesScanCallback; private boolean discoveryFlg = false; public MDNSManage(Context context){ mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE); } public void scanMDNSDevices(String serviceType){ if (mNsdManager == null) return; if (discoveryFlg){ return; }else { discoveryFlg = true; } mDiscoveryListener = new NsdManager.DiscoveryListener() { @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "onStartDiscoveryFailed........"); } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "onStopDiscoveryFailed........"); } @Override public void onDiscoveryStarted(String serviceType) { Log.e(TAG, "onDiscoveryStarted........"); } @Override public void onDiscoveryStopped(String serviceType) { Log.e(TAG, "onDiscoveryStopped........"); } @Override public void onServiceFound(NsdServiceInfo serviceInfo) { Log.e(TAG, "onServiceFound........"); Log.e(TAG, "onServiceFound........"+serviceInfo.toString()); mResolveListener = new NsdManager.ResolveListener() { @Override public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { Log.e(TAG, "Resolve failed" + errorCode); } @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { Log.e(TAG, "onServiceResolved"); Log.e(TAG, "onServiceResolved........"+serviceInfo.toString()); if (onMDNSDevicesScanCallback != null) onMDNSDevicesScanCallback.onScanCallback(serviceInfo.getServiceName(),serviceInfo.getHost().getHostAddress(),serviceInfo.getPort()); } }; mNsdManager.resolveService(serviceInfo,mResolveListener); } @Override public void onServiceLost(NsdServiceInfo serviceInfo) { Log.e(TAG, "onServiceLost........"); } }; mNsdManager.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); } public void stopServiceDiscovery(){ if (discoveryFlg){ discoveryFlg = false; }else { return; } mNsdManager.stopServiceDiscovery(mDiscoveryListener); } public void setOnMDNSDevicesScanCallback(OnMDNSDevicesScanCallback onMDNSDevicesScanCallback) { this.onMDNSDevicesScanCallback = onMDNSDevicesScanCallback; } public interface OnMDNSDevicesScanCallback{ void onScanCallback(String name,String IP,int port); } }
package net.minecraft.server; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.mojang.datafixers.DSL; import com.mojang.datafixers.DataFix; import com.mojang.datafixers.TypeRewriteRule; import com.mojang.datafixers.Typed; import com.mojang.datafixers.schemas.Schema; import com.mojang.datafixers.types.Type; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Dynamic; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; public class DataConverterStatistic extends DataFix { private static final Set<String> a = ImmutableSet.builder().add("stat.craftItem.minecraft.spawn_egg").add("stat.useItem.minecraft.spawn_egg").add("stat.breakItem.minecraft.spawn_egg").add("stat.pickup.minecraft.spawn_egg").add("stat.drop.minecraft.spawn_egg").build(); private static final Map<String, String> b = ImmutableMap.builder().put("stat.leaveGame", "minecraft:leave_game").put("stat.playOneMinute", "minecraft:play_one_minute").put("stat.timeSinceDeath", "minecraft:time_since_death").put("stat.sneakTime", "minecraft:sneak_time").put("stat.walkOneCm", "minecraft:walk_one_cm").put("stat.crouchOneCm", "minecraft:crouch_one_cm").put("stat.sprintOneCm", "minecraft:sprint_one_cm").put("stat.swimOneCm", "minecraft:swim_one_cm").put("stat.fallOneCm", "minecraft:fall_one_cm").put("stat.climbOneCm", "minecraft:climb_one_cm").put("stat.flyOneCm", "minecraft:fly_one_cm").put("stat.diveOneCm", "minecraft:dive_one_cm").put("stat.minecartOneCm", "minecraft:minecart_one_cm").put("stat.boatOneCm", "minecraft:boat_one_cm").put("stat.pigOneCm", "minecraft:pig_one_cm").put("stat.horseOneCm", "minecraft:horse_one_cm").put("stat.aviateOneCm", "minecraft:aviate_one_cm").put("stat.jump", "minecraft:jump").put("stat.drop", "minecraft:drop").put("stat.damageDealt", "minecraft:damage_dealt").put("stat.damageTaken", "minecraft:damage_taken").put("stat.deaths", "minecraft:deaths").put("stat.mobKills", "minecraft:mob_kills").put("stat.animalsBred", "minecraft:animals_bred").put("stat.playerKills", "minecraft:player_kills").put("stat.fishCaught", "minecraft:fish_caught").put("stat.talkedToVillager", "minecraft:talked_to_villager").put("stat.tradedWithVillager", "minecraft:traded_with_villager").put("stat.cakeSlicesEaten", "minecraft:eat_cake_slice").put("stat.cauldronFilled", "minecraft:fill_cauldron").put("stat.cauldronUsed", "minecraft:use_cauldron").put("stat.armorCleaned", "minecraft:clean_armor").put("stat.bannerCleaned", "minecraft:clean_banner").put("stat.brewingstandInteraction", "minecraft:interact_with_brewingstand").put("stat.beaconInteraction", "minecraft:interact_with_beacon").put("stat.dropperInspected", "minecraft:inspect_dropper").put("stat.hopperInspected", "minecraft:inspect_hopper").put("stat.dispenserInspected", "minecraft:inspect_dispenser").put("stat.noteblockPlayed", "minecraft:play_noteblock").put("stat.noteblockTuned", "minecraft:tune_noteblock").put("stat.flowerPotted", "minecraft:pot_flower").put("stat.trappedChestTriggered", "minecraft:trigger_trapped_chest").put("stat.enderchestOpened", "minecraft:open_enderchest").put("stat.itemEnchanted", "minecraft:enchant_item").put("stat.recordPlayed", "minecraft:play_record").put("stat.furnaceInteraction", "minecraft:interact_with_furnace").put("stat.craftingTableInteraction", "minecraft:interact_with_crafting_table").put("stat.chestOpened", "minecraft:open_chest").put("stat.sleepInBed", "minecraft:sleep_in_bed").put("stat.shulkerBoxOpened", "minecraft:open_shulker_box").build(); private static final Map<String, String> c = ImmutableMap.builder().put("stat.craftItem", "minecraft:crafted").put("stat.useItem", "minecraft:used").put("stat.breakItem", "minecraft:broken").put("stat.pickup", "minecraft:picked_up").put("stat.drop", "minecraft:dropped").build(); private static final Map<String, String> d = ImmutableMap.builder().put("stat.entityKilledBy", "minecraft:killed_by").put("stat.killEntity", "minecraft:killed").build(); private static final Map<String, String> e = ImmutableMap.builder().put("Bat", "minecraft:bat").put("Blaze", "minecraft:blaze").put("CaveSpider", "minecraft:cave_spider").put("Chicken", "minecraft:chicken").put("Cow", "minecraft:cow").put("Creeper", "minecraft:creeper").put("Donkey", "minecraft:donkey").put("ElderGuardian", "minecraft:elder_guardian").put("Enderman", "minecraft:enderman").put("Endermite", "minecraft:endermite").put("EvocationIllager", "minecraft:evocation_illager").put("Ghast", "minecraft:ghast").put("Guardian", "minecraft:guardian").put("Horse", "minecraft:horse").put("Husk", "minecraft:husk").put("Llama", "minecraft:llama").put("LavaSlime", "minecraft:magma_cube").put("MushroomCow", "minecraft:mooshroom").put("Mule", "minecraft:mule").put("Ozelot", "minecraft:ocelot").put("Parrot", "minecraft:parrot").put("Pig", "minecraft:pig").put("PolarBear", "minecraft:polar_bear").put("Rabbit", "minecraft:rabbit").put("Sheep", "minecraft:sheep").put("Shulker", "minecraft:shulker").put("Silverfish", "minecraft:silverfish").put("SkeletonHorse", "minecraft:skeleton_horse").put("Skeleton", "minecraft:skeleton").put("Slime", "minecraft:slime").put("Spider", "minecraft:spider").put("Squid", "minecraft:squid").put("Stray", "minecraft:stray").put("Vex", "minecraft:vex").put("Villager", "minecraft:villager").put("VindicationIllager", "minecraft:vindication_illager").put("Witch", "minecraft:witch").put("WitherSkeleton", "minecraft:wither_skeleton").put("Wolf", "minecraft:wolf").put("ZombieHorse", "minecraft:zombie_horse").put("PigZombie", "minecraft:zombie_pigman").put("ZombieVillager", "minecraft:zombie_villager").put("Zombie", "minecraft:zombie").build(); public DataConverterStatistic(Schema schema, boolean flag) { super(schema, flag); } public TypeRewriteRule makeRule() { Type<?> type = this.getOutputSchema().getType(DataConverterTypes.STATS); return this.fixTypeEverywhereTyped("StatsCounterFix", this.getInputSchema().getType(DataConverterTypes.STATS), type, (typed) -> { Dynamic<?> dynamic = (Dynamic) typed.get(DSL.remainderFinder()); Map<Dynamic<?>, Dynamic<?>> map = Maps.newHashMap(); Optional<? extends Map<? extends Dynamic<?>, ? extends Dynamic<?>>> optional = dynamic.getMapValues().result(); if (optional.isPresent()) { Iterator iterator = ((Map) optional.get()).entrySet().iterator(); while (iterator.hasNext()) { Entry<? extends Dynamic<?>, ? extends Dynamic<?>> entry = (Entry) iterator.next(); if (((Dynamic) entry.getValue()).asNumber().result().isPresent()) { String s = ((Dynamic) entry.getKey()).asString(""); if (!DataConverterStatistic.a.contains(s)) { String s1; String s2; if (DataConverterStatistic.b.containsKey(s)) { s1 = "minecraft:custom"; s2 = (String) DataConverterStatistic.b.get(s); } else { int i = StringUtils.ordinalIndexOf(s, ".", 2); if (i < 0) { continue; } String s3 = s.substring(0, i); if ("stat.mineBlock".equals(s3)) { s1 = "minecraft:mined"; s2 = this.b(s.substring(i + 1).replace('.', ':')); } else { String s4; if (DataConverterStatistic.c.containsKey(s3)) { s1 = (String) DataConverterStatistic.c.get(s3); s4 = s.substring(i + 1).replace('.', ':'); String s5 = this.a(s4); s2 = s5 == null ? s4 : s5; } else { if (!DataConverterStatistic.d.containsKey(s3)) { continue; } s1 = (String) DataConverterStatistic.d.get(s3); s4 = s.substring(i + 1).replace('.', ':'); s2 = (String) DataConverterStatistic.e.getOrDefault(s4, s4); } } } Dynamic<?> dynamic1 = dynamic.createString(s1); Dynamic<?> dynamic2 = (Dynamic) map.computeIfAbsent(dynamic1, (dynamic3) -> { return dynamic.emptyMap(); }); map.put(dynamic1, dynamic2.set(s2, (Dynamic) entry.getValue())); } } } } return (Typed) ((Pair) type.readTyped(dynamic.emptyMap().set("stats", dynamic.createMap(map))).result().orElseThrow(() -> { return new IllegalStateException("Could not parse new stats object."); })).getFirst(); }); } @Nullable protected String a(String s) { return DataConverterFlatten.a(s, 0); } protected String b(String s) { return DataConverterFlattenData.a(s); } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * 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.kie.smoke.wb.selenium.model.persps; import org.kie.smoke.wb.selenium.util.Waits; import org.openqa.selenium.By; public class ArtifactRepositoryPerspective extends AbstractPerspective { private static final By NAME_COLUMN_HEADER = By.xpath("//th[contains(text(),'Name')]"); @Override public boolean isDisplayed() { return Waits.isElementPresent(driver, NAME_COLUMN_HEADER); } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.live.v20180801.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeLiveDomainResponse extends AbstractModel{ /** * 域名信息。 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("DomainInfo") @Expose private DomainInfo DomainInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 域名信息。 注意:此字段可能返回 null,表示取不到有效值。 * @return DomainInfo 域名信息。 注意:此字段可能返回 null,表示取不到有效值。 */ public DomainInfo getDomainInfo() { return this.DomainInfo; } /** * Set 域名信息。 注意:此字段可能返回 null,表示取不到有效值。 * @param DomainInfo 域名信息。 注意:此字段可能返回 null,表示取不到有效值。 */ public void setDomainInfo(DomainInfo DomainInfo) { this.DomainInfo = DomainInfo; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamObj(map, prefix + "DomainInfo.", this.DomainInfo); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
package com.evan.my.shop.web.admin.abstracts; import com.evan.my.shop.commons.dto.BaseResult; import com.evan.my.shop.commons.persistence.BaseTreeEntity; import com.evan.my.shop.commons.persistence.BaseTreeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; public abstract class AbstractBaseTreeController<T extends BaseTreeEntity, S extends BaseTreeService<T>> { @Autowired protected S service; /** * 跳转列表页 * * @param model {@link Model} * @return */ public abstract String list(Model model); /** * 跳转表单页 * * @return */ public abstract String form(T entity); /** * 保存 * * @param entity {@link T} * @param model {@link int} * @param redirectAttributes {@link RedirectAttributes} * @return */ public abstract String save(T entity, Model model, RedirectAttributes redirectAttributes); /** * 删除 * @param ids {@link String} * @return */ public abstract BaseResult delete(String ids); /** * 树形结构 * * @param id {@link Long} * @return */ public abstract List<T> treeData(Long id); /** * 排序 * * @param sourceList 数据源集合 * @param targetList 排序后的集合 * @param parentId 父节点的 ID */ protected void sortList(List<T> sourceList, List<T> targetList, Long parentId) { for (T sourceEntity : sourceList) { if (sourceEntity.getParent().getId().equals(parentId)) { targetList.add(sourceEntity); // 判断有没有子节点,如果有则继续追加 if (sourceEntity.getIsParent()) { for (T currentEntity : sourceList) { if (currentEntity.getParent().getId().equals(sourceEntity.getId())) { sortList(sourceList, targetList, sourceEntity.getId()); break; } } } } } } }