gt
stringclasses
1 value
context
stringlengths
2.05k
161k
//===================================================================== // //File: $RCSfile: CanvasEditorReloadContentsTest.java,v $ //Version: $Revision: 1.15 $ //Modified: $Date: 2013/05/10 05:41:50 $ // //(c) Copyright 2004-2014 by Mentor Graphics Corp. 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.xtuml.bp.ui.canvas.test; import java.io.IOException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFileState; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.xtuml.bp.core.CorePlugin; import org.xtuml.bp.core.InstanceStateMachine_c; import org.xtuml.bp.core.ModelClass_c; import org.xtuml.bp.core.Ooaofooa; import org.xtuml.bp.core.Package_c; import org.xtuml.bp.core.StateMachineState_c; import org.xtuml.bp.core.StateMachine_c; import org.xtuml.bp.core.common.ClassQueryInterface_c; import org.xtuml.bp.core.common.NonRootModelElement; import org.xtuml.bp.test.common.BaseTest; import org.xtuml.bp.test.common.CanvasTestUtils; import org.xtuml.bp.test.common.OrderedRunner; import org.xtuml.bp.test.common.UITestingUtilities; import org.xtuml.bp.ui.canvas.GraphicalElement_c; import org.xtuml.bp.ui.canvas.Model_c; import org.xtuml.bp.ui.canvas.Ooaofgraphics; import org.xtuml.bp.ui.canvas.Shape_c; import org.xtuml.bp.ui.graphics.editor.GraphicalEditor; import junit.framework.TestCase; /** * Performs tests related to the updating of an editor's * contents when a model is reloaded from disk. */ @RunWith(OrderedRunner.class) public class CanvasEditorReloadContentsTest extends CanvasTest { /** * The name of the test domain used during these tests. */ private static final String testModelName = "odms"; /** * Constructor. */ public CanvasEditorReloadContentsTest() { super(null, null); } /* (non-Javadoc) * @see org.xtuml.bp.ui.canvas.test.CanvasTest#getResultName() */ protected String getResultName() { return null; } @Override @Before public void setUp() throws Exception { super.setUp(); Ooaofooa.setPersistEnabled(true); } @After public void tearDown() throws Exception { super.tearDown(); Ooaofooa.setPersistEnabled(false); } /** * For issue 780. Drags a shape on a domain diagram, then copies * over the domain's changed file with the original version, * checking to see that the shape reverts to its original position * due to the domain being reloaded. * @throws IOException * @throws CoreException */ @Test public void testEditorUpdatesOnReload() throws CoreException, IOException { // make sure the user isn't prompted to do a parse all CorePlugin.enableParseAllOnResourceChange(); // setup the test project and model loadProject(testModelName); BaseTest.dispatchEvents(0); // find a subsystem's shape that is in the canvas Package_c subsystem = Package_c.PackageInstance(modelRoot, new ClassQueryInterface_c() { @Override public boolean evaluate(Object candidate) { return ((Package_c) candidate).getName().equals("Odms"); } }); // open an editor on the test domain GraphicalEditor editor = UITestingUtilities.getGraphicalEditorFor(subsystem, false); Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(modelRoot.getId()); GraphicalElement_c element = CanvasTestUtils.getGraphicalElement(graphicsRoot, subsystem); Shape_c shape = Shape_c.getOneGD_SHPOnR2(element); UITestingUtilities.addElementToGraphicalSelection(subsystem); // drag the subsystem's shape a bit, then let go to get the // change persisted Model_c canvas = editor.getModel(); Point oldCenter = CanvasTestUtils.getShapeCenter(shape); Point mouse = CanvasTestUtils.convertToMouseCoor(oldCenter, canvas); CanvasTestUtils.createMouseEvent( mouse.x, mouse.y, "MouseDown"); int dx = 30, dy = 30; CanvasTestUtils.createMouseEvent( mouse.x + dx, mouse.y + dy, "MouseMove"); CanvasTestUtils.createMouseEvent( mouse.x + dx, mouse.y + dy, "MouseUp"); Point draggedCenter = CanvasTestUtils.getShapeCenter(shape); draggedCenter = CanvasTestUtils.convertToMouseCoor(draggedCenter, canvas); assertTrue("Drag had no effect", !draggedCenter.equals(oldCenter)); BaseTest.dispatchEvents(0); // restore from local history IFile file = ((NonRootModelElement) Model_c.getOneGD_MDOnR1(element).getRepresents()).getFile(); IFileState[] history = file.getHistory(new NullProgressMonitor()); if (history.length > 0) { file.setContents(history[0], IFile.FORCE, new NullProgressMonitor()); } // find the same subsystem's shape (once again) that // is presumably in the editor's new canvas (as the shape // would not be created if there were not also a new canvas // created) subsystem = Package_c.PackageInstance(modelRoot, new ClassQueryInterface_c() { @Override public boolean evaluate(Object candidate) { return ((Package_c) candidate).getName().equals("Odms"); } }); element = CanvasTestUtils.getGraphicalElement(graphicsRoot, subsystem); shape = Shape_c.getOneGD_SHPOnR2(element); assertNotNull("No new shape (and therefore, canvas) after reload", shape); // check that the shape reverted to its original position // due to the reload Point finalCenter = CanvasTestUtils.getShapeCenter(shape); assertTrue("Shape position did not revert after reload", finalCenter.equals(oldCenter)); } /** * For issue MFP issue 54. If the data for a state machine changes, * make sure the canvas editor doesn't close. * @throws IOException * @throws CoreException */ @Test public void testISMEditorStaysOpenOnReload() throws CoreException, IOException { // setup the test project and model loadProject(testModelName); // open an editor on the test domain ModelClass_c mc = ModelClass_c.ModelClassInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { if (((ModelClass_c) candidate).getName().equals("Disk")) return true; else return false; } } ); InstanceStateMachine_c uut = InstanceStateMachine_c.getOneSM_ISMOnR518(mc); TestCase.assertNotNull(uut); CanvasTestUtils.openCanvasEditor(uut); BaseTest.dispatchEvents(0); GraphicalEditor editor = CanvasTestUtils.getCanvasEditor("Disk"); BaseTest.dispatchEvents(0); // find a state's shape that is in the canvas StateMachineState_c state = StateMachineState_c.getOneSM_STATEOnR501( StateMachine_c.getOneSM_SMOnR517(uut)); moveShapeInEditor(editor, state); // replace the ISM file with previous from local history IFileState[] fh = state.getFile().getHistory(null); state.getFile().setContents(fh[0], true, true, null); BaseTest.dispatchEvents(0); // verify that the canvas editor is still open GraphicalEditor afterEditor = CanvasTestUtils.getCanvasEditor("Disk"); assertNotNull("Editor closed by file reload", afterEditor); } /** * Move the shape that represents me in the editor * * @param editor * @param me * @return the center of the shape before the move */ private Point moveShapeInEditor(GraphicalEditor editor, NonRootModelElement me) { editor.zoomAll(); BaseTest.dispatchEvents(0); Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(modelRoot.getId()); GraphicalElement_c element = CanvasTestUtils.getGraphicalElement(graphicsRoot, me); Shape_c shape = Shape_c.getOneGD_SHPOnR2(element); // drag the state's shape a bit, then let go to get the // change persisted Model_c canvas = editor.getModel(); Point oldCenter = CanvasTestUtils.getShapeCenter(shape); Point mouse = CanvasTestUtils.convertToMouseCoor(oldCenter, canvas); CanvasTestUtils.createMouseEvent( mouse.x, mouse.y, "MouseDown"); int dx = 20, dy = 20; CanvasTestUtils.createMouseEvent( mouse.x + dx, mouse.y + dy, "MouseMove"); CanvasTestUtils.createMouseEvent( mouse.x + dx, mouse.y + dy, "MouseUp"); BaseTest.dispatchEvents(0); Point draggedCenter = CanvasTestUtils.getShapeCenter(shape); assertTrue("Drag had no effect", !draggedCenter.equals(oldCenter)); return oldCenter; } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.refactoring.extractmethod; import com.intellij.codeInsight.CodeInsightUtilCore; import com.intellij.codeInsight.codeFragment.CodeFragment; import com.intellij.lang.LanguageNamesValidation; import com.intellij.lang.refactoring.NamesValidator; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.extractMethod.*; import com.intellij.refactoring.listeners.RefactoringElementListenerComposite; import com.intellij.refactoring.listeners.RefactoringEventData; import com.intellij.refactoring.listeners.RefactoringEventListener; import com.intellij.refactoring.rename.RenameUtil; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.usageView.UsageInfo; import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.hash.HashMap; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.codeInsight.codeFragment.PyCodeFragment; import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.Scope; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyFunctionBuilder; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.refactoring.PyReplaceExpressionUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author oleg */ public class PyExtractMethodUtil { public static final String NAME = "extract.method.name"; private PyExtractMethodUtil() { } public static void extractFromStatements(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PyCodeFragment fragment, @NotNull final PsiElement statement1, @NotNull final PsiElement statement2) { if (!fragment.getOutputVariables().isEmpty() && fragment.isReturnInstructionInside()) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.extract.method.error.local.variable.modifications.and.returns"), RefactoringBundle.message("error.title"), "refactoring.extractMethod"); return; } final PyFunction function = PsiTreeUtil.getParentOfType(statement1, PyFunction.class); final PyUtil.MethodFlags flags = function == null ? null : PyUtil.MethodFlags.of(function); final boolean isClassMethod = flags != null && flags.isClassMethod(); final boolean isStaticMethod = flags != null && flags.isStaticMethod(); // collect statements final List<PsiElement> elementsRange = PyPsiUtils.collectElements(statement1, statement2); if (elementsRange.isEmpty()) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.extract.method.error.empty.fragment"), RefactoringBundle.message("extract.method.title"), "refactoring.extractMethod"); return; } final Pair<String, AbstractVariableData[]> data = getNameAndVariableData(project, fragment, statement1, isClassMethod, isStaticMethod); if (data.first == null || data.second == null) { return; } final String methodName = data.first; final AbstractVariableData[] variableData = data.second; final SimpleDuplicatesFinder finder = new SimpleDuplicatesFinder(statement1, statement2, variableData, fragment.getOutputVariables()); CommandProcessor.getInstance().executeCommand(project, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { final RefactoringEventData beforeData = new RefactoringEventData(); beforeData.addElements(new PsiElement[]{statement1, statement2}); project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringStarted(getRefactoringId(), beforeData); final StringBuilder builder = new StringBuilder(); final boolean isAsync = fragment.isAsync(); if (isAsync) { builder.append("async "); } builder.append("def f():\n "); final List<PsiElement> newMethodElements = new ArrayList<PsiElement>(elementsRange); final boolean hasOutputVariables = !fragment.getOutputVariables().isEmpty(); final PyElementGenerator generator = PyElementGenerator.getInstance(project); final LanguageLevel languageLevel = LanguageLevel.forElement(statement1); if (hasOutputVariables) { // Generate return modified variables statements final String outputVariables = StringUtil.join(fragment.getOutputVariables(), ", "); String newMethodText = builder + "return " + outputVariables; builder.append(outputVariables); final PyFunction function = generator.createFromText(languageLevel, PyFunction.class, newMethodText); final PsiElement returnStatement = function.getStatementList().getStatements()[0]; newMethodElements.add(returnStatement); } // Generate method PyFunction generatedMethod = generateMethodFromElements(project, methodName, variableData, newMethodElements, flags, isAsync); generatedMethod = insertGeneratedMethod(statement1, generatedMethod); // Process parameters final PsiElement firstElement = elementsRange.get(0); final boolean isMethod = PyPsiUtils.isMethodContext(firstElement); processParameters(project, generatedMethod, variableData, isMethod, isClassMethod, isStaticMethod); processGlobalWrites(generatedMethod, fragment); processNonlocalWrites(generatedMethod, fragment); // Generate call element if (hasOutputVariables) { builder.append(" = "); } else if (fragment.isReturnInstructionInside()) { builder.append("return "); } if (isAsync) { builder.append("await "); } else if (fragment.isYieldInside()) { builder.append("yield from "); } if (isMethod) { appendSelf(firstElement, builder, isStaticMethod); } builder.append(methodName).append("("); builder.append(createCallArgsString(variableData)).append(")"); final PyFunction function = generator.createFromText(languageLevel, PyFunction.class, builder.toString()); PsiElement callElement = function.getStatementList().getStatements()[0]; // replace statements with call callElement = replaceElements(elementsRange, callElement); callElement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(callElement); if (callElement != null) { processDuplicates(callElement, generatedMethod, finder, editor); } // Set editor setSelectionAndCaret(editor, callElement); final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(generatedMethod); project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringDone(getRefactoringId(), afterData); } }); } }, PyBundle.message("refactoring.extract.method"), null); } private static void processDuplicates(@NotNull final PsiElement callElement, @NotNull final PyFunction generatedMethod, @NotNull final SimpleDuplicatesFinder finder, @NotNull final Editor editor) { final ScopeOwner owner = ScopeUtil.getScopeOwner(callElement); if (owner instanceof PsiFile) return; final List<PsiElement> scope = new ArrayList<PsiElement>(); if (owner instanceof PyFunction) { scope.add(owner); final PyClass containingClass = ((PyFunction)owner).getContainingClass(); if (containingClass != null) { for (PyFunction function : containingClass.getMethods(false)) { if (!function.equals(owner) && !function.equals(generatedMethod)) { scope.add(function); } } } } ExtractMethodHelper.processDuplicates(callElement, generatedMethod, scope, finder, editor, new Consumer<Pair<SimpleMatch, PsiElement>>() { @Override public void consume(@NotNull Pair<SimpleMatch, PsiElement> pair) { replaceElements(pair.first, pair.second.copy()); } } ); } private static void processGlobalWrites(@NotNull final PyFunction function, @NotNull final PyCodeFragment fragment) { final Set<String> globalWrites = fragment.getGlobalWrites(); final Set<String> newGlobalNames = new LinkedHashSet<String>(); final Scope scope = ControlFlowCache.getScope(function); for (String name : globalWrites) { if (!scope.isGlobal(name)) { newGlobalNames.add(name); } } if (!newGlobalNames.isEmpty()) { final PyElementGenerator generator = PyElementGenerator.getInstance(function.getProject()); final PyGlobalStatement globalStatement = generator.createFromText(LanguageLevel.forElement(function), PyGlobalStatement.class, "global " + StringUtil.join(newGlobalNames, ", ")); final PyStatementList statementList = function.getStatementList(); statementList.addBefore(globalStatement, statementList.getFirstChild()); } } private static void processNonlocalWrites(@NotNull PyFunction function, @NotNull PyCodeFragment fragment) { final Set<String> nonlocalWrites = fragment.getNonlocalWrites(); final Set<String> newNonlocalNames = new LinkedHashSet<String>(); final Scope scope = ControlFlowCache.getScope(function); for (String name : nonlocalWrites) { if (!scope.isNonlocal(name)) { newNonlocalNames.add(name); } } if (!newNonlocalNames.isEmpty()) { final PyElementGenerator generator = PyElementGenerator.getInstance(function.getProject()); final PyNonlocalStatement nonlocalStatement = generator.createFromText(LanguageLevel.forElement(function), PyNonlocalStatement.class, "nonlocal " + StringUtil.join(newNonlocalNames, ", ")); final PyStatementList statementList = function.getStatementList(); statementList.addBefore(nonlocalStatement, statementList.getFirstChild()); } } private static void appendSelf(@NotNull PsiElement firstElement, @NotNull StringBuilder builder, boolean staticMethod) { if (staticMethod) { final PyClass containingClass = PsiTreeUtil.getParentOfType(firstElement, PyClass.class); assert containingClass != null; builder.append(containingClass.getName()); } else { builder.append(PyUtil.getFirstParameterName(PsiTreeUtil.getParentOfType(firstElement, PyFunction.class))); } builder.append("."); } public static void extractFromExpression(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PyCodeFragment fragment, @NotNull final PsiElement expression) { if (!fragment.getOutputVariables().isEmpty()) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.extract.method.error.local.variable.modifications"), RefactoringBundle.message("error.title"), "refactoring.extractMethod"); return; } if (fragment.isReturnInstructionInside()) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.extract.method.error.returns"), RefactoringBundle.message("error.title"), "refactoring.extractMethod"); return; } final PyFunction function = PsiTreeUtil.getParentOfType(expression, PyFunction.class); final PyUtil.MethodFlags flags = function == null ? null : PyUtil.MethodFlags.of(function); final boolean isClassMethod = flags != null && flags.isClassMethod(); final boolean isStaticMethod = flags != null && flags.isClassMethod(); final Pair<String, AbstractVariableData[]> data = getNameAndVariableData(project, fragment, expression, isClassMethod, isStaticMethod); if (data.first == null || data.second == null) { return; } final String methodName = data.first; final AbstractVariableData[] variableData = data.second; final SimpleDuplicatesFinder finder = new SimpleDuplicatesFinder(expression, expression, variableData, fragment.getOutputVariables()); if (fragment.getOutputVariables().isEmpty()) { CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { // Generate method final boolean isAsync = fragment.isAsync(); PyFunction generatedMethod = generateMethodFromExpression(project, methodName, variableData, expression, flags, isAsync); generatedMethod = insertGeneratedMethod(expression, generatedMethod); // Process parameters final boolean isMethod = PyPsiUtils.isMethodContext(expression); processParameters(project, generatedMethod, variableData, isMethod, isClassMethod, isStaticMethod); // Generating call element final StringBuilder builder = new StringBuilder(); if (isAsync) { builder.append("async "); } builder.append("def f():\n "); if (isAsync) { builder.append("await "); } else if (fragment.isYieldInside()) { builder.append("yield from "); } else { builder.append("return "); } if (isMethod) { appendSelf(expression, builder, isStaticMethod); } builder.append(methodName); builder.append("(").append(createCallArgsString(variableData)).append(")"); final PyElementGenerator generator = PyElementGenerator.getInstance(project); final PyFunction function = generator.createFromText(LanguageLevel.forElement(expression), PyFunction.class, builder.toString()); final PyElement generated = function.getStatementList().getStatements()[0]; PsiElement callElement = null; if (generated instanceof PyReturnStatement) { callElement = ((PyReturnStatement)generated).getExpression(); } else if (generated instanceof PyExpressionStatement) { callElement = ((PyExpressionStatement)generated).getExpression(); } // replace statements with call if (callElement != null) { callElement = PyReplaceExpressionUtil.replaceExpression(expression, callElement); } if (callElement != null) { processDuplicates(callElement, generatedMethod, finder, editor); } // Set editor setSelectionAndCaret(editor, callElement); } }); } }, PyBundle.message("refactoring.extract.method"), null); } } private static void setSelectionAndCaret(@NotNull Editor editor, @Nullable final PsiElement callElement) { editor.getSelectionModel().removeSelection(); if (callElement != null) { final int offset = callElement.getTextOffset(); editor.getCaretModel().moveToOffset(offset); } } @NotNull private static PsiElement replaceElements(@NotNull final List<PsiElement> elementsRange, @NotNull PsiElement callElement) { callElement = elementsRange.get(0).replace(callElement); if (elementsRange.size() > 1) { callElement.getParent().deleteChildRange(elementsRange.get(1), elementsRange.get(elementsRange.size() - 1)); } return callElement; } @NotNull private static PsiElement replaceElements(@NotNull final SimpleMatch match, @NotNull final PsiElement element) { final List<PsiElement> elementsRange = PyPsiUtils.collectElements(match.getStartElement(), match.getEndElement()); final Map<String, String> changedParameters = match.getChangedParameters(); PsiElement callElement = element; final PyElementGenerator generator = PyElementGenerator.getInstance(callElement.getProject()); if (element instanceof PyAssignmentStatement) { final PyExpression value = ((PyAssignmentStatement)element).getAssignedValue(); if (value != null) callElement = value; final PyExpression[] targets = ((PyAssignmentStatement)element).getTargets(); if (targets.length == 1) { final String output = match.getChangedOutput(); final PyExpression text = generator.createFromText(LanguageLevel.forElement(callElement), PyAssignmentStatement.class, output + " = 1").getTargets()[0]; targets[0].replace(text); } } if (element instanceof PyExpressionStatement) { callElement = ((PyExpressionStatement)element).getExpression(); } if (callElement instanceof PyCallExpression) { final Set<String> keys = changedParameters.keySet(); final PyArgumentList argumentList = ((PyCallExpression)callElement).getArgumentList(); if (argumentList != null) { for (PyExpression arg : argumentList.getArguments()) { final String argText = arg.getText(); if (argText != null && keys.contains(argText)) { arg.replace(generator.createExpressionFromText( LanguageLevel.forElement(callElement), changedParameters.get(argText))); } } } } return replaceElements(elementsRange, element); } // Creates string for call @NotNull private static String createCallArgsString(@NotNull final AbstractVariableData[] variableDatas) { return StringUtil.join(ContainerUtil.mapNotNull(variableDatas, new Function<AbstractVariableData, String>() { @Override public String fun(AbstractVariableData data) { return data.isPassAsParameter() ? data.getOriginalName() : null; } }), ","); } private static void processParameters(@NotNull final Project project, @NotNull final PyFunction generatedMethod, @NotNull final AbstractVariableData[] variableData, final boolean isMethod, final boolean isClassMethod, final boolean isStaticMethod) { final Map<String, String> map = createMap(variableData); // Rename parameters for (PyParameter parameter : generatedMethod.getParameterList().getParameters()) { final String name = parameter.getName(); final String newName = map.get(name); if (name != null && newName != null && !name.equals(newName)) { final Map<PsiElement, String> allRenames = new java.util.HashMap<PsiElement, String>(); allRenames.put(parameter, newName); final UsageInfo[] usages = RenameUtil.findUsages(parameter, newName, false, false, allRenames); try { RenameUtil.doRename(parameter, newName, usages, project, new RefactoringElementListenerComposite()); } catch (IncorrectOperationException e) { RenameUtil.showErrorMessage(e, parameter, project); return; } } } // Change signature according to pass settings and final PyFunctionBuilder builder = new PyFunctionBuilder("foo"); if (isClassMethod) { builder.parameter("cls"); } else if (isMethod && !isStaticMethod) { builder.parameter("self"); } for (AbstractVariableData data : variableData) { if (data.isPassAsParameter()) { builder.parameter(data.getName()); } } final PyParameterList pyParameterList = builder.buildFunction(project, LanguageLevel.forElement(generatedMethod)).getParameterList(); generatedMethod.getParameterList().replace(pyParameterList); } @NotNull private static Map<String, String> createMap(@NotNull final AbstractVariableData[] variableData) { final Map<String, String> map = new HashMap<String, String>(); for (AbstractVariableData data : variableData) { map.put(data.getOriginalName(), data.getName()); } return map; } @NotNull private static PyFunction insertGeneratedMethod(@NotNull PsiElement anchor, @NotNull final PyFunction generatedMethod) { final Pair<PsiElement, TextRange> data = anchor.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE); if (data != null) { anchor = data.first; } final PsiNamedElement parent = PsiTreeUtil.getParentOfType(anchor, PyFile.class, PyClass.class, PyFunction.class); final PsiElement result; // The only safe case to insert extracted function *after* original scope owner is function. if (parent instanceof PyFunction) { result = parent.getParent().addAfter(generatedMethod, parent); } else { final PsiElement target = parent instanceof PyClass ? ((PyClass)parent).getStatementList() : parent; final PsiElement insertionAnchor = PyPsiUtils.getParentRightBefore(anchor, target); assert insertionAnchor != null; final Couple<PsiComment> comments = PyPsiUtils.getPrecedingComments(insertionAnchor); result = insertionAnchor.getParent().addBefore(generatedMethod, comments != null ? comments.getFirst() : insertionAnchor); } // to ensure correct reformatting, mark the entire method as generated result.accept(new PsiRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { super.visitElement(element); CodeEditUtil.setNodeGenerated(element.getNode(), true); } }); return (PyFunction)result; } @NotNull private static PyFunction generateMethodFromExpression(@NotNull final Project project, @NotNull final String methodName, @NotNull final AbstractVariableData[] variableData, @NotNull final PsiElement expression, @Nullable final PyUtil.MethodFlags flags, boolean isAsync) { final PyFunctionBuilder builder = new PyFunctionBuilder(methodName); addDecorators(builder, flags); addFakeParameters(builder, variableData); if (isAsync) { builder.makeAsync(); } final String text; if (expression instanceof PyYieldExpression) { text = String.format("(%s)", expression.getText()); } else { text = expression.getText(); } builder.statement("return " + text); return builder.buildFunction(project, LanguageLevel.forElement(expression)); } @NotNull private static PyFunction generateMethodFromElements(@NotNull final Project project, @NotNull final String methodName, @NotNull final AbstractVariableData[] variableData, @NotNull final List<PsiElement> elementsRange, @Nullable PyUtil.MethodFlags flags, boolean isAsync) { assert !elementsRange.isEmpty() : "Empty statements list was selected!"; final PyFunctionBuilder builder = new PyFunctionBuilder(methodName); if (isAsync) { builder.makeAsync(); } addDecorators(builder, flags); addFakeParameters(builder, variableData); final PyFunction method = builder.buildFunction(project, LanguageLevel.forElement(elementsRange.get(0))); final PyStatementList statementList = method.getStatementList(); for (PsiElement element : elementsRange) { if (element instanceof PsiWhiteSpace) { continue; } statementList.add(element); } // remove last instruction final PsiElement child = statementList.getFirstChild(); if (child != null) { child.delete(); } PsiElement last = statementList; while (last != null) { last = last.getLastChild(); if (last instanceof PsiWhiteSpace) { last.delete(); } } return method; } private static void addDecorators(@NotNull PyFunctionBuilder builder, @Nullable PyUtil.MethodFlags flags) { if (flags != null) { if (flags.isClassMethod()) { builder.decorate(PyNames.CLASSMETHOD); } else if (flags.isStaticMethod()) { builder.decorate(PyNames.STATICMETHOD); } } } private static void addFakeParameters(@NotNull PyFunctionBuilder builder, @NotNull AbstractVariableData[] variableData) { for (AbstractVariableData data : variableData) { builder.parameter(data.getOriginalName()); } } @NotNull private static Pair<String, AbstractVariableData[]> getNameAndVariableData(@NotNull final Project project, @NotNull final CodeFragment fragment, @NotNull final PsiElement element, final boolean isClassMethod, final boolean isStaticMethod) { final ExtractMethodValidator validator = new PyExtractMethodValidator(element, project); if (ApplicationManager.getApplication().isUnitTestMode()) { String name = System.getProperty(NAME); if (name == null) { name = "foo"; } final String error = validator.check(name); if (error != null) { if (ApplicationManager.getApplication().isUnitTestMode()) { throw new CommonRefactoringUtil.RefactoringErrorHintException(error); } if (Messages.showOkCancelDialog(error + ". " + RefactoringBundle.message("do.you.wish.to.continue"), RefactoringBundle.message("warning.title"), Messages.getWarningIcon()) != Messages.OK) { throw new CommonRefactoringUtil.RefactoringErrorHintException(error); } } final List<AbstractVariableData> data = new ArrayList<AbstractVariableData>(); for (String in : fragment.getInputVariables()) { final AbstractVariableData d = new AbstractVariableData(); d.name = in + "_new"; d.originalName = in; d.passAsParameter = true; data.add(d); } return Pair.create(name, data.toArray(new AbstractVariableData[data.size()])); } final boolean isMethod = PyPsiUtils.isMethodContext(element); final ExtractMethodDecorator decorator = new ExtractMethodDecorator() { @NotNull public String createMethodPreview(final String methodName, @NotNull final AbstractVariableData[] variableDatas) { final StringBuilder builder = new StringBuilder(); if (isClassMethod) { builder.append("cls"); } else if (isMethod && !isStaticMethod) { builder.append("self"); } for (AbstractVariableData variableData : variableDatas) { if (variableData.passAsParameter) { if (builder.length() != 0) { builder.append(", "); } builder.append(variableData.name); } } builder.insert(0, "("); builder.insert(0, methodName); builder.insert(0, "def "); builder.append(")"); return builder.toString(); } }; final AbstractExtractMethodDialog dialog = new AbstractExtractMethodDialog(project, "method_name", fragment, validator, decorator, PythonFileType.INSTANCE) { @Override protected String getHelpId() { return "python.reference.extractMethod"; } }; dialog.show(); //return if don`t want to extract method if (!dialog.isOK()) { return Pair.empty(); } return Pair.create(dialog.getMethodName(), dialog.getVariableData()); } @NotNull public static String getRefactoringId() { return "refactoring.python.extract.method"; } private static class PyExtractMethodValidator implements ExtractMethodValidator { private final PsiElement myElement; private final Project myProject; @Nullable private final Function<String, Boolean> myFunction; public PyExtractMethodValidator(final PsiElement element, final Project project) { myElement = element; myProject = project; final ScopeOwner parent = ScopeUtil.getScopeOwner(myElement); myFunction = new Function<String, Boolean>() { @NotNull @Override public Boolean fun(String s) { ScopeOwner owner = parent; while (owner != null) { if (owner instanceof PyClass) { if (((PyClass)owner).findMethodByName(s, true) != null) { return false; } } final Scope scope = ControlFlowCache.getScope(owner); if (scope.containsDeclaration(s)) { return false; } owner = ScopeUtil.getScopeOwner(owner); } return true; } }; } @Nullable public String check(final String name) { if (myFunction != null && !myFunction.fun(name)) { return PyBundle.message("refactoring.extract.method.error.name.clash"); } return null; } public boolean isValidName(@NotNull final String name) { final NamesValidator validator = LanguageNamesValidation.INSTANCE.forLanguage(PythonLanguage.getInstance()); assert validator != null; return validator.isIdentifier(name, myProject); } } }
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.config.materials; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.PipelineConfig; import com.thoughtworks.go.domain.MaterialRevision; import com.thoughtworks.go.domain.materials.MatchedRevision; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.domain.materials.Modifications; import com.thoughtworks.go.domain.materials.Revision; import com.thoughtworks.go.util.command.EnvironmentVariableContext; import com.thoughtworks.go.util.command.UrlArgument; import com.thoughtworks.go.util.json.JsonMap; import org.apache.commons.lang.StringUtils; import java.io.File; import java.util.Map; import static com.thoughtworks.go.util.command.EnvironmentVariableContext.escapeEnvironmentVariable; /** * @understands a source control repository and its configuration */ public abstract class ScmMaterial extends AbstractMaterial { public static final String GO_REVISION = "GO_REVISION"; public static final String GO_TO_REVISION = "GO_TO_REVISION"; public static final String GO_FROM_REVISION = "GO_FROM_REVISION"; protected Filter filter; protected String folder; protected boolean autoUpdate = true; public ScmMaterial(String typeName) { super(typeName); } @Override protected void appendPipelineUniqueCriteria(Map<String, Object> basicCriteria) { basicCriteria.put("dest", folder); } public File workingdir(File baseFolder) { if (getFolder() == null) { return baseFolder; } return new File(baseFolder, getFolder()); } protected String updatingTarget() { return StringUtils.isEmpty(getFolder()) ? "files" : getFolder(); } public void toJson(JsonMap json, Revision revision) { json.put("folder", getFolder()); json.put("scmType", getTypeForDisplay()); json.put("location", getLocation()); if (!CaseInsensitiveString.isBlank(getName())) { json.put("materialName", CaseInsensitiveString.str(getName())); } json.put("action", "Modified"); } //most of the material such as hg, git, p4 all print the file from the root without '/' //but subverion print it with '/', we standarize it here. look at the implementation of subversion as well. public boolean matches(String name, String regex) { if (regex.startsWith("/")) { regex = regex.substring(1); } return name.matches(regex); } public abstract String getUserName(); public abstract String getPassword(); public abstract String getEncryptedPassword(); public abstract boolean isCheckExternals(); public abstract String getUrl(); protected abstract UrlArgument getUrlArgument(); protected abstract String getLocation(); public void setFilter(Filter filter) { this.filter = filter; } public void emailContent(StringBuilder content, Modification modification) { content.append(getTypeForDisplay() + ": " + getLocation()).append('\n').append( String.format("revision: %s, modified by %s on %s", modification.getRevision(), modification.getUserName(), modification.getModifiedTime())) .append('\n') .append(modification.getComment()); } public String getDescription() { return getUriForDisplay(); } public String getUriForDisplay() { return getUrlArgument().forDisplay(); } public void populateEnvironmentContext(EnvironmentVariableContext environmentVariableContext, MaterialRevision materialRevision, File workingDir) { String toRevision = materialRevision.getRevision().getRevision(); String fromRevision = materialRevision.getOldestRevision().getRevision(); setGoRevisionVariables(environmentVariableContext, fromRevision, toRevision); } private void setGoRevisionVariables(EnvironmentVariableContext environmentVariableContext, String fromRevision, String toRevision) { setVariableWithName(environmentVariableContext, toRevision, GO_REVISION); setVariableWithName(environmentVariableContext, toRevision, GO_TO_REVISION); setVariableWithName(environmentVariableContext, fromRevision, GO_FROM_REVISION); } protected void setVariableWithName(EnvironmentVariableContext environmentVariableContext, String value, String propertyName) { if (!CaseInsensitiveString.isBlank(this.name)) { environmentVariableContext.setProperty(propertyName + "_" + escapeEnvironmentVariable(this.name.toUpper()), value, false); return; } String scrubbedFolder = escapeEnvironmentVariable(folder); if (!StringUtils.isEmpty(scrubbedFolder)) { environmentVariableContext.setProperty(propertyName + "_" + scrubbedFolder, value, false); } else { environmentVariableContext.setProperty(propertyName, value, false); } } public String getFolder() { return folder; } public String getDisplayName() { return name == null ? getUriForDisplay() : CaseInsensitiveString.str(name); } public boolean isAutoUpdate() { return autoUpdate; } public boolean getAutoUpdate() { return autoUpdate; } public void setAutoUpdate(boolean value) { autoUpdate = value; } public final MatchedRevision createMatchedRevision(Modification modification, String searchString) { return new MatchedRevision(searchString, getShortRevision(modification.getRevision()), modification.getRevision(), modification.getUserName(), modification.getModifiedTime(), modification.getComment()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ScmMaterial that = (ScmMaterial) o; if (folder != null ? !folder.equals(that.folder) : that.folder != null) { return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (folder != null ? folder.hashCode() : 0); return result; } public static String changesetUrl(Modification modification, String baseUrl, final long id) { return baseUrl + "/api/materials/" + id + "/changeset/" + modification.getRevision() + ".xml"; } public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) { return false; } // TODO: Consider renaming this to dest since we use that word in the UI & Config public void setFolder(String folder) { this.folder = folder; } public Revision oldestRevision(Modifications modifications) { return Modification.oldestRevision(modifications); } @Override public boolean supportsDestinationFolder() { return true; } }
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.web.client; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.springframework.beans.BeanUtils; import org.springframework.http.client.AbstractClientHttpRequestFactoryWrapper; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.support.BasicAuthorizationInterceptor; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplateHandler; /** * Builder that can be used to configure and create a {@link RestTemplate}. Provides * convenience methods to register {@link #messageConverters(HttpMessageConverter...) * converters}, {@link #errorHandler(ResponseErrorHandler) error handlers} and * {@link #uriTemplateHandler(UriTemplateHandler) UriTemplateHandlers}. * <p> * By default the built {@link RestTemplate} will attempt to use the most suitable * {@link ClientHttpRequestFactory}, call {@link #detectRequestFactory(boolean) * detectRequestFactory(false)} if you prefer to keep the default. In a typical * auto-configured Spring Boot application this builder is available as a bean and can be * injected whenever a {@link RestTemplate} is needed. * * @author Stephane Nicoll * @author Phillip Webb * @author Andy Wilkinson * @since 1.4.0 */ public class RestTemplateBuilder { private static final Map<String, String> REQUEST_FACTORY_CANDIDATES; static { Map<String, String> candidates = new LinkedHashMap<>(); candidates.put("org.apache.http.client.HttpClient", "org.springframework.http.client.HttpComponentsClientHttpRequestFactory"); candidates.put("okhttp3.OkHttpClient", "org.springframework.http.client.OkHttp3ClientHttpRequestFactory"); candidates.put("com.squareup.okhttp.OkHttpClient", "org.springframework.http.client.OkHttpClientHttpRequestFactory"); candidates.put("io.netty.channel.EventLoopGroup", "org.springframework.http.client.Netty4ClientHttpRequestFactory"); REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates); } private final boolean detectRequestFactory; private final String rootUri; private final Set<HttpMessageConverter<?>> messageConverters; private final ClientHttpRequestFactory requestFactory; private final UriTemplateHandler uriTemplateHandler; private final ResponseErrorHandler errorHandler; private final BasicAuthorizationInterceptor basicAuthorization; private final Set<RestTemplateCustomizer> restTemplateCustomizers; private final Set<RequestFactoryCustomizer> requestFactoryCustomizers; private final Set<ClientHttpRequestInterceptor> interceptors; /** * Create a new {@link RestTemplateBuilder} instance. * @param customizers any {@link RestTemplateCustomizer RestTemplateCustomizers} that * should be applied when the {@link RestTemplate} is built */ public RestTemplateBuilder(RestTemplateCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.detectRequestFactory = true; this.rootUri = null; this.messageConverters = null; this.requestFactory = null; this.uriTemplateHandler = null; this.errorHandler = null; this.basicAuthorization = null; this.restTemplateCustomizers = Collections .unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); this.requestFactoryCustomizers = Collections.<RequestFactoryCustomizer>emptySet(); this.interceptors = Collections.<ClientHttpRequestInterceptor>emptySet(); } private RestTemplateBuilder(boolean detectRequestFactory, String rootUri, Set<HttpMessageConverter<?>> messageConverters, ClientHttpRequestFactory requestFactory, UriTemplateHandler uriTemplateHandler, ResponseErrorHandler errorHandler, BasicAuthorizationInterceptor basicAuthorization, Set<RestTemplateCustomizer> restTemplateCustomizers, Set<RequestFactoryCustomizer> requestFactoryCustomizers, Set<ClientHttpRequestInterceptor> interceptors) { super(); this.detectRequestFactory = detectRequestFactory; this.rootUri = rootUri; this.messageConverters = messageConverters; this.requestFactory = requestFactory; this.uriTemplateHandler = uriTemplateHandler; this.errorHandler = errorHandler; this.basicAuthorization = basicAuthorization; this.restTemplateCustomizers = restTemplateCustomizers; this.requestFactoryCustomizers = requestFactoryCustomizers; this.interceptors = interceptors; } /** * Set if the {@link ClientHttpRequestFactory} should be detected based on the * classpath. Default if {@code true}. * @param detectRequestFactory if the {@link ClientHttpRequestFactory} should be * detected * @return a new builder instance */ public RestTemplateBuilder detectRequestFactory(boolean detectRequestFactory) { return new RestTemplateBuilder(detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set a root URL that should be applied to each request that starts with {@code '/'}. * See {@link RootUriTemplateHandler} for details. * @param rootUri the root URI or {@code null} * @return a new builder instance */ public RestTemplateBuilder rootUri(String rootUri) { return new RestTemplateBuilder(this.detectRequestFactory, rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set the {@link HttpMessageConverter HttpMessageConverters} that should be used with * the {@link RestTemplate}. Setting this value will replace any previously configured * converters. * @param messageConverters the converters to set * @return a new builder instance * @see #additionalMessageConverters(HttpMessageConverter...) */ public RestTemplateBuilder messageConverters( HttpMessageConverter<?>... messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return messageConverters(Arrays.asList(messageConverters)); } /** * Set the {@link HttpMessageConverter HttpMessageConverters} that should be used with * the {@link RestTemplate}. Setting this value will replace any previously configured * converters. * @param messageConverters the converters to set * @return a new builder instance * @see #additionalMessageConverters(HttpMessageConverter...) */ public RestTemplateBuilder messageConverters( Collection<? extends HttpMessageConverter<?>> messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, Collections.unmodifiableSet( new LinkedHashSet<HttpMessageConverter<?>>(messageConverters)), this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Add additional {@link HttpMessageConverter HttpMessageConverters} that should be * used with the {@link RestTemplate}. * @param messageConverters the converters to add * @return a new builder instance * @see #messageConverters(HttpMessageConverter...) */ public RestTemplateBuilder additionalMessageConverters( HttpMessageConverter<?>... messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return additionalMessageConverters(Arrays.asList(messageConverters)); } /** * Add additional {@link HttpMessageConverter HttpMessageConverters} that should be * used with the {@link RestTemplate}. * @param messageConverters the converters to add * @return a new builder instance * @see #messageConverters(HttpMessageConverter...) */ public RestTemplateBuilder additionalMessageConverters( Collection<? extends HttpMessageConverter<?>> messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, append(this.messageConverters, messageConverters), this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set the {@link HttpMessageConverter HttpMessageConverters} that should be used with * the {@link RestTemplate} to the default set. Calling this method will replace any * previously defined converters. * @return a new builder instance * @see #messageConverters(HttpMessageConverter...) */ public RestTemplateBuilder defaultMessageConverters() { return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, Collections.unmodifiableSet( new LinkedHashSet<>(new RestTemplate().getMessageConverters())), this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set the {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors} that * should be used with the {@link RestTemplate}. Setting this value will replace any * previously defined interceptors. * @param interceptors the interceptors to set * @return a new builder instance * @since 1.4.1 * @see #additionalInterceptors(ClientHttpRequestInterceptor...) */ public RestTemplateBuilder interceptors( ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return interceptors(Arrays.asList(interceptors)); } /** * Set the {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors} that * should be used with the {@link RestTemplate}. Setting this value will replace any * previously defined interceptors. * @param interceptors the interceptors to set * @return a new builder instance * @since 1.4.1 * @see #additionalInterceptors(ClientHttpRequestInterceptor...) */ public RestTemplateBuilder interceptors( Collection<ClientHttpRequestInterceptor> interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, Collections.unmodifiableSet(new LinkedHashSet<>(interceptors))); } /** * Add additional {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors} * that should be used with the {@link RestTemplate}. * @param interceptors the interceptors to add * @return a new builder instance * @since 1.4.1 * @see #interceptors(ClientHttpRequestInterceptor...) */ public RestTemplateBuilder additionalInterceptors( ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return additionalInterceptors(Arrays.asList(interceptors)); } /** * Add additional {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors} * that should be used with the {@link RestTemplate}. * @param interceptors the interceptors to add * @return a new builder instance * @since 1.4.1 * @see #interceptors(ClientHttpRequestInterceptor...) */ public RestTemplateBuilder additionalInterceptors( Collection<? extends ClientHttpRequestInterceptor> interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, append(this.interceptors, interceptors)); } /** * Set the {@link ClientHttpRequestFactory} class that should be used with the * {@link RestTemplate}. * @param requestFactory the request factory to use * @return a new builder instance */ public RestTemplateBuilder requestFactory( Class<? extends ClientHttpRequestFactory> requestFactory) { Assert.notNull(requestFactory, "RequestFactory must not be null"); return requestFactory(createRequestFactory(requestFactory)); } private ClientHttpRequestFactory createRequestFactory( Class<? extends ClientHttpRequestFactory> requestFactory) { try { Constructor<?> constructor = requestFactory.getDeclaredConstructor(); constructor.setAccessible(true); return (ClientHttpRequestFactory) constructor.newInstance(); } catch (Exception ex) { throw new IllegalStateException(ex); } } /** * Set the {@link ClientHttpRequestFactory} that should be used with the * {@link RestTemplate}. * @param requestFactory the request factory to use * @return a new builder instance */ public RestTemplateBuilder requestFactory(ClientHttpRequestFactory requestFactory) { Assert.notNull(requestFactory, "RequestFactory must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set the {@link UriTemplateHandler} that should be used with the * {@link RestTemplate}. * @param uriTemplateHandler the URI template handler to use * @return a new builder instance */ public RestTemplateBuilder uriTemplateHandler(UriTemplateHandler uriTemplateHandler) { Assert.notNull(uriTemplateHandler, "UriTemplateHandler must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set the {@link ResponseErrorHandler} that should be used with the * {@link RestTemplate}. * @param errorHandler the error handler to use * @return a new builder instance */ public RestTemplateBuilder errorHandler(ResponseErrorHandler errorHandler) { Assert.notNull(errorHandler, "ErrorHandler must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Add HTTP basic authentication to requests. See * {@link BasicAuthorizationInterceptor} for details. * @param username the user name * @param password the password * @return a new builder instance */ public RestTemplateBuilder basicAuthorization(String username, String password) { return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, new BasicAuthorizationInterceptor(username, password), this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** * Set the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be * applied to the {@link RestTemplate}. Customizers are applied in the order that they * were added after builder configuration has been applied. Setting this value will * replace any previously configured customizers. * @param restTemplateCustomizers the customizers to set * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ public RestTemplateBuilder customizers( RestTemplateCustomizer... restTemplateCustomizers) { Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return customizers(Arrays.asList(restTemplateCustomizers)); } /** * Set the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be * applied to the {@link RestTemplate}. Customizers are applied in the order that they * were added after builder configuration has been applied. Setting this value will * replace any previously configured customizers. * @param restTemplateCustomizers the customizers to set * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ public RestTemplateBuilder customizers( Collection<? extends RestTemplateCustomizer> restTemplateCustomizers) { Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, Collections.unmodifiableSet(new LinkedHashSet<RestTemplateCustomizer>( restTemplateCustomizers)), this.requestFactoryCustomizers, this.interceptors); } /** * Add {@link RestTemplateCustomizer RestTemplateCustomizers} that should be applied * to the {@link RestTemplate}. Customizers are applied in the order that they were * added after builder configuration has been applied. * @param restTemplateCustomizers the customizers to add * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ public RestTemplateBuilder additionalCustomizers( RestTemplateCustomizer... restTemplateCustomizers) { Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return additionalCustomizers(Arrays.asList(restTemplateCustomizers)); } /** * Add {@link RestTemplateCustomizer RestTemplateCustomizers} that should be applied * to the {@link RestTemplate}. Customizers are applied in the order that they were * added after builder configuration has been applied. * @param customizers the customizers to add * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ public RestTemplateBuilder additionalCustomizers( Collection<? extends RestTemplateCustomizer> customizers) { Assert.notNull(customizers, "RestTemplateCustomizers must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, append(this.restTemplateCustomizers, customizers), this.requestFactoryCustomizers, this.interceptors); } /** * Sets the connect timeout in milliseconds on the underlying * {@link ClientHttpRequestFactory}. * @param connectTimeout the connect timeout in milliseconds * @return a new builder instance. */ public RestTemplateBuilder setConnectTimeout(int connectTimeout) { return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, append(this.requestFactoryCustomizers, new ConnectTimeoutRequestFactoryCustomizer(connectTimeout)), this.interceptors); } /** * Sets the read timeout in milliseconds on the underlying * {@link ClientHttpRequestFactory}. * @param readTimeout the read timeout in milliseconds * @return a new builder instance. */ public RestTemplateBuilder setReadTimeout(int readTimeout) { return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, append(this.requestFactoryCustomizers, new ReadTimeoutRequestFactoryCustomizer(readTimeout)), this.interceptors); } /** * Build a new {@link RestTemplate} instance and configure it using this builder. * @return a configured {@link RestTemplate} instance. * @see #build(Class) * @see #configure(RestTemplate) */ public RestTemplate build() { return build(RestTemplate.class); } /** * Build a new {@link RestTemplate} instance of the specified type and configure it * using this builder. * @param <T> the type of rest template * @param restTemplateClass the template type to create * @return a configured {@link RestTemplate} instance. * @see RestTemplateBuilder#build() * @see #configure(RestTemplate) */ public <T extends RestTemplate> T build(Class<T> restTemplateClass) { return configure(BeanUtils.instantiateClass(restTemplateClass)); } /** * Configure the provided {@link RestTemplate} instance using this builder. * @param <T> the type of rest template * @param restTemplate the {@link RestTemplate} to configure * @return the rest template instance * @see RestTemplateBuilder#build() * @see RestTemplateBuilder#build(Class) */ public <T extends RestTemplate> T configure(T restTemplate) { configureRequestFactory(restTemplate); if (!CollectionUtils.isEmpty(this.messageConverters)) { restTemplate.setMessageConverters(new ArrayList<>(this.messageConverters)); } if (this.uriTemplateHandler != null) { restTemplate.setUriTemplateHandler(this.uriTemplateHandler); } if (this.errorHandler != null) { restTemplate.setErrorHandler(this.errorHandler); } if (this.rootUri != null) { RootUriTemplateHandler.addTo(restTemplate, this.rootUri); } if (this.basicAuthorization != null) { restTemplate.getInterceptors().add(this.basicAuthorization); } if (!CollectionUtils.isEmpty(this.restTemplateCustomizers)) { for (RestTemplateCustomizer customizer : this.restTemplateCustomizers) { customizer.customize(restTemplate); } } restTemplate.getInterceptors().addAll(this.interceptors); return restTemplate; } private void configureRequestFactory(RestTemplate restTemplate) { ClientHttpRequestFactory requestFactory = null; if (this.requestFactory != null) { requestFactory = this.requestFactory; } else if (this.detectRequestFactory) { requestFactory = detectRequestFactory(); } if (requestFactory != null) { ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary( requestFactory); for (RequestFactoryCustomizer customizer : this.requestFactoryCustomizers) { customizer.customize(unwrappedRequestFactory); } restTemplate.setRequestFactory(requestFactory); } } private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary( ClientHttpRequestFactory requestFactory) { if (!(requestFactory instanceof AbstractClientHttpRequestFactoryWrapper)) { return requestFactory; } ClientHttpRequestFactory unwrappedRequestFactory = requestFactory; Field field = ReflectionUtils.findField( AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); ReflectionUtils.makeAccessible(field); do { unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils .getField(field, unwrappedRequestFactory); } while (unwrappedRequestFactory instanceof AbstractClientHttpRequestFactoryWrapper); return unwrappedRequestFactory; } private ClientHttpRequestFactory detectRequestFactory() { for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES .entrySet()) { ClassLoader classLoader = getClass().getClassLoader(); if (ClassUtils.isPresent(candidate.getKey(), classLoader)) { Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(), classLoader); return (ClientHttpRequestFactory) BeanUtils .instantiateClass(factoryClass); } } return new SimpleClientHttpRequestFactory(); } private <T> Set<T> append(Set<T> set, T addition) { Set<T> result = new LinkedHashSet<>( set == null ? Collections.<T>emptySet() : set); result.add(addition); return Collections.unmodifiableSet(result); } private <T> Set<T> append(Set<T> set, Collection<? extends T> additions) { Set<T> result = new LinkedHashSet<>( set == null ? Collections.<T>emptySet() : set); result.addAll(additions); return Collections.unmodifiableSet(result); } /** * Strategy interface used to customize the {@link ClientHttpRequestFactory}. */ private interface RequestFactoryCustomizer { void customize(ClientHttpRequestFactory factory); } /** * {@link RequestFactoryCustomizer} to call a "set timeout" method. */ private static abstract class TimeoutRequestFactoryCustomizer implements RequestFactoryCustomizer { private final int timeout; private final String methodName; TimeoutRequestFactoryCustomizer(int timeout, String methodName) { this.timeout = timeout; this.methodName = methodName; } @Override public void customize(ClientHttpRequestFactory factory) { ReflectionUtils.invokeMethod(findMethod(factory), factory, this.timeout); } private Method findMethod(ClientHttpRequestFactory factory) { Method method = ReflectionUtils.findMethod(factory.getClass(), this.methodName, int.class); if (method != null) { return method; } throw new IllegalStateException("Request factory " + factory.getClass() + " does not have a " + this.methodName + "(int) method"); } } /** * {@link RequestFactoryCustomizer} to set the read timeout. */ private static class ReadTimeoutRequestFactoryCustomizer extends TimeoutRequestFactoryCustomizer { ReadTimeoutRequestFactoryCustomizer(int readTimeout) { super(readTimeout, "setReadTimeout"); } } /** * {@link RequestFactoryCustomizer} to set the connect timeout. */ private static class ConnectTimeoutRequestFactoryCustomizer extends TimeoutRequestFactoryCustomizer { ConnectTimeoutRequestFactoryCustomizer(int connectTimeout) { super(connectTimeout, "setConnectTimeout"); } } }
package dynamo.handlers; import dynamo.AmbariRestClient; import dynamo.serialization.*; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.InputStream; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Properties; /****************************************************************************** * Sends data to a Kafka cluster. ******************************************************************************/ public class KafkaHandler implements IDataHandler { private final Logger _logger = LoggerFactory.getLogger(KafkaHandler.class); private final Properties _kafkaProperties = new Properties(); private ISerializer _serializer; private String _keySerializer; private String _valueSerializer; private String _topic; private String _ambariUrl; private String _kafkaCluster; private String _kafkaUsername; private String _kafkaPassword; private String _zookeeperHost = null; private String _brokerList = null; private ArrayList<String> _zookeeperNodes; private ArrayList<String> _kafkaBrokerNodes; private KafkaProducer<String, byte[]> _producer; /**************************************************************************** * Creates an instance of KafkaHandler. ****************************************************************************/ public KafkaHandler() { CheckConfiguration(); DiscoverZookeeperAndBrokers(); InitializeKafka(); } /**************************************************************************** * Creates an instance of KafkaHandler. * * @param topic * The topic. ****************************************************************************/ public KafkaHandler(String topic) { this (topic, null); } /**************************************************************************** * Creates an instance of KafkaHandler. * * @param serializer * The serializer. ****************************************************************************/ public KafkaHandler(ISerializer serializer) { this(null, serializer); } /**************************************************************************** * Creates an instance of KafkaHandler. * * @param topic * The topic. * @param serializer * The serializer. ****************************************************************************/ public KafkaHandler(String topic, ISerializer serializer) { _topic = topic; _serializer = serializer; CheckConfiguration(); DiscoverZookeeperAndBrokers(); InitializeKafka(); } /**************************************************************************** * Serializes the data to a byte array and sends it a Kafka cluster. * * @param data * The data. * @throws Throwable * Any uncaught exception. ****************************************************************************/ public void HandleData(Object data) throws Throwable { if (_serializer == null) throw new NullPointerException("No serialization set."); final byte[] serializedData = _serializer.Serialize(data); final ProducerRecord<String, byte[]> record = new ProducerRecord<>(_topic, serializedData); _producer = new KafkaProducer<>(_kafkaProperties); _producer.send(record); _producer.close(); } /**************************************************************************** * Checks for a properties file to load settings. ****************************************************************************/ private void CheckConfiguration() { InputStream propertiesStream = null; try { final String propertiesFile = Paths.get("dynamo.properties").toAbsolutePath().toString(); propertiesStream = new FileInputStream(propertiesFile); final Properties settings = new Properties(); settings.load(propertiesStream); _ambariUrl = settings.getProperty("Handlers.Kafka.BaseUrl"); _kafkaCluster = settings.getProperty("Handlers.Kafka.Cluster"); _kafkaPassword = settings.getProperty("Handlers.Kafka.Password"); _kafkaUsername = settings.getProperty("Handlers.Kafka.Username"); _keySerializer = settings.getProperty("Handlers.Kafka.KeySerializer"); _valueSerializer = settings.getProperty("Handlers.Kafka.ValueSerializer"); if (_topic == null || _topic.isEmpty()) _topic = settings.getProperty("Handlers.Kafka.Topic"); if (_serializer == null) _serializer = ConfigureSerializer(settings); } catch (Exception e) { _logger.error(e.getMessage(), e); System.exit(0); } finally { if (propertiesStream != null) { try { propertiesStream.close(); } catch (Exception e) { _logger.error(e.getMessage(), e); } } } } /**************************************************************************** * Sets up serialization from configuration settings. * * @param settings * The properties object with the parsed settings. * @return * The serializer ****************************************************************************/ private ISerializer ConfigureSerializer(final Properties settings) { final String serializationFormat = settings.getProperty("Serialization.Format"); switch (serializationFormat.toLowerCase()) { case "avro": return new AvroSerializer(); case "json": return new JsonSerializer(); case "text": final String fieldDelimiter = settings.getProperty("Serialization.Delimiter"); return new TextSerializer(fieldDelimiter); case "xml": return new XmlSerializer(); default: throw new IllegalArgumentException("Unsupported serialization format: " + serializationFormat); } } /**************************************************************************** * Discovers the Zookeeper and Kafka Broker nodes via the Ambari REST API. ****************************************************************************/ private void DiscoverZookeeperAndBrokers() { AmbariRestClient ambariRestClient = new AmbariRestClient(_ambariUrl, _kafkaCluster, _kafkaUsername, _kafkaPassword); _zookeeperNodes = ambariRestClient.getZookeeperNodes(); _kafkaBrokerNodes = ambariRestClient.getKafkaNodes(); for (String node : _zookeeperNodes) _zookeeperHost += node + ","; _zookeeperHost = _zookeeperHost.substring(0, _zookeeperHost.length() - 2); for (String broker : _kafkaBrokerNodes) _brokerList += broker + ","; _zookeeperHost = _zookeeperHost.substring(0, _zookeeperHost.length() - 2); } /**************************************************************************** * Initializes settings for Kafka. ****************************************************************************/ private void InitializeKafka() { _kafkaProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, _brokerList); _kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, _keySerializer); _kafkaProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, _valueSerializer); _kafkaProperties.put(ProducerConfig.ACKS_CONFIG, "1"); } }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.tests.gwt; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.tests.AccelerometerTest; import com.badlogic.gdx.tests.ActionSequenceTest; import com.badlogic.gdx.tests.ActionTest; import com.badlogic.gdx.tests.AlphaTest; import com.badlogic.gdx.tests.AnimationTest; import com.badlogic.gdx.tests.AssetManagerTest; import com.badlogic.gdx.tests.AtlasIssueTest; import com.badlogic.gdx.tests.BitmapFontAlignmentTest; import com.badlogic.gdx.tests.BitmapFontFlipTest; import com.badlogic.gdx.tests.BitmapFontMetricsTest; import com.badlogic.gdx.tests.BitmapFontTest; import com.badlogic.gdx.tests.BlitTest; import com.badlogic.gdx.tests.Box2DCharacterControllerTest; import com.badlogic.gdx.tests.Box2DTest; import com.badlogic.gdx.tests.Box2DTestCollection; import com.badlogic.gdx.tests.ComplexActionTest; import com.badlogic.gdx.tests.CustomShaderSpriteBatchTest; import com.badlogic.gdx.tests.DecalTest; import com.badlogic.gdx.tests.EdgeDetectionTest; import com.badlogic.gdx.tests.FilterPerformanceTest; import com.badlogic.gdx.tests.FrameBufferTest; import com.badlogic.gdx.tests.GestureDetectorTest; import com.badlogic.gdx.tests.GroupCullingTest; import com.badlogic.gdx.tests.GroupFadeTest; import com.badlogic.gdx.tests.I18NSimpleMessageTest; import com.badlogic.gdx.tests.ImageScaleTest; import com.badlogic.gdx.tests.ImageTest; import com.badlogic.gdx.tests.IndexBufferObjectShaderTest; import com.badlogic.gdx.tests.IntegerBitmapFontTest; import com.badlogic.gdx.tests.InverseKinematicsTest; import com.badlogic.gdx.tests.IsometricTileTest; import com.badlogic.gdx.tests.KinematicBodyTest; import com.badlogic.gdx.tests.LabelScaleTest; import com.badlogic.gdx.tests.LabelTest; import com.badlogic.gdx.tests.LifeCycleTest; import com.badlogic.gdx.tests.MeshShaderTest; import com.badlogic.gdx.tests.MipMapTest; import com.badlogic.gdx.tests.MultitouchTest; import com.badlogic.gdx.tests.MusicTest; import com.badlogic.gdx.tests.ParallaxTest; import com.badlogic.gdx.tests.ParticleEmitterTest; import com.badlogic.gdx.tests.PixelsPerInchTest; import com.badlogic.gdx.tests.ProjectiveTextureTest; import com.badlogic.gdx.tests.ReflectionTest; import com.badlogic.gdx.tests.RotationTest; import com.badlogic.gdx.tests.ShapeRendererTest; import com.badlogic.gdx.tests.SimpleAnimationTest; import com.badlogic.gdx.tests.SimpleDecalTest; import com.badlogic.gdx.tests.SimpleStageCullingTest; import com.badlogic.gdx.tests.SortedSpriteTest; import com.badlogic.gdx.tests.SoundTest; import com.badlogic.gdx.tests.SpriteBatchShaderTest; import com.badlogic.gdx.tests.SpriteCacheOffsetTest; import com.badlogic.gdx.tests.SpriteCacheTest; import com.badlogic.gdx.tests.StageTest; import com.badlogic.gdx.tests.TableTest; import com.badlogic.gdx.tests.TextButtonTest; import com.badlogic.gdx.tests.TextureAtlasTest; import com.badlogic.gdx.tests.TiledMapAtlasAssetManagerTest; import com.badlogic.gdx.tests.TimeUtilsTest; import com.badlogic.gdx.tests.UITest; import com.badlogic.gdx.tests.VertexBufferObjectShaderTest; import com.badlogic.gdx.tests.YDownTest; import com.badlogic.gdx.tests.g3d.ShadowMappingTest; import com.badlogic.gdx.tests.superkoalio.SuperKoalio; import com.badlogic.gdx.tests.utils.GdxTest; public class GwtTestWrapper extends GdxTest { Stage ui; Table container; Skin skin; BitmapFont font; GdxTest test; boolean dispose = false; @Override public void create () { Gdx.app.setLogLevel(Application.LOG_DEBUG); Gdx.app.log("GdxTestGwt", "Setting up for " + tests.length + " tests."); ui = new Stage(); skin = new Skin(Gdx.files.internal("data/uiskin.json")); font = new BitmapFont(Gdx.files.internal("data/arial-15.fnt"), false); container = new Table(); ui.addActor(container); container.debug(); Table table = new Table(); ScrollPane scroll = new ScrollPane(table); container.add(scroll).expand().fill(); table.pad(10).defaults().expandX().space(4); for (final Instancer instancer : tests) { table.row(); TextButton button = new TextButton(instancer.instance().getClass().getName(), skin); button.addListener(new ClickListener() { @Override public void clicked (InputEvent event, float x, float y) { ((InputWrapper)Gdx.input).multiplexer.removeProcessor(ui); test = instancer.instance(); Gdx.app.log("GdxTestGwt", "Clicked on " + test.getClass().getName()); test.create(); test.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } }); table.add(button).expandX().fillX(); } container.row(); container.add(new Label("Click on a test to start it, press ESC to close it.", new LabelStyle(font, Color.WHITE))).pad(5, 5, 5, 5); Gdx.input = new InputWrapper(Gdx.input) { @Override public boolean keyUp (int keycode) { if (keycode == Keys.ESCAPE) { if (test != null) { Gdx.app.log("GdxTestGwt", "Exiting current test."); dispose = true; } } return false; } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { if (screenX < Gdx.graphics.getWidth() / 10.0 && screenY < Gdx.graphics.getHeight() / 10.0) { if (test != null) { dispose = true; } } return false; } }; ((InputWrapper)Gdx.input).multiplexer.addProcessor(ui); Gdx.app.log("GdxTestGwt", "Test picker UI setup complete."); } public void render () { if (test == null) { Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClearColor(0, 0, 0, 0); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); ui.act(Gdx.graphics.getDeltaTime()); ui.draw(); } else { if (dispose) { test.pause(); test.dispose(); test = null; Gdx.graphics.setVSync(true); InputWrapper wrapper = ((InputWrapper)Gdx.input); wrapper.multiplexer.addProcessor(ui); wrapper.multiplexer.removeProcessor(wrapper.lastProcessor); wrapper.lastProcessor = null; dispose = false; } else { test.render(); } } } public void resize (int width, int height) { ui.getViewport().update(width, height, true); container.setSize(width, height); if (test != null) { test.resize(width, height); } } class InputWrapper extends InputAdapter implements Input { Input input; InputProcessor lastProcessor; InputMultiplexer multiplexer; public InputWrapper (Input input) { this.input = input; this.multiplexer = new InputMultiplexer(); this.multiplexer.addProcessor(this); input.setInputProcessor(multiplexer); } @Override public float getAccelerometerX () { return input.getAccelerometerX(); } @Override public float getAccelerometerY () { return input.getAccelerometerY(); } @Override public float getAccelerometerZ () { return input.getAccelerometerZ(); } @Override public int getX () { return input.getX(); } @Override public int getX (int pointer) { return input.getX(pointer); } @Override public int getDeltaX () { return input.getDeltaX(); } @Override public int getDeltaX (int pointer) { return input.getDeltaX(pointer); } @Override public int getY () { return input.getY(); } @Override public int getY (int pointer) { return input.getY(pointer); } @Override public int getDeltaY () { return input.getDeltaY(); } @Override public int getDeltaY (int pointer) { return input.getDeltaY(pointer); } @Override public boolean isTouched () { return input.isTouched(); } @Override public boolean justTouched () { return input.justTouched(); } @Override public boolean isTouched (int pointer) { return input.isTouched(pointer); } @Override public boolean isButtonPressed (int button) { return input.isButtonPressed(button); } @Override public boolean isKeyPressed (int key) { return input.isKeyPressed(key); } @Override public void getTextInput (TextInputListener listener, String title, String text) { input.getTextInput(listener, title, text); } @Override public void getPlaceholderTextInput (TextInputListener listener, String title, String placeholder) { input.getPlaceholderTextInput(listener, title, placeholder); } @Override public void setOnscreenKeyboardVisible (boolean visible) { input.setOnscreenKeyboardVisible(visible); } @Override public void vibrate (int milliseconds) { input.vibrate(milliseconds); } @Override public void vibrate (long[] pattern, int repeat) { input.vibrate(pattern, repeat); } @Override public void cancelVibrate () { input.cancelVibrate(); } @Override public float getAzimuth () { return input.getAzimuth(); } @Override public float getPitch () { return input.getPitch(); } @Override public float getRoll () { return input.getRoll(); } @Override public void getRotationMatrix (float[] matrix) { input.getRotationMatrix(matrix); } @Override public long getCurrentEventTime () { return input.getCurrentEventTime(); } @Override public void setCatchBackKey (boolean catchBack) { input.setCatchBackKey(catchBack); } @Override public void setCatchMenuKey (boolean catchMenu) { input.setCatchMenuKey(catchMenu); } @Override public void setInputProcessor (InputProcessor processor) { multiplexer.removeProcessor(lastProcessor); multiplexer.addProcessor(processor); lastProcessor = processor; } @Override public InputProcessor getInputProcessor () { return input.getInputProcessor(); } @Override public boolean isPeripheralAvailable (Peripheral peripheral) { return input.isPeripheralAvailable(peripheral); } @Override public int getRotation () { return input.getRotation(); } @Override public Orientation getNativeOrientation () { return input.getNativeOrientation(); } @Override public void setCursorCatched (boolean catched) { input.setCursorCatched(catched); } @Override public boolean isCursorCatched () { return input.isCursorCatched(); } @Override public void setCursorPosition (int x, int y) { setCursorPosition(x, y); } @Override public void setCursorImage (Pixmap pixmap, int xHotspot, int yHotspot) { } } interface Instancer { public GdxTest instance (); } Instancer[] tests = {new Instancer() { public GdxTest instance () { return new AccelerometerTest(); } }, new Instancer() { public GdxTest instance () { return new ActionTest(); } }, new Instancer() { public GdxTest instance () { return new ActionSequenceTest(); } }, new Instancer() { public GdxTest instance () { return new AnimationTest(); } }, new Instancer() { public GdxTest instance () { return new AssetManagerTest(); } }, new Instancer() { public GdxTest instance () { return new AtlasIssueTest(); } }, new Instancer() { public GdxTest instance () { return new BitmapFontAlignmentTest(); } }, new Instancer() { public GdxTest instance () { return new BitmapFontFlipTest(); } }, new Instancer() { public GdxTest instance () { return new BitmapFontTest(); } }, new Instancer() { public GdxTest instance () { return new BitmapFontMetricsTest(); } }, new Instancer() { public GdxTest instance () { return new BlitTest(); } }, new Instancer() { public GdxTest instance () { return new Box2DCharacterControllerTest(); } }, new Instancer() { public GdxTest instance () { return new Box2DTest(); } }, new Instancer() { public GdxTest instance () { return new Box2DTestCollection(); } }, new Instancer() { public GdxTest instance () { return new ComplexActionTest(); } }, new Instancer() { public GdxTest instance () { return new CustomShaderSpriteBatchTest(); } }, new Instancer() { public GdxTest instance () { return new DecalTest(); } }, new Instancer() { public GdxTest instance () { return new LabelScaleTest(); } }, new Instancer() { public GdxTest instance () { return new EdgeDetectionTest(); } }, new Instancer() { public GdxTest instance () { return new FilterPerformanceTest(); } }, // new Instancer() {public GdxTest instance(){return new FlickScrollPaneTest();}}, // FIXME this messes up stuff, why? new Instancer() { public GdxTest instance () { return new FrameBufferTest(); } }, new Instancer() { public GdxTest instance () { return new GestureDetectorTest(); } }, new Instancer() { public GdxTest instance () { return new GroupCullingTest(); } }, new Instancer() { public GdxTest instance () { return new GroupFadeTest(); } }, new Instancer() { public GdxTest instance () { return new I18NSimpleMessageTest(); } }, new Instancer() { public GdxTest instance () { return new ImageScaleTest(); } }, new Instancer() { public GdxTest instance () { return new ImageTest(); } }, new Instancer() { public GdxTest instance () { return new IndexBufferObjectShaderTest(); } }, new Instancer() { public GdxTest instance () { return new IntegerBitmapFontTest(); } }, new Instancer() { public GdxTest instance () { return new InverseKinematicsTest(); } }, new Instancer() { public GdxTest instance () { return new IsometricTileTest(); } }, new Instancer() { public GdxTest instance () { return new KinematicBodyTest(); } }, new Instancer() { public GdxTest instance () { return new LifeCycleTest(); } }, new Instancer() { public GdxTest instance () { return new LabelTest(); } }, // new Instancer() {public GdxTest instance(){return new MatrixJNITest();}}, // No purpose new Instancer() { public GdxTest instance () { return new MeshShaderTest(); } }, new Instancer() { public GdxTest instance () { return new MipMapTest(); } }, new Instancer() { public GdxTest instance () { return new MultitouchTest(); } }, new Instancer() { public GdxTest instance () { return new MusicTest(); } }, new Instancer() { public GdxTest instance () { return new ParallaxTest(); } }, new Instancer() { public GdxTest instance () { return new ParticleEmitterTest(); } }, new Instancer() { public GdxTest instance () { return new PixelsPerInchTest(); } }, // new Instancer() {public GdxTest instance(){return new PixmapBlendingTest();}}, // FIXME no idea why this doesn't work new Instancer() { public GdxTest instance () { return new ProjectiveTextureTest(); } }, new Instancer() { public GdxTest instance () { return new RotationTest(); } }, // new Instancer() {public GdxTest instance(){return new RunnablePostTest();}}, // Goes into infinite loop // new Instancer() {public GdxTest instance(){return new ScrollPaneTest();}}, // FIXME this messes up stuff, why? // new Instancer() {public GdxTest instance(){return new ShaderMultitextureTest();}}, // FIXME fucks up stuff new Instancer() { public GdxTest instance () { return new ShadowMappingTest(); } }, new Instancer() { public GdxTest instance () { return new ShapeRendererTest(); } }, new Instancer() { public GdxTest instance () { return new SimpleAnimationTest(); } }, new Instancer() { public GdxTest instance () { return new SimpleDecalTest(); } }, new Instancer() { public GdxTest instance () { return new SimpleStageCullingTest(); } }, new Instancer() { public GdxTest instance () { return new SortedSpriteTest(); } }, new Instancer() { public GdxTest instance () { return new SpriteBatchShaderTest(); } }, new Instancer() { public GdxTest instance () { return new SpriteCacheOffsetTest(); } }, new Instancer() { public GdxTest instance () { return new SpriteCacheTest(); } }, new Instancer() { public GdxTest instance () { return new SoundTest(); } }, new Instancer() { public GdxTest instance () { return new StageTest(); } }, // new Instancer() {public GdxTest instance(){return new StagePerformanceTest();}}, // FIXME borks out new Instancer() { public GdxTest instance () { return new TableTest(); } }, new Instancer() { public GdxTest instance () { return new TextButtonTest(); } }, new Instancer() { public GdxTest instance () { return new TextButtonTest(); } }, new Instancer() { public GdxTest instance () { return new TextureAtlasTest(); } }, new Instancer() { public GdxTest instance () { return new UITest(); } }, new Instancer() { public GdxTest instance () { return new VertexBufferObjectShaderTest(); } }, new Instancer() { public GdxTest instance () { return new YDownTest(); } }, new Instancer() { public GdxTest instance () { return new SuperKoalio(); } }, new Instancer() { public GdxTest instance () { return new ReflectionTest(); } }, new Instancer() { public GdxTest instance () { return new TiledMapAtlasAssetManagerTest(); } }, new Instancer() { public GdxTest instance () { return new TimeUtilsTest(); } }}; }
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.sqoop; import org.junit.BeforeClass; import org.junit.Test; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.job.entry.JobEntryCopy; import org.pentaho.di.repository.LongObjectId; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryMeta; import org.pentaho.di.repository.filerep.KettleFileRepository; import org.pentaho.di.repository.kdr.KettleDatabaseRepository; import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryCreationHelper; import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta; import org.w3c.dom.Document; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import static org.junit.Assert.*; public class SqoopExportJobEntryTest { @BeforeClass public static void init() throws KettleException { KettleEnvironment.init(); } @Test public void conditionalsForUIInteractions() { SqoopExportJobEntry je = new SqoopExportJobEntry(); assertTrue(je.evaluates()); assertTrue(je.isUnconditional()); } @Test public void getTool() { SqoopExportJobEntry je = new SqoopExportJobEntry(); assertEquals("export", je.getToolName()); } @Test public void saveLoadTest_xml() throws KettleXMLException { SqoopExportJobEntry je = new SqoopExportJobEntry(); SqoopExportConfig config = new SqoopExportConfig(); String connectValue = "jdbc:mysql://localhost:3306/test"; String myPassword = "my-password"; DatabaseMeta databaseMeta = new DatabaseMeta("test database", "H2", null, null, null, null, null, null); config.setJobEntryName("testing"); config.setBlockingExecution("false"); config.setBlockingPollingInterval("100"); config.setConnect(connectValue); config.setExportDir("/test-export"); config.setPassword(myPassword); config.setDatabase(databaseMeta.getName()); je.setJobConfig(config); JobEntryCopy jec = new JobEntryCopy(je); jec.setLocation(0, 0); String xml = jec.getXML(); assertTrue("Password not encrypted upon save to xml", !xml.contains(myPassword)); Document d = XMLHandler.loadXMLString(xml); SqoopExportJobEntry je2 = new SqoopExportJobEntry(); je2.loadXML(d.getDocumentElement(), Collections.singletonList(databaseMeta), null, null); SqoopExportConfig config2 = je2.getJobConfig(); assertEquals(config.getJobEntryName(), config2.getJobEntryName()); assertEquals(config.getBlockingExecution(), config2.getBlockingExecution()); assertEquals(config.getBlockingPollingInterval(), config2.getBlockingPollingInterval()); assertEquals(config.getConnect(), config2.getConnect()); assertEquals(config.getExportDir(), config2.getExportDir()); assertEquals(config.getPassword(), config2.getPassword()); assertEquals(config.getDatabase(), config2.getDatabase()); assertNotNull(je2.getDatabaseMeta()); assertEquals(databaseMeta.getName(), je2.getDatabaseMeta().getName()); } @Test public void saveLoadTest_xml_advanced_options() throws KettleXMLException { SqoopExportJobEntry je = new SqoopExportJobEntry(); SqoopExportConfig config = new SqoopExportConfig(); String connectValue = "jdbc:mysql://localhost:3306/test"; String myPassword = "my-password"; config.setJobEntryName("testing"); config.setBlockingExecution("false"); config.setBlockingPollingInterval("100"); config.setConnect(connectValue); config.setExportDir("/test-export"); config.setPassword(myPassword); config.copyConnectionInfoToAdvanced(); je.setJobConfig(config); JobEntryCopy jec = new JobEntryCopy(je); jec.setLocation(0, 0); String xml = jec.getXML(); assertTrue("Password not encrypted upon save to xml", !xml.contains(myPassword)); Document d = XMLHandler.loadXMLString(xml); SqoopExportJobEntry je2 = new SqoopExportJobEntry(); je2.loadXML(d.getDocumentElement(), null, null, null); SqoopExportConfig config2 = je2.getJobConfig(); assertEquals(config.getJobEntryName(), config2.getJobEntryName()); assertEquals(config.getBlockingExecution(), config2.getBlockingExecution()); assertEquals(config.getBlockingPollingInterval(), config2.getBlockingPollingInterval()); assertEquals(config.getConnect(), config2.getConnect()); assertEquals(config.getExportDir(), config2.getExportDir()); assertEquals(config.getPassword(), config2.getPassword()); assertNull(config2.getDatabase()); assertEquals(config.getConnectFromAdvanced(), config2.getConnectFromAdvanced()); assertEquals(config.getUsernameFromAdvanced(), config2.getUsernameFromAdvanced()); assertEquals(config.getPasswordFromAdvanced(), config2.getPasswordFromAdvanced()); assertNull(je2.getDatabaseMeta()); } @Test public void saveLoadTest_rep() throws KettleException, IOException { SqoopExportJobEntry je = new SqoopExportJobEntry(); SqoopExportConfig config = new SqoopExportConfig(); String connectValue = "jdbc:mysql://localhost:3306/test"; DatabaseMeta meta = new DatabaseMeta("test database", "H2", null, null, null, null, null, null); config.setJobEntryName("testing"); config.setBlockingExecution("${blocking}"); config.setBlockingPollingInterval("100"); config.setConnect(connectValue); config.setExportDir("/test-export"); config.setPassword("my-password"); config.setDatabase(meta.getName()); je.setJobConfig(config); KettleEnvironment.init(); String filename = File.createTempFile(getClass().getSimpleName() + "-export-dbtest", "").getAbsolutePath(); try { DatabaseMeta databaseMeta = new DatabaseMeta("H2Repo", "H2", "JDBC", null, filename, null, null, null); RepositoryMeta repositoryMeta = new KettleDatabaseRepositoryMeta("KettleDatabaseRepository", "H2Repo", "H2 Repository", databaseMeta); KettleDatabaseRepository repository = new KettleDatabaseRepository(); repository.init(repositoryMeta); repository.connectionDelegate.connect(true, true); KettleDatabaseRepositoryCreationHelper helper = new KettleDatabaseRepositoryCreationHelper(repository); helper.createRepositorySchema(null, false, new ArrayList<String>(), false); repository.disconnect(); // Test connecting... // repository.connect("admin", "admin"); assertTrue(repository.isConnected()); // A job entry must have an ID if we're going to save it to a repository je.setObjectId(new LongObjectId(1)); ObjectId id_job = new LongObjectId(1); // Save the original job entry into the repository je.saveRep(repository, id_job); // Load it back into a new job entry SqoopExportJobEntry je2 = new SqoopExportJobEntry(); je2.loadRep(repository, id_job, Collections.singletonList(meta), null); // Make sure all settings we set are properly loaded SqoopExportConfig config2 = je2.getJobConfig(); assertEquals(config.getJobEntryName(), config2.getJobEntryName()); assertEquals(config.getBlockingExecution(), config2.getBlockingExecution()); assertEquals(config.getBlockingPollingInterval(), config2.getBlockingPollingInterval()); assertEquals(config.getConnect(), config2.getConnect()); assertEquals(config.getExportDir(), config2.getExportDir()); assertEquals(config.getPassword(), config2.getPassword()); assertNotNull(je2.getDatabaseMeta()); assertEquals(meta.getName(), je2.getDatabaseMeta().getName()); } finally { // Delete test database new File(filename+".h2.db").delete(); new File(filename+".trace.db").delete(); } } @Test public void saveLoadTest_rep_advanced_options() throws KettleException, IOException { SqoopExportJobEntry je = new SqoopExportJobEntry(); SqoopExportConfig config = new SqoopExportConfig(); String connectValue = "jdbc:mysql://localhost:3306/test"; config.setJobEntryName("testing"); config.setBlockingExecution("${blocking}"); config.setBlockingPollingInterval("100"); config.setConnect(connectValue); config.setExportDir("/test-export"); config.setPassword("my-password"); config.copyConnectionInfoToAdvanced(); je.setJobConfig(config); KettleEnvironment.init(); String filename = File.createTempFile(getClass().getSimpleName() + "-export-dbtest", "").getAbsolutePath(); try { DatabaseMeta databaseMeta = new DatabaseMeta("H2Repo", "H2", "JDBC", null, filename, null, null, null); RepositoryMeta repositoryMeta = new KettleDatabaseRepositoryMeta("KettleDatabaseRepository", "H2Repo", "H2 Repository", databaseMeta); KettleDatabaseRepository repository = new KettleDatabaseRepository(); repository.init(repositoryMeta); repository.connectionDelegate.connect(true, true); KettleDatabaseRepositoryCreationHelper helper = new KettleDatabaseRepositoryCreationHelper(repository); helper.createRepositorySchema(null, false, new ArrayList<String>(), false); repository.disconnect(); // Test connecting... // repository.connect("admin", "admin"); assertTrue(repository.isConnected()); // A job entry must have an ID if we're going to save it to a repository je.setObjectId(new LongObjectId(1)); ObjectId id_job = new LongObjectId(1); // Save the original job entry into the repository je.saveRep(repository, id_job); // Load it back into a new job entry SqoopExportJobEntry je2 = new SqoopExportJobEntry(); je2.loadRep(repository, id_job, null, null); // Make sure all settings we set are properly loaded SqoopExportConfig config2 = je2.getJobConfig(); assertEquals(config.getJobEntryName(), config2.getJobEntryName()); assertEquals(config.getBlockingExecution(), config2.getBlockingExecution()); assertEquals(config.getBlockingPollingInterval(), config2.getBlockingPollingInterval()); assertEquals(config.getConnect(), config2.getConnect()); assertEquals(config.getExportDir(), config2.getExportDir()); assertEquals(config.getPassword(), config2.getPassword()); assertNull(config2.getDatabase()); assertEquals(config.getConnectFromAdvanced(), config2.getConnectFromAdvanced()); assertEquals(config.getUsernameFromAdvanced(), config2.getUsernameFromAdvanced()); assertEquals(config.getPasswordFromAdvanced(), config2.getPasswordFromAdvanced()); assertNull(je2.getDatabaseMeta()); } finally { // Delete test database new File(filename+".h2.db").delete(); new File(filename+".trace.db").delete(); } } @Test public void getDatabaseMeta() throws KettleException { SqoopExportJobEntry entry = new SqoopExportJobEntry(); DatabaseMeta meta = new DatabaseMeta("test", "H2", null, null, null, null, null, null); assertNull(entry.getDatabaseMeta()); entry.setDatabaseMeta(meta); assertEquals(meta, entry.getDatabaseMeta()); } }
/* * 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.arrow.vector.complex; import static org.apache.arrow.memory.util.LargeMemoryUtil.capAtMaxInt; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.arrow.memory.ArrowBuf; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.util.CommonUtil; import org.apache.arrow.util.Preconditions; import org.apache.arrow.vector.AddOrGetResult; import org.apache.arrow.vector.BaseFixedWidthVector; import org.apache.arrow.vector.BaseValueVector; import org.apache.arrow.vector.BaseVariableWidthVector; import org.apache.arrow.vector.DensityAwareVector; import org.apache.arrow.vector.FieldVector; import org.apache.arrow.vector.NullVector; import org.apache.arrow.vector.UInt4Vector; import org.apache.arrow.vector.ValueVector; import org.apache.arrow.vector.ZeroVector; import org.apache.arrow.vector.types.pojo.ArrowType.ArrowTypeID; import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.util.CallBack; import org.apache.arrow.vector.util.OversizedAllocationException; import org.apache.arrow.vector.util.SchemaChangeRuntimeException; /** Base class for Vectors that contain repeated values. */ public abstract class BaseRepeatedValueVector extends BaseValueVector implements RepeatedValueVector, BaseListVector { public static final FieldVector DEFAULT_DATA_VECTOR = ZeroVector.INSTANCE; public static final String DATA_VECTOR_NAME = "$data$"; public static final byte OFFSET_WIDTH = 4; protected ArrowBuf offsetBuffer; protected FieldVector vector; protected final CallBack callBack; protected int valueCount; protected long offsetAllocationSizeInBytes = INITIAL_VALUE_ALLOCATION * OFFSET_WIDTH; private final String name; protected String defaultDataVectorName = DATA_VECTOR_NAME; protected BaseRepeatedValueVector(String name, BufferAllocator allocator, CallBack callBack) { this(name, allocator, DEFAULT_DATA_VECTOR, callBack); } protected BaseRepeatedValueVector(String name, BufferAllocator allocator, FieldVector vector, CallBack callBack) { super(allocator); this.name = name; this.offsetBuffer = allocator.getEmpty(); this.vector = Preconditions.checkNotNull(vector, "data vector cannot be null"); this.callBack = callBack; this.valueCount = 0; } @Override public String getName() { return name; } @Override public boolean allocateNewSafe() { boolean dataAlloc = false; try { allocateOffsetBuffer(offsetAllocationSizeInBytes); dataAlloc = vector.allocateNewSafe(); } catch (Exception e) { e.printStackTrace(); clear(); return false; } finally { if (!dataAlloc) { clear(); } } return dataAlloc; } protected void allocateOffsetBuffer(final long size) { final int curSize = (int) size; offsetBuffer = allocator.buffer(curSize); offsetBuffer.readerIndex(0); offsetAllocationSizeInBytes = curSize; offsetBuffer.setZero(0, offsetBuffer.capacity()); } @Override public void reAlloc() { reallocOffsetBuffer(); vector.reAlloc(); } protected void reallocOffsetBuffer() { final long currentBufferCapacity = offsetBuffer.capacity(); long newAllocationSize = currentBufferCapacity * 2; if (newAllocationSize == 0) { if (offsetAllocationSizeInBytes > 0) { newAllocationSize = offsetAllocationSizeInBytes; } else { newAllocationSize = INITIAL_VALUE_ALLOCATION * OFFSET_WIDTH * 2; } } newAllocationSize = CommonUtil.nextPowerOfTwo(newAllocationSize); newAllocationSize = Math.min(newAllocationSize, (long) (OFFSET_WIDTH) * Integer.MAX_VALUE); assert newAllocationSize >= 1; if (newAllocationSize > MAX_ALLOCATION_SIZE || newAllocationSize <= offsetBuffer.capacity()) { throw new OversizedAllocationException("Unable to expand the buffer"); } final ArrowBuf newBuf = allocator.buffer(newAllocationSize); newBuf.setBytes(0, offsetBuffer, 0, currentBufferCapacity); newBuf.setZero(currentBufferCapacity, newBuf.capacity() - currentBufferCapacity); offsetBuffer.getReferenceManager().release(1); offsetBuffer = newBuf; offsetAllocationSizeInBytes = newAllocationSize; } /** * Get the offset vector. * @deprecated This API will be removed, as the current implementations no longer hold inner offset vectors. * * @return the underlying offset vector or null if none exists. */ @Override @Deprecated public UInt4Vector getOffsetVector() { throw new UnsupportedOperationException("There is no inner offset vector"); } @Override public FieldVector getDataVector() { return vector; } @Override public void setInitialCapacity(int numRecords) { offsetAllocationSizeInBytes = (numRecords + 1) * OFFSET_WIDTH; if (vector instanceof BaseFixedWidthVector || vector instanceof BaseVariableWidthVector) { vector.setInitialCapacity(numRecords * RepeatedValueVector.DEFAULT_REPEAT_PER_RECORD); } else { vector.setInitialCapacity(numRecords); } } /** * Specialized version of setInitialCapacity() for ListVector. This is * used by some callers when they want to explicitly control and be * conservative about memory allocated for inner data vector. This is * very useful when we are working with memory constraints for a query * and have a fixed amount of memory reserved for the record batch. In * such cases, we are likely to face OOM or related problems when * we reserve memory for a record batch with value count x and * do setInitialCapacity(x) such that each vector allocates only * what is necessary and not the default amount but the multiplier * forces the memory requirement to go beyond what was needed. * * @param numRecords value count * @param density density of ListVector. Density is the average size of * list per position in the List vector. For example, a * density value of 10 implies each position in the list * vector has a list of 10 values. * A density value of 0.1 implies out of 10 positions in * the list vector, 1 position has a list of size 1 and * remaining positions are null (no lists) or empty lists. * This helps in tightly controlling the memory we provision * for inner data vector. */ @Override public void setInitialCapacity(int numRecords, double density) { if ((numRecords * density) >= Integer.MAX_VALUE) { throw new OversizedAllocationException("Requested amount of memory is more than max allowed"); } offsetAllocationSizeInBytes = (numRecords + 1) * OFFSET_WIDTH; int innerValueCapacity = Math.max((int) (numRecords * density), 1); if (vector instanceof DensityAwareVector) { ((DensityAwareVector) vector).setInitialCapacity(innerValueCapacity, density); } else { vector.setInitialCapacity(innerValueCapacity); } } @Override public int getValueCapacity() { final int offsetValueCapacity = Math.max(getOffsetBufferValueCapacity() - 1, 0); if (vector == DEFAULT_DATA_VECTOR) { return offsetValueCapacity; } return Math.min(vector.getValueCapacity(), offsetValueCapacity); } protected int getOffsetBufferValueCapacity() { return capAtMaxInt(offsetBuffer.capacity() / OFFSET_WIDTH); } @Override public int getBufferSize() { if (valueCount == 0) { return 0; } return ((valueCount + 1) * OFFSET_WIDTH) + vector.getBufferSize(); } @Override public int getBufferSizeFor(int valueCount) { if (valueCount == 0) { return 0; } int innerVectorValueCount = offsetBuffer.getInt(valueCount * OFFSET_WIDTH); return ((valueCount + 1) * OFFSET_WIDTH) + vector.getBufferSizeFor(innerVectorValueCount); } @Override public Iterator<ValueVector> iterator() { return Collections.<ValueVector>singleton(getDataVector()).iterator(); } @Override public void clear() { offsetBuffer = releaseBuffer(offsetBuffer); vector.clear(); valueCount = 0; super.clear(); } @Override public void reset() { offsetBuffer.setZero(0, offsetBuffer.capacity()); vector.reset(); valueCount = 0; } @Override public ArrowBuf[] getBuffers(boolean clear) { final ArrowBuf[] buffers; if (getBufferSize() == 0) { buffers = new ArrowBuf[0]; } else { List<ArrowBuf> list = new ArrayList<>(); list.add(offsetBuffer); list.addAll(Arrays.asList(vector.getBuffers(false))); buffers = list.toArray(new ArrowBuf[list.size()]); } if (clear) { for (ArrowBuf buffer : buffers) { buffer.getReferenceManager().retain(); } clear(); } return buffers; } /** * Get value indicating if inner vector is set. * @return 1 if inner vector is explicitly set via #addOrGetVector else 0 */ public int size() { return vector == DEFAULT_DATA_VECTOR ? 0 : 1; } /** * Initialize the data vector (and execute callback) if it hasn't already been done, * returns the data vector. */ public <T extends ValueVector> AddOrGetResult<T> addOrGetVector(FieldType fieldType) { boolean created = false; if (vector instanceof NullVector) { vector = fieldType.createNewSingleVector(defaultDataVectorName, allocator, callBack); // returned vector must have the same field created = true; if (callBack != null && // not a schema change if changing from ZeroVector to ZeroVector (fieldType.getType().getTypeID() != ArrowTypeID.Null)) { callBack.doWork(); } } if (vector.getField().getType().getTypeID() != fieldType.getType().getTypeID()) { final String msg = String.format("Inner vector type mismatch. Requested type: [%s], actual type: [%s]", fieldType.getType().getTypeID(), vector.getField().getType().getTypeID()); throw new SchemaChangeRuntimeException(msg); } return new AddOrGetResult<>((T) vector, created); } protected void replaceDataVector(FieldVector v) { vector.clear(); vector = v; } @Override public int getValueCount() { return valueCount; } /* returns the value count for inner data vector for this list vector */ public int getInnerValueCount() { return vector.getValueCount(); } /** Returns the value count for inner data vector at a particular index. */ public int getInnerValueCountAt(int index) { return offsetBuffer.getInt((index + 1) * OFFSET_WIDTH) - offsetBuffer.getInt(index * OFFSET_WIDTH); } /** Return if value at index is null (this implementation is always false). */ public boolean isNull(int index) { return false; } /** Return if value at index is empty (this implementation is always false). */ public boolean isEmpty(int index) { return false; } /** Starts a new repeated value. */ public int startNewValue(int index) { while (index >= getOffsetBufferValueCapacity()) { reallocOffsetBuffer(); } int offset = offsetBuffer.getInt(index * OFFSET_WIDTH); offsetBuffer.setInt((index + 1) * OFFSET_WIDTH, offset); setValueCount(index + 1); return offset; } /** Preallocates the number of repeated values. */ public void setValueCount(int valueCount) { this.valueCount = valueCount; while (valueCount > getOffsetBufferValueCapacity()) { reallocOffsetBuffer(); } final int childValueCount = valueCount == 0 ? 0 : offsetBuffer.getInt(valueCount * OFFSET_WIDTH); vector.setValueCount(childValueCount); } }
/* * Copyright 2011 Thingtrack, S.L. * * 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.thingtrack.konekti.domain; /* * #%L * Konekti Domain Layer * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Thingtrack s.l. * %% * 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. * #L% */ import java.util.List; import java.io.Serializable; import java.util.Date; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Entity class * <p> * Represents the any employee in the organization * <p> * @author Thingtrack S.L. * */ @SuppressWarnings("serial") @Entity @Table(name="EMPLOYEE_AGENT") @AttributeOverrides({ @AttributeOverride(name="agentId", column=@Column(name="EMPLOYEE_AGENT_ID")) }) public class EmployeeAgent extends Agent implements Serializable { /** * Surname */ @Column(name="SURNAME", length=64) private String surname; /** * Shortname */ @Column(name="SHORTNAME", length=64) private String shortname; /** * Unique worknumber */ @Column(name="WORKNUMBER", unique=true, length=64) private String workNumber; /** * National */ @Column(name="NIF", length=64) private String nif; /** * Title */ @Column(name="TITTLE", length=32) private String tittle; /** * Working phone number */ @Column(name="WORK_MOBILE", length=32) private String workMobile; /** * Seniority * */ @Column(name="SENIORITY") @Temporal(TemporalType.DATE) private Date seniority; /** * Birthday */ @Column(name="BIRTHDAY") @Temporal(TemporalType.DATE) private Date birthday; /** * {@link EmployeeAgentType} * <p><ul> * <li>MANAGER * <li>OFFICER * <li>WORKER * <li>DRIVER * <ul><p> */ @ManyToOne @JoinColumn(name="EMPLOYEE_AGENT_TYPE_ID", nullable=false) private EmployeeAgentType employeeAgentType; /** * @deprecated */ @OneToMany(mappedBy="driver") private List<OfferRequestLine> offerRequestLines; /** * {@link Organization} owner */ @ManyToOne @JoinColumn(name = "ORGANIZATION_ID", nullable = false) private Organization organization; /** * {@link EmployeeAgentStatus} * <p><ul> * <li>ACTIVE * <li>DECLINE * <ul><p> */ @ManyToOne @JoinColumn(name="EMPLOYEE_AGENT_STATUS_ID", nullable=false) private EmployeeAgentStatus employeeAgentStatus; public enum EMPLOYEE_AGENT_TYPE{ MANAGER, OFFICER, WORKER, DRIVER } public enum STATUS { ACTIVE, DECLINE } /** * @param workNumber the workNumber to set */ public void setWorkNumber(String workNumber) { this.workNumber = workNumber; } /** * @return the workNumber */ public String getWorkNumber() { return workNumber; } /** * @param employeeAgentType the employeeAgentType to set */ public void setEmployeeAgentType(EmployeeAgentType employeeAgentType) { this.employeeAgentType = employeeAgentType; } /** * @return the employeeAgentType */ public EmployeeAgentType getEmployeeAgentType() { return employeeAgentType; } /** * @param nif the nif to set */ public void setNif(String nif) { this.nif = nif; } /** * @return the nif */ public String getNif() { return nif; } /** * @param tittle the tittle to set */ public void setTittle(String tittle) { this.tittle = tittle; } /** * @return the tittle */ public String getTittle() { return tittle; } /** * @param workMobile the workMobile to set */ public void setWorkMobile(String workMobile) { this.workMobile = workMobile; } /** * @return the workMobile */ public String getWorkMobile() { return workMobile; } /** * @param employeeAgentStatus the employeeAgentStatus to set */ public void setEmployeeAgentStatus(EmployeeAgentStatus employeeAgentStatus) { this.employeeAgentStatus = employeeAgentStatus; } /** * @return the employeeAgentStatus */ public EmployeeAgentStatus getEmployeeAgentStatus() { return employeeAgentStatus; } /** * @param seniority the seniority to set */ public void setSeniority(Date seniority) { this.seniority = seniority; } /** * @return the seniority */ public Date getSeniority() { return seniority; } /** * @param shortname the shortname to set */ public void setShortname(String shortname) { this.shortname = shortname; } /** * @return the shortname */ public String getShortname() { return shortname; } /** * @param offerRequestLines the offerRequestLines to set */ public void setOfferRequestLines(List<OfferRequestLine> offerRequestLines) { this.offerRequestLines = offerRequestLines; } /** * @return the offerRequestLines */ public List<OfferRequestLine> getOfferRequestLines() { return offerRequestLines; } /** * @return the birthday */ public Date getBirthday() { return birthday; } /** * @param birthday the birthday to set */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the organization */ public Organization getOrganization() { return organization; } /** * @param organization the organization to set */ public void setOrganization(Organization organization) { this.organization = organization; } }
package sedgewick; /************************************************************************* * Compilation: javac StdArrayIO.java * Execution: java StdArrayIO < input.txt * * A library for reading in 1D and 2D arrays of integers, doubles, * and booleans from standard input and printing them out to * standard output. * * % more tinyDouble1D.txt * 4 * .000 .246 .222 -.032 * * % more tinyDouble2D.txt * 4 3 * .000 .270 .000 * .246 .224 -.036 * .222 .176 .0893 * -.032 .739 .270 * * % more tinyBoolean2D.txt * 4 3 * 1 1 0 * 0 0 0 * 0 1 1 * 1 1 1 * * % cat tinyDouble1D.txt tinyDouble2D.txt tinyBoolean2D.txt | java StdArrayIO * 4 * 0.00000 0.24600 0.22200 -0.03200 * * 4 3 * 0.00000 0.27000 0.00000 * 0.24600 0.22400 -0.03600 * 0.22200 0.17600 0.08930 * 0.03200 0.73900 0.27000 * * 4 3 * 1 1 0 * 0 0 0 * 0 1 1 * 1 1 1 * *************************************************************************/ /** * <i>Standard array IO</i>. This class provides methods for reading * in 1D and 2D arrays from standard input and printing out to * standard output. * <p> * For additional documentation, see * <a href="http://introcs.cs.princeton.edu/22libary">Section 2.2</a> of * <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> * by Robert Sedgewick and Kevin Wayne. */ public class StdArrayIO { /** * Read in and return an array of doubles from standard input. */ public static double[] readDouble1D() { int N = StdIn.readInt(); double[] a = new double[N]; for (int i = 0; i < N; i++) { a[i] = StdIn.readDouble(); } return a; } /** * Print an array of doubles to standard output. */ public static void print(double[] a) { int N = a.length; StdOut.println(N); for (int i = 0; i < N; i++) { StdOut.printf("%9.5f ", a[i]); } StdOut.println(); } /** * Read in and return an M-by-N array of doubles from standard input. */ public static double[][] readDouble2D() { int M = StdIn.readInt(); int N = StdIn.readInt(); double[][] a = new double[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a[i][j] = StdIn.readDouble(); } } return a; } /** * Print the M-by-N array of doubles to standard output. */ public static void print(double[][] a) { int M = a.length; int N = a[0].length; StdOut.println(M + " " + N); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { StdOut.printf("%9.5f ", a[i][j]); } StdOut.println(); } } /** * Read in and return an array of ints from standard input. */ public static int[] readInt1D() { int N = StdIn.readInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = StdIn.readInt(); } return a; } /** * Print an array of ints to standard output. */ public static void print(int[] a) { int N = a.length; StdOut.println(N); for (int i = 0; i < N; i++) { StdOut.printf("%9d ", a[i]); } StdOut.println(); } /** * Read in and return an M-by-N array of ints from standard input. */ public static int[][] readInt2D() { int M = StdIn.readInt(); int N = StdIn.readInt(); int[][] a = new int[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a[i][j] = StdIn.readInt(); } } return a; } /** * Print the M-by-N array of ints to standard output. */ public static void print(int[][] a) { int M = a.length; int N = a[0].length; StdOut.println(M + " " + N); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { StdOut.printf("%9d ", a[i][j]); } StdOut.println(); } } /** * Read in and return an array of booleans from standard input. */ public static boolean[] readBoolean1D() { int N = StdIn.readInt(); boolean[] a = new boolean[N]; for (int i = 0; i < N; i++) { a[i] = StdIn.readBoolean(); } return a; } /** * Print an array of booleans to standard output. */ public static void print(boolean[] a) { int N = a.length; StdOut.println(N); for (int i = 0; i < N; i++) { if (a[i]) StdOut.print("1 "); else StdOut.print("0 "); } StdOut.println(); } /** * Read in and return an M-by-N array of booleans from standard input. */ public static boolean[][] readBoolean2D() { int M = StdIn.readInt(); int N = StdIn.readInt(); boolean[][] a = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a[i][j] = StdIn.readBoolean(); } } return a; } /** * Print the M-by-N array of booleans to standard output. */ public static void print(boolean[][] a) { int M = a.length; int N = a[0].length; StdOut.println(M + " " + N); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (a[i][j]) StdOut.print("1 "); else StdOut.print("0 "); } StdOut.println(); } } /** * Test client. */ public static void main(String[] args) { // read and print an array of doubles double[] a = StdArrayIO.readDouble1D(); StdArrayIO.print(a); StdOut.println(); // read and print a matrix of doubles double[][] b = StdArrayIO.readDouble2D(); StdArrayIO.print(b); StdOut.println(); // read and print a matrix of doubles boolean[][] d = StdArrayIO.readBoolean2D(); StdArrayIO.print(d); StdOut.println(); } }
/* Derby - Class org.apache.derby.impl.sql.execute.TemporaryRowHolderImpl 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.derby.impl.sql.execute; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.sql.execute.CursorResultSet; import org.apache.derby.iapi.sql.execute.ExecRow; import org.apache.derby.iapi.sql.execute.TemporaryRowHolder; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.ResultDescription; import org.apache.derby.iapi.store.access.ConglomerateController; import org.apache.derby.iapi.store.access.ScanController; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.types.RowLocation; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.types.SQLRef; import org.apache.derby.iapi.types.SQLLongint; import java.util.Properties; /** * This is a class that is used to temporarily * (non-persistently) hold rows that are used in * language execution. It will store them in an * array, or a temporary conglomerate, depending * on the number of rows. * <p> * It is used for deferred DML processing. * */ class TemporaryRowHolderImpl implements TemporaryRowHolder { public static final int DEFAULT_OVERFLOWTHRESHOLD = 5; protected static final int STATE_UNINIT = 0; protected static final int STATE_INSERT = 1; protected static final int STATE_DRAIN = 2; protected ExecRow[] rowArray; protected int lastArraySlot; private int numRowsIn; protected int state = STATE_UNINIT; private long CID; private boolean conglomCreated; private ConglomerateController cc; private Properties properties; private ScanController scan; private ResultDescription resultDescription; /** Activation object with local state information. */ Activation activation; private boolean isUniqueStream; /* beetle 3865 updateable cursor use index. A virtual memory heap is a heap that has in-memory * part to get better performance, less overhead. No position index needed. We read from and write * to the in-memory part as much as possible. And we can insert after we start retrieving results. * Could be used for other things too. */ private boolean isVirtualMemHeap; private boolean uniqueIndexCreated; private boolean positionIndexCreated; private long uniqueIndexConglomId; private long positionIndexConglomId; private ConglomerateController uniqueIndex_cc; private ConglomerateController positionIndex_cc; private DataValueDescriptor[] uniqueIndexRow = null; private DataValueDescriptor[] positionIndexRow = null; private RowLocation destRowLocation; //row location in the temporary conglomerate private SQLLongint position_sqllong; /** * Uses the default overflow to * a conglomerate threshold (5). * * @param activation the activation * @param properties the properties of the original table. Used * to help the store use optimal page size, etc. * @param resultDescription the result description. Relevant for the getResultDescription * call on the result set returned by getResultSet. May be null */ public TemporaryRowHolderImpl ( Activation activation, Properties properties, ResultDescription resultDescription ) { this(activation, properties, resultDescription, DEFAULT_OVERFLOWTHRESHOLD, false, false); } /** * Uses the default overflow to * a conglomerate threshold (5). * * @param activation the activation * @param properties the properties of the original table. Used * to help the store use optimal page size, etc. * @param resultDescription the result description. Relevant for the getResultDescription * call on the result set returned by getResultSet. May be null * @param isUniqueStream - true , if it has to be temporary row holder unique stream */ public TemporaryRowHolderImpl ( Activation activation, Properties properties, ResultDescription resultDescription, boolean isUniqueStream ) { this(activation, properties, resultDescription, 1, isUniqueStream, false); } /** * Create a temporary row holder with the defined overflow to conglom * * @param activation the activation * @param properties the properties of the original table. Used * to help the store use optimal page size, etc. * @param resultDescription the result description. Relevant for the getResultDescription * call on the result set returned by getResultSet. May be null * @param overflowToConglomThreshold on an attempt to insert * this number of rows, the rows will be put * into a temporary conglomerate. */ public TemporaryRowHolderImpl ( Activation activation, Properties properties, ResultDescription resultDescription, int overflowToConglomThreshold, boolean isUniqueStream, boolean isVirtualMemHeap ) { if (SanityManager.DEBUG) { if (overflowToConglomThreshold <= 0) { SanityManager.THROWASSERT("It is assumed that "+ "the overflow threshold is > 0. "+ "If you you need to change this you have to recode some of "+ "this class."); } } this.activation = activation; this.properties = properties; this.resultDescription = resultDescription; this.isUniqueStream = isUniqueStream; this.isVirtualMemHeap = isVirtualMemHeap; rowArray = new ExecRow[overflowToConglomThreshold]; lastArraySlot = -1; } /* Avoid materializing a stream just because it goes through a temp table. * It is OK to have a stream in the temp table (in memory or spilled to * disk). The assumption is that one stream does not appear in two rows. * For "update", one stream can be in two rows and the materialization is * done in UpdateResultSet. Note to future users of this class who may * insert a stream into this temp holder: * (1) As mentioned above, one un-materialized stream can't appear in two * rows; you need to objectify it first otherwise. * (2) If you need to retrieve an un-materialized stream more than once * from the temp holder, you need to either materialize the stream * the first time, or, if there's a memory constraint, in the first * time create a RememberBytesInputStream with the byte holder being * BackingStoreByteHolder, finish it, and reset it after usage. * A third option is to create a stream clone, but this requires that * the container handles are kept open until the streams have been * drained. * * Beetle 4896. */ private ExecRow cloneRow(ExecRow inputRow) { DataValueDescriptor[] cols = inputRow.getRowArray(); int ncols = cols.length; ExecRow cloned = ((ValueRow) inputRow).cloneMe(); for (int i = 0; i < ncols; i++) { if (cols[i] != null) { /* Rows are 1-based, cols[] is 0-based */ cloned.setColumn(i + 1, cols[i].cloneHolder()); } } if (inputRow instanceof IndexValueRow) return new IndexValueRow(cloned); else return cloned; } /** * Insert a row * * @param inputRow the row to insert * * @exception StandardException on error */ public void insert(ExecRow inputRow) throws StandardException { if (SanityManager.DEBUG) { if(!isUniqueStream && !isVirtualMemHeap) SanityManager.ASSERT(state != STATE_DRAIN, "you cannot insert rows after starting to drain"); } if (! isVirtualMemHeap) state = STATE_INSERT; if(uniqueIndexCreated) { if(isRowAlreadyExist(inputRow)) return; } numRowsIn++; if (lastArraySlot + 1 < rowArray.length) { rowArray[++lastArraySlot] = cloneRow(inputRow); //In case of unique stream we push every thing into the // conglomerates for time being, we keep one row in the array for // the template. if (!isUniqueStream) { return; } } if (!conglomCreated) { TransactionController tc = activation.getTransactionController(); // TODO-COLLATE, I think collation needs to get set always correctly // but did see what to get collate id when there was no result // description. The problem comes if row holder is used to stream // row to temp disk, then row is read from disk using an interface // where store creates the DataValueDescriptor template itself, // and subsquently the returned column is used for some sort of // comparison. Also could be a problem is reader of tempoary // table uses qualifiers, that would result in comparisons internal // to store. I believe the below impl is incomplete - either // it should always be default, or real collate_ids should be // passed in. // null collate_ids in createConglomerate call indicates to use all // default collate ids. int collation_ids[] = null; /* TODO-COLLATE - if we could count on resultDescription I think the following would work. if (resultDescription != null) { // init collation id info from resultDescription for create call collation_ids = new int[resultDescription.getColumnCount()]; for (int i = 0; i < collation_ids.length; i++) { collation_ids[i] = resultDescription.getColumnDescriptor( i + 1).getType().getCollationType(); } } */ /* ** Create the conglomerate with the template row. */ CID = tc.createConglomerate( "heap", inputRow.getRowArray(), null, //column sort order - not required for heap collation_ids, properties, TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT); conglomCreated = true; cc = tc.openConglomerate(CID, false, TransactionController.OPENMODE_FORUPDATE, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE); if(isUniqueStream) destRowLocation = cc.newRowLocationTemplate(); } int status = 0; if(isUniqueStream) { cc.insertAndFetchLocation(inputRow.getRowArray(), destRowLocation); insertToPositionIndex(numRowsIn -1, destRowLocation); //create the unique index based on input row ROW Location if(!uniqueIndexCreated) isRowAlreadyExist(inputRow); }else { status = cc.insert(inputRow.getRowArray()); if (isVirtualMemHeap) state = STATE_INSERT; } if (SanityManager.DEBUG) { if (status != 0) { SanityManager.THROWASSERT("got funky status ("+status+") back from "+ "ConglomerateConstroller.insert()"); } } } /** * Maintain an unique index based on the input row's row location in the * base table, this index make sures that we don't insert duplicate rows * into the temporary heap. * @param inputRow the row we are inserting to temporary row holder * @exception StandardException on error */ private boolean isRowAlreadyExist(ExecRow inputRow) throws StandardException { DataValueDescriptor rlColumn; RowLocation baseRowLocation; rlColumn = inputRow.getColumn(inputRow.nColumns()); if(CID!=0 && rlColumn instanceof SQLRef) { baseRowLocation = (RowLocation) (rlColumn).getObject(); if(!uniqueIndexCreated) { TransactionController tc = activation.getTransactionController(); int numKeys = 2; uniqueIndexRow = new DataValueDescriptor[numKeys]; uniqueIndexRow[0] = baseRowLocation; uniqueIndexRow[1] = baseRowLocation; Properties props = makeIndexProperties(uniqueIndexRow, CID); uniqueIndexConglomId = tc.createConglomerate( "BTREE", uniqueIndexRow, null, null, // no collation needed for index on row locations. props, (TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT)); uniqueIndex_cc = tc.openConglomerate( uniqueIndexConglomId, false, TransactionController.OPENMODE_FORUPDATE, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE); uniqueIndexCreated = true; } uniqueIndexRow[0] = baseRowLocation; uniqueIndexRow[1] = baseRowLocation; // Insert the row into the secondary index. int status; if ((status = uniqueIndex_cc.insert(uniqueIndexRow))!= 0) { if(status == ConglomerateController.ROWISDUPLICATE) { return true ; // okay; we don't insert duplicates } else { if (SanityManager.DEBUG) { if (status != 0) { SanityManager.THROWASSERT("got funky status ("+status+") back from "+ "Unique Index insert()"); } } } } } return false; } /** * Maintain an index that will allow us to read from the * temporary heap in the order we inserted. * @param position - the number of the row we are inserting into heap * @param rl the row to Location in the temporary heap * @exception StandardException on error */ private void insertToPositionIndex(int position, RowLocation rl ) throws StandardException { if(!positionIndexCreated) { TransactionController tc = activation.getTransactionController(); int numKeys = 2; position_sqllong = new SQLLongint(); positionIndexRow = new DataValueDescriptor[numKeys]; positionIndexRow[0] = position_sqllong; positionIndexRow[1] = rl; Properties props = makeIndexProperties(positionIndexRow, CID); positionIndexConglomId = tc.createConglomerate( "BTREE", positionIndexRow, null, null, // no collation needed for index on row locations. props, (TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT)); positionIndex_cc = tc.openConglomerate( positionIndexConglomId, false, TransactionController.OPENMODE_FORUPDATE, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE); positionIndexCreated = true; } position_sqllong.setValue(position); positionIndexRow[0] = position_sqllong; positionIndexRow[1] = rl; //insert the row location to position index positionIndex_cc.insert(positionIndexRow); } /** * Get a result set for scanning what has been inserted * so far. * * @return a result set to use */ public CursorResultSet getResultSet() { state = STATE_DRAIN; TransactionController tc = activation.getTransactionController(); if(isUniqueStream) { return new TemporaryRowHolderResultSet(tc, rowArray, resultDescription, isVirtualMemHeap, true, positionIndexConglomId, this); } else { return new TemporaryRowHolderResultSet(tc, rowArray, resultDescription, isVirtualMemHeap, this); } } /** * Purge the row holder of all its rows. * Resets the row holder so that it can * accept new inserts. A cheap way to * recycle a row holder. * * @exception StandardException on error */ public void truncate() throws StandardException { close(); if (SanityManager.DEBUG) { SanityManager.ASSERT(lastArraySlot == -1); SanityManager.ASSERT(state == STATE_UNINIT); SanityManager.ASSERT(!conglomCreated); SanityManager.ASSERT(CID == 0); } for (int i = 0; i < rowArray.length; i++) { rowArray[i] = null; } numRowsIn = 0; } /** * Accessor to get the id of the temporary conglomerate. Temporary * conglomerates have negative ids. An id equal to zero means that no * temporary conglomerate has been created. * @return Conglomerate ID of temporary conglomerate */ public long getTemporaryConglomId() { if (SanityManager.DEBUG) { SanityManager.ASSERT(CID == 0 && !conglomCreated || CID < 0 && conglomCreated); } return CID; } public long getPositionIndexConglomId() { return positionIndexConglomId; } private Properties makeIndexProperties(DataValueDescriptor[] indexRowArray, long conglomId ) throws StandardException { int nCols = indexRowArray.length; Properties props = new Properties(); props.put("allowDuplicates", "false"); // all columns form the key, (currently) required props.put("nKeyFields", String.valueOf(nCols)); props.put("nUniqueColumns", String.valueOf(nCols-1)); props.put("rowLocationColumn", String.valueOf(nCols-1)); props.put("baseConglomerateId", String.valueOf(conglomId)); return props; } public void setRowHolderTypeToUniqueStream() { isUniqueStream = true; } /** * Clean up * * @exception StandardException on error */ public void close() throws StandardException { if (scan != null) { scan.close(); scan = null; } if (cc != null) { cc.close(); cc = null; } if (uniqueIndex_cc != null) { uniqueIndex_cc.close(); uniqueIndex_cc = null; } if (positionIndex_cc != null) { positionIndex_cc.close(); positionIndex_cc = null; } TransactionController tc = activation.getTransactionController(); if (uniqueIndexCreated) { tc.dropConglomerate(uniqueIndexConglomId); uniqueIndexCreated = false; } if (positionIndexCreated) { tc.dropConglomerate(positionIndexConglomId); positionIndexCreated = false; } if (conglomCreated) { tc.dropConglomerate(CID); conglomCreated = false; CID = 0; } else { if (SanityManager.DEBUG) { SanityManager.ASSERT(CID == 0, "CID(" + CID + ")==0"); } } state = STATE_UNINIT; lastArraySlot = -1; } }
package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringOrListParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.param.TokenAndListParam; import ca.uhn.fhir.rest.param.TokenOrListParam; import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.param.TokenParamModifier; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2016may.hapi.rest.server.ServerConformanceProvider; import org.hl7.fhir.dstu2016may.model.Conformance; import org.hl7.fhir.dstu2016may.model.IdType; import org.hl7.fhir.dstu2016may.model.OperationDefinition; import org.hl7.fhir.dstu2016may.model.Parameters; import org.hl7.fhir.dstu2016may.model.Patient; import org.hl7.fhir.dstu2016may.model.StringType; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.stringContainsInOrder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class OperationServerWithSearchParamTypesDstu2_1Test { private static CloseableHttpClient ourClient; private static FhirContext ourCtx; private static String ourLastMethod; private static List<StringOrListParam> ourLastParamValStr; private static List<TokenOrListParam> ourLastParamValTok; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerWithSearchParamTypesDstu2_1Test.class); private static int ourPort; private static Server ourServer; @BeforeEach public void before() { ourLastMethod = ""; ourLastParamValStr = null; ourLastParamValTok = null; } private HttpServletRequest createHttpServletRequest() { HttpServletRequest req = mock(HttpServletRequest.class); when(req.getRequestURI()).thenReturn("/FhirStorm/fhir/Patient/_search"); when(req.getServletPath()).thenReturn("/fhir"); when(req.getRequestURL()).thenReturn(new StringBuffer().append("http://fhirstorm.dyndns.org:8080/FhirStorm/fhir/Patient/_search")); when(req.getContextPath()).thenReturn("/FhirStorm"); return req; } private ServletConfig createServletConfig() { ServletConfig sc = mock(ServletConfig.class); when(sc.getServletContext()).thenReturn(null); return sc; } @Test public void testAndListWithParameters() throws Exception { Parameters p = new Parameters(); p.addParameter().setName("valstr").setValue(new StringType("VALSTR1A,VALSTR1B")); p.addParameter().setName("valstr").setValue(new StringType("VALSTR2A,VALSTR2B")); p.addParameter().setName("valtok").setValue(new StringType("VALTOK1A|VALTOK1B")); p.addParameter().setName("valtok").setValue(new StringType("VALTOK2A|VALTOK2B")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$andlist"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(2, ourLastParamValStr.size()); assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); assertEquals(2, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("type $orlist", ourLastMethod); } @Test public void testEscapedOperationName() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/%24andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(2, ourLastParamValStr.size()); } @Test public void testAndListWithUrl() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(2, ourLastParamValStr.size()); assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); assertEquals(2, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("type $orlist", ourLastMethod); } @Test public void testGenerateConformance() throws Exception { RestfulServer rs = new RestfulServer(ourCtx); rs.setProviders(new PatientProvider()); ServerConformanceProvider sc = new ServerConformanceProvider(rs); rs.setServerConformanceProvider(sc); rs.init(createServletConfig()); Conformance conformance = sc.getServerConformance(createHttpServletRequest(), createRequestDetails(rs)); String conf = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(conformance); ourLog.info(conf); //@formatter:off assertThat(conf, stringContainsInOrder( "<type value=\"Patient\"/>", "<operation>", "<name value=\"andlist\"/>", "</operation>" )); assertThat(conf, stringContainsInOrder( "<type value=\"Patient\"/>", "<operation>", "<name value=\"nonrepeating\"/>" )); assertThat(conf, stringContainsInOrder( "<type value=\"Patient\"/>", "<operation>", "<name value=\"orlist\"/>" )); //@formatter:on /* * Check the operation definitions themselves */ OperationDefinition andListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient--andlist"), createRequestDetails(rs)); String def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(andListDef); ourLog.info(def); //@formatter:off assertThat(def, stringContainsInOrder( "<parameter>", "<name value=\"valtok\"/>", "<use value=\"in\"/>", "<min value=\"0\"/>", "<max value=\"10\"/>", "<type value=\"string\"/>", "<searchType value=\"token\"/>", "</parameter>" )); //@formatter:on andListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient--andlist-withnomax"), createRequestDetails(rs)); def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(andListDef); ourLog.info(def); //@formatter:off assertThat(def, stringContainsInOrder( "<parameter>", "<name value=\"valtok\"/>", "<use value=\"in\"/>", "<min value=\"0\"/>", "<max value=\"*\"/>", "<type value=\"string\"/>", "<searchType value=\"token\"/>", "</parameter>" )); //@formatter:on OperationDefinition orListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient--orlist"), createRequestDetails(rs)); def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(orListDef); ourLog.info(def); //@formatter:off assertThat(def, stringContainsInOrder( "<parameter>", "<name value=\"valtok\"/>", "<use value=\"in\"/>", "<min value=\"0\"/>", "<max value=\"10\"/>", "<type value=\"string\"/>", "<searchType value=\"token\"/>", "</parameter>" )); //@formatter:on orListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient--orlist-withnomax"), createRequestDetails(rs)); def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(orListDef); ourLog.info(def); //@formatter:off assertThat(def, stringContainsInOrder( "<parameter>", "<name value=\"valtok\"/>", "<use value=\"in\"/>", "<min value=\"0\"/>", "<max value=\"*\"/>", "<type value=\"string\"/>", "<searchType value=\"token\"/>", "</parameter>" )); //@formatter:on } @Test public void testNonRepeatingWithParams() throws Exception { Parameters p = new Parameters(); p.addParameter().setName("valstr").setValue(new StringType("VALSTR")); p.addParameter().setName("valtok").setValue(new StringType("VALTOKA|VALTOKB")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$nonrepeating"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(1, ourLastParamValStr.size()); assertEquals(1, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals(1, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOKA", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOKB", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("type $nonrepeating", ourLastMethod); } @Test public void testNonRepeatingWithUrl() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr=VALSTR&valtok=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(1, ourLastParamValStr.size()); assertEquals(1, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals(1, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOKA", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOKB", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("type $nonrepeating", ourLastMethod); } @Test public void testNonRepeatingWithUrlQualified() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr:exact=VALSTR&valtok:not=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(1, ourLastParamValStr.size()); assertEquals(1, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertTrue(ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).isExact()); assertEquals(1, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOKA", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOKB", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals(TokenParamModifier.NOT, ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getModifier()); assertEquals("type $nonrepeating", ourLastMethod); } @Test public void testOrListWithParameters() throws Exception { Parameters p = new Parameters(); p.addParameter().setName("valstr").setValue(new StringType("VALSTR1A,VALSTR1B")); p.addParameter().setName("valstr").setValue(new StringType("VALSTR2A,VALSTR2B")); p.addParameter().setName("valtok").setValue(new StringType("VALTOK1A|VALTOK1B")); p.addParameter().setName("valtok").setValue(new StringType("VALTOK2A|VALTOK2B")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$orlist"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(2, ourLastParamValStr.size()); assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); assertEquals(2, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("type $orlist", ourLastMethod); } @Test public void testOrListWithUrl() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$orlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); String response = IOUtils.toString(status.getEntity().getContent()); ourLog.info(response); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(2, ourLastParamValStr.size()); assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); assertEquals(2, ourLastParamValTok.size()); assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); assertEquals("type $orlist", ourLastMethod); } @AfterAll public static void afterClassClearContext() throws Exception { JettyUtil.closeServer(ourServer); TestUtil.clearAllStaticFieldsForUnitTest(); } @BeforeAll public static void beforeClass() throws Exception { ourCtx = FhirContext.forDstu2_1(); ourServer = new Server(0); ServletHandler proxyHandler = new ServletHandler(); RestfulServer servlet = new RestfulServer(ourCtx); servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); servlet.setFhirContext(ourCtx); servlet.setResourceProviders(new PatientProvider()); ServletHolder servletHolder = new ServletHolder(servlet); proxyHandler.addServletWithMapping(servletHolder, "/*"); ourServer.setHandler(proxyHandler); JettyUtil.startServer(ourServer); ourPort = JettyUtil.getPortForStartedServer(ourServer); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionManager(connectionManager); ourClient = builder.build(); } public static class PatientProvider implements IResourceProvider { @Operation(name = "$andlist", idempotent = true) public Parameters andlist( //@formatter:off @OperationParam(name="valstr", max=10) StringAndListParam theValStr, @OperationParam(name="valtok", max=10) TokenAndListParam theValTok //@formatter:on ) { ourLastMethod = "type $orlist"; ourLastParamValStr = theValStr.getValuesAsQueryTokens(); ourLastParamValTok = theValTok.getValuesAsQueryTokens(); return createEmptyParams(); } @Operation(name = "$andlist-withnomax", idempotent = true) public Parameters andlistWithNoMax( //@formatter:off @OperationParam(name="valstr") StringAndListParam theValStr, @OperationParam(name="valtok") TokenAndListParam theValTok //@formatter:on ) { ourLastMethod = "type $orlist"; ourLastParamValStr = theValStr.getValuesAsQueryTokens(); ourLastParamValTok = theValTok.getValuesAsQueryTokens(); return createEmptyParams(); } /** * Just so we have something to return */ private Parameters createEmptyParams() { Parameters retVal = new Parameters(); retVal.setId("100"); return retVal; } @Override public Class<? extends IBaseResource> getResourceType() { return Patient.class; } @Operation(name = "$nonrepeating", idempotent = true) public Parameters nonrepeating( //@formatter:off @OperationParam(name="valstr") StringParam theValStr, @OperationParam(name="valtok") TokenParam theValTok //@formatter:on ) { ourLastMethod = "type $nonrepeating"; ourLastParamValStr = Collections.singletonList(new StringOrListParam().add(theValStr)); ourLastParamValTok = Collections.singletonList(new TokenOrListParam().add(theValTok)); return createEmptyParams(); } @Operation(name = "$orlist", idempotent = true) public Parameters orlist( //@formatter:off @OperationParam(name="valstr", max=10) List<StringOrListParam> theValStr, @OperationParam(name="valtok", max=10) List<TokenOrListParam> theValTok //@formatter:on ) { ourLastMethod = "type $orlist"; ourLastParamValStr = theValStr; ourLastParamValTok = theValTok; return createEmptyParams(); } @Operation(name = "$orlist-withnomax", idempotent = true) public Parameters orlistWithNoMax( //@formatter:off @OperationParam(name="valstr") List<StringOrListParam> theValStr, @OperationParam(name="valtok") List<TokenOrListParam> theValTok //@formatter:on ) { ourLastMethod = "type $orlist"; ourLastParamValStr = theValStr; ourLastParamValTok = theValTok; return createEmptyParams(); } } private RequestDetails createRequestDetails(RestfulServer theServer) { ServletRequestDetails retVal = new ServletRequestDetails(null); retVal.setServer(theServer); return retVal; } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.psi; import com.intellij.JavaTestUtil; import com.intellij.psi.*; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase; public class ConstantValuesTest extends LightJavaCodeInsightFixtureTestCase { private PsiClass myClass; @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath() + "/psi/constantValues"; } @Override protected void setUp() throws Exception { super.setUp(); myClass = ((PsiJavaFile)myFixture.configureByFile("ClassWithConstants.java")).getClasses()[0]; } @Override protected void tearDown() throws Exception { myClass = null; super.tearDown(); } public void testInt1() { PsiField field = myClass.findFieldByName("INT_CONST1", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.INT, initializer.getType()); assertEquals(Integer.valueOf(1), initializer.getValue()); assertEquals("1", initializer.getText()); assertEquals(Integer.valueOf(1), field.computeConstantValue()); } public void testInt2() { PsiField field = myClass.findFieldByName("INT_CONST2", false); assertNotNull(field); PsiPrefixExpression initializer = (PsiPrefixExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.INT, initializer.getType()); PsiLiteralExpression operand = (PsiLiteralExpression)initializer.getOperand(); assertNotNull(operand); assertEquals(Integer.valueOf(1), operand.getValue()); assertEquals("-1", initializer.getText()); assertEquals(Integer.valueOf(-1), field.computeConstantValue()); } public void testInt3() { PsiField field = myClass.findFieldByName("INT_CONST3", false); assertNotNull(field); PsiPrefixExpression initializer = (PsiPrefixExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.INT, initializer.getType()); int value = -1 << 31; assertEquals(Integer.toString(value), initializer.getText()); assertEquals(Integer.valueOf(value), field.computeConstantValue()); } public void testLong1() { PsiField field = myClass.findFieldByName("LONG_CONST1", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals("2", initializer.getText()); assertEquals(PsiType.INT, initializer.getType()); assertEquals(Integer.valueOf(2), initializer.getValue()); assertEquals(Long.valueOf(2), field.computeConstantValue()); } public void testLong2() { PsiField field = myClass.findFieldByName("LONG_CONST2", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.LONG, initializer.getType()); assertEquals(Long.valueOf(1000000000000L), initializer.getValue()); assertEquals("1000000000000L", initializer.getText()); assertEquals(Long.valueOf(1000000000000L), field.computeConstantValue()); } public void testLong3() { PsiField field = myClass.findFieldByName("LONG_CONST3", false); assertNotNull(field); PsiPrefixExpression initializer = (PsiPrefixExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.LONG, initializer.getType()); long value = -1L << 63; assertEquals(value + "L", initializer.getText()); assertEquals(Long.valueOf(value), field.computeConstantValue()); } public void testShort() { PsiField field = myClass.findFieldByName("SHORT_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.INT, initializer.getType()); assertEquals(Integer.valueOf(3), initializer.getValue()); assertEquals("3", initializer.getText()); assertEquals(Short.valueOf((short)3), field.computeConstantValue()); } public void testByte() { PsiField field = myClass.findFieldByName("BYTE_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.INT, initializer.getType()); assertEquals(Integer.valueOf(4), initializer.getValue()); assertEquals("4", initializer.getText()); assertEquals(Byte.valueOf((byte)4), field.computeConstantValue()); } public void testChar() { PsiField field = myClass.findFieldByName("CHAR_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.CHAR, initializer.getType()); assertEquals(new Character('5'), initializer.getValue()); assertEquals("'5'", initializer.getText()); assertEquals(new Character('5'), field.computeConstantValue()); } public void testBoolean() { PsiField field = myClass.findFieldByName("BOOL_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.BOOLEAN, initializer.getType()); assertEquals(Boolean.TRUE, initializer.getValue()); assertEquals("true", initializer.getText()); assertEquals(Boolean.TRUE, field.computeConstantValue()); } public void testFloat() { PsiField field = myClass.findFieldByName("FLOAT_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.FLOAT, initializer.getType()); assertEquals(new Float(1.234f), initializer.getValue()); assertEquals("1.234f", initializer.getText()); assertEquals(new Float(1.234f), field.computeConstantValue()); } public void testDouble() { PsiField field = myClass.findFieldByName("DOUBLE_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); assertEquals(PsiType.DOUBLE, initializer.getType()); assertEquals(new Double(3.456), initializer.getValue()); assertEquals("3.456", initializer.getText()); assertEquals(new Double(3.456), field.computeConstantValue()); } public void testString() { PsiField field = myClass.findFieldByName("STRING_CONST", false); assertNotNull(field); PsiLiteralExpression initializer = (PsiLiteralExpression)field.getInitializer(); assertNotNull(initializer); PsiType type = initializer.getType(); assertNotNull(type); assertTrue(type.equalsToText("java.lang.String")); assertEquals("a\r\n\"bcd", initializer.getValue()); assertEquals("\"a\\r\\n\\\"bcd\"", initializer.getText()); assertEquals("a\r\n\"bcd", field.computeConstantValue()); } public void testInfinity() { PsiField field1 = myClass.findFieldByName("d1", false); assertNotNull(field1); PsiReferenceExpression initializer1 = (PsiReferenceExpression)field1.getInitializer(); assertNotNull(initializer1); assertEquals(PsiType.DOUBLE, initializer1.getType()); assertEquals("Double.POSITIVE_INFINITY", initializer1.getText()); assertEquals(new Double(Double.POSITIVE_INFINITY), field1.computeConstantValue()); PsiField field2 = myClass.findFieldByName("d2", false); assertNotNull(field2); PsiReferenceExpression initializer2 = (PsiReferenceExpression)field2.getInitializer(); assertNotNull(initializer2); assertEquals(PsiType.DOUBLE, initializer2.getType()); assertEquals("Double.NEGATIVE_INFINITY", initializer2.getText()); assertEquals(new Double(Double.NEGATIVE_INFINITY), field2.computeConstantValue()); PsiField field3 = myClass.findFieldByName("d3", false); assertNotNull(field3); PsiReferenceExpression initializer3 = (PsiReferenceExpression)field3.getInitializer(); assertNotNull(initializer3); assertEquals(PsiType.DOUBLE, initializer3.getType()); assertEquals("Double.NaN", initializer3.getText()); assertEquals(new Double(Double.NaN), field3.computeConstantValue()); } public void testConstantEvaluatorStackOverflowResistance() { StringBuilder text = new StringBuilder(65536).append("class X { String s = \"\""); for (int i = 0; i < 10000; i++) text.append(" + \"\""); text.append("; }"); PsiJavaFile file = (PsiJavaFile)myFixture.configureByText("a.java", text.toString()); PsiField field = file.getClasses()[0].findFieldByName("s", false); assertNotNull(field); assertEquals("", JavaConstantExpressionEvaluator.computeConstantExpression(field.getInitializer(), false)); } public void testStringConstExpression1() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_CONST1", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("\"a\" + \"b\"", initializer.getText()); assertEquals("ab", field.computeConstantValue()); } public void testStringConstExpression2() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_CONST2", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("\"a\" + 123", initializer.getText()); assertEquals("a123", field.computeConstantValue()); } public void testStringConstExpression3() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_CONST3", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("123 + \"b\"", initializer.getText()); assertEquals("123b", field.computeConstantValue()); } public void testStringConstExpression4() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_CONST4", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("INT_CONST1 + \"aaa\"", initializer.getText()); assertEquals("1aaa", field.computeConstantValue()); } public void testStringExpressionClass() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_CLASS", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("Integer.class + \"xxx\"", initializer.getText()); assertEquals("class java.lang.Integerxxx", field.computeConstantValue()); } public void testStringExpressionClassArray() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_CLASS_ARRAY", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("Integer[].class + \"xxx\"", initializer.getText()); assertEquals("class [Ljava.lang.Integer;xxx", field.computeConstantValue()); } public void testStringExpressionInterface() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_INTERFACE", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("Runnable.class + \"xxx\"", initializer.getText()); assertEquals("interface java.lang.Runnablexxx", field.computeConstantValue()); } public void testStringExpressionPrimitive() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_PRIMITIVE", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("int.class + \"xxx\"", initializer.getText()); assertEquals("intxxx", field.computeConstantValue()); } public void testStringExpressionPrimitiveArray() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_PRIMITIVE_ARRAY", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("int[].class + \"xxx\"", initializer.getText()); assertEquals("class [Ixxx", field.computeConstantValue()); } public void testStringExpressionMethod() { PsiField field = myClass.findFieldByName("STRING_EXPRESSION_METHOD", false); assertNotNull(field); PsiBinaryExpression initializer = (PsiBinaryExpression)field.getInitializer(); assertNotNull(initializer); assertTrue(initializer.getType().equalsToText("java.lang.String")); assertEquals("val() + \"xxx\"", initializer.getText()); assertNull(field.computeConstantValue()); } }
/** * 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.lens.cube.parse; import static org.apache.hadoop.hive.ql.parse.HiveParser.*; import java.util.*; import org.apache.lens.cube.error.ColUnAvailableInTimeRange; import org.apache.lens.cube.error.ColUnAvailableInTimeRangeException; import org.apache.lens.cube.error.LensCubeErrorCode; import org.apache.lens.cube.metadata.*; import org.apache.lens.cube.metadata.join.JoinPath; import org.apache.lens.cube.parse.join.AutoJoinContext; import org.apache.lens.server.api.LensConfConstants; import org.apache.lens.server.api.error.LensException; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.ql.parse.ASTNode; import org.apache.hadoop.hive.ql.plan.PlanUtils; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; @Slf4j public class TimeRangeChecker implements ContextRewriter { public TimeRangeChecker(Configuration conf) { } @Override public void rewriteContext(CubeQueryContext cubeql) throws LensException { if (cubeql.getCube() == null) { return; } doColLifeValidation(cubeql); doFactRangeValidation(cubeql); } private void extractTimeRange(CubeQueryContext cubeql) throws LensException { // get time range - // Time range should be direct child of where condition // TOK_WHERE.TOK_FUNCTION.Identifier Or, it should be right hand child of // AND condition TOK_WHERE.KW_AND.TOK_FUNCTION.Identifier if (cubeql.getWhereAST() == null || cubeql.getWhereAST().getChildCount() < 1) { throw new LensException(LensCubeErrorCode.NO_TIMERANGE_FILTER.getLensErrorInfo()); } searchTimeRanges(cubeql.getWhereAST(), cubeql, null, 0); } private void searchTimeRanges(ASTNode root, CubeQueryContext cubeql, ASTNode parent, int childIndex) throws LensException { if (root == null) { return; } else if (root.getToken().getType() == TOK_FUNCTION) { ASTNode fname = HQLParser.findNodeByPath(root, Identifier); if (fname != null && CubeQueryContext.TIME_RANGE_FUNC.equalsIgnoreCase(fname.getText())) { processTimeRangeFunction(cubeql, root, parent, childIndex); } } else { for (int i = 0; i < root.getChildCount(); i++) { ASTNode child = (ASTNode) root.getChild(i); searchTimeRanges(child, cubeql, root, i); } } } private String getColumnName(ASTNode node) { String column = null; if (node.getToken().getType() == DOT) { ASTNode colIdent = (ASTNode) node.getChild(1); column = colIdent.getText().toLowerCase(); } else if (node.getToken().getType() == TOK_TABLE_OR_COL) { // Take child ident.totext ASTNode ident = (ASTNode) node.getChild(0); column = ident.getText().toLowerCase(); } return column; } private void processTimeRangeFunction(CubeQueryContext cubeql, ASTNode timenode, ASTNode parent, int childIndex) throws LensException { TimeRange.TimeRangeBuilder builder = TimeRange.getBuilder(); builder.astNode(timenode); builder.parent(parent); builder.childIndex(childIndex); String timeDimName = getColumnName((ASTNode) timenode.getChild(1)); if (!cubeql.getCube().getTimedDimensions().contains(timeDimName)) { throw new LensException(LensCubeErrorCode.NOT_A_TIMED_DIMENSION.getLensErrorInfo(), timeDimName); } // Replace timeDimName with column which is used for partitioning. Assume // the same column // is used as a partition column in all storages of the fact timeDimName = cubeql.getPartitionColumnOfTimeDim(timeDimName); builder.partitionColumn(timeDimName); String fromDateRaw = PlanUtils.stripQuotes(timenode.getChild(2).getText()); String toDateRaw = null; if (timenode.getChildCount() > 3) { ASTNode toDateNode = (ASTNode) timenode.getChild(3); if (toDateNode != null) { toDateRaw = PlanUtils.stripQuotes(timenode.getChild(3).getText()); } } long currentTime = cubeql.getConf().getLong(LensConfConstants.QUERY_CURRENT_TIME_IN_MILLIS, 0); Date now; if (currentTime != 0) { now = new Date(currentTime); } else { now = new Date(); } builder.fromDate(DateUtil.resolveDate(fromDateRaw, now)); if (StringUtils.isNotBlank(toDateRaw)) { builder.toDate(DateUtil.resolveDate(toDateRaw, now)); } else { builder.toDate(now); } TimeRange range = builder.build(); range.validate(); cubeql.getTimeRanges().add(range); } private void doColLifeValidation(CubeQueryContext cubeql) throws LensException, ColUnAvailableInTimeRangeException { Set<String> cubeColumns = cubeql.getColumnsQueried(cubeql.getCube().getName()); if (cubeColumns == null || cubeColumns.isEmpty()) { // Query doesn't have any columns from cube return; } for (String col : cubeql.getColumnsQueried(cubeql.getCube().getName())) { CubeColumn column = cubeql.getCube().getColumnByName(col); for (TimeRange range : cubeql.getTimeRanges()) { if (column == null) { if (!cubeql.getCube().getTimedDimensions().contains(col)) { throw new LensException(LensCubeErrorCode.NOT_A_CUBE_COLUMN.getLensErrorInfo(), col); } continue; } if (!column.isColumnAvailableInTimeRange(range)) { throwException(column); } } } // Look at referenced columns through denormalization resolver // and do column life validation Map<String, Set<DenormalizationResolver.ReferencedQueriedColumn>> refCols = cubeql.getDeNormCtx().getReferencedCols(); for (String col : refCols.keySet()) { Iterator<DenormalizationResolver.ReferencedQueriedColumn> refColIter = refCols.get(col).iterator(); while (refColIter.hasNext()) { DenormalizationResolver.ReferencedQueriedColumn refCol = refColIter.next(); for (TimeRange range : cubeql.getTimeRanges()) { if (!refCol.col.isColumnAvailableInTimeRange(range)) { log.debug("The refernced column: {} is not in the range queried", refCol.col.getName()); refColIter.remove(); break; } } } } // Remove join paths that have columns with invalid life span AutoJoinContext joinContext = cubeql.getAutoJoinCtx(); if (joinContext == null) { return; } // Get cube columns which are part of join chain Set<String> joinColumns = joinContext.getAllJoinPathColumnsOfTable((AbstractCubeTable) cubeql.getCube()); if (joinColumns == null || joinColumns.isEmpty()) { return; } // Loop over all cube columns part of join paths for (String col : joinColumns) { CubeColumn column = cubeql.getCube().getColumnByName(col); for (TimeRange range : cubeql.getTimeRanges()) { if (!column.isColumnAvailableInTimeRange(range)) { log.info("Timerange queried is not in column life for {}, Removing join paths containing the column", column); // Remove join paths containing this column Map<Aliased<Dimension>, List<JoinPath>> allPaths = joinContext.getAllPaths(); for (Aliased<Dimension> dimension : allPaths.keySet()) { List<JoinPath> joinPaths = allPaths.get(dimension); Iterator<JoinPath> joinPathIterator = joinPaths.iterator(); while (joinPathIterator.hasNext()) { JoinPath path = joinPathIterator.next(); if (path.containsColumnOfTable(col, (AbstractCubeTable) cubeql.getCube())) { log.info("Removing join path: {} as columns :{} is not available in the range", path, col); joinPathIterator.remove(); if (joinPaths.isEmpty()) { // This dimension doesn't have any paths left throw new LensException(LensCubeErrorCode.NO_JOIN_PATH.getLensErrorInfo(), "No valid join path available for dimension " + dimension + " which would satisfy time range " + range.getFromDate() + "-" + range.getToDate()); } } } // End loop to remove path } // End loop for all paths } } // End time range loop } // End column loop } private void throwException(CubeColumn column) throws ColUnAvailableInTimeRangeException { final Long availabilityStartTime = (column.getStartTimeMillisSinceEpoch().isPresent()) ? column.getStartTimeMillisSinceEpoch().get() : null; final Long availabilityEndTime = column.getEndTimeMillisSinceEpoch().isPresent() ? column.getEndTimeMillisSinceEpoch().get() : null; ColUnAvailableInTimeRange col = new ColUnAvailableInTimeRange(column.getName(), availabilityStartTime, availabilityEndTime); throw new ColUnAvailableInTimeRangeException(col); } private void doFactRangeValidation(CubeQueryContext cubeql) { Iterator<CandidateFact> iter = cubeql.getCandidateFacts().iterator(); while (iter.hasNext()) { CandidateFact cfact = iter.next(); List<TimeRange> invalidTimeRanges = Lists.newArrayList(); for (TimeRange timeRange : cubeql.getTimeRanges()) { if (!cfact.isValidForTimeRange(timeRange)) { invalidTimeRanges.add(timeRange); } } if (!invalidTimeRanges.isEmpty()){ cubeql.addFactPruningMsgs(cfact.fact, CandidateTablePruneCause.factNotAvailableInRange(invalidTimeRanges)); log.info("Not considering {} as it's not available for time ranges: {}", cfact, invalidTimeRanges); iter.remove(); } } cubeql.pruneCandidateFactSet(CandidateTablePruneCause.CandidateTablePruneCode.FACT_NOT_AVAILABLE_IN_RANGE); } }
package mil.nga.geopackage.tiles.matrixset; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.contents.Contents; import mil.nga.geopackage.contents.ContentsDataType; import mil.nga.geopackage.srs.SpatialReferenceSystem; import mil.nga.proj.Projection; import mil.nga.sf.proj.GeometryTransform; /** * Tile Matrix Set object. Defines the minimum bounding box (min_x, min_y, * max_x, max_y) and spatial reference system (srs_id) for all content in a tile * pyramid user data table. * * @author osbornb */ @DatabaseTable(tableName = "gpkg_tile_matrix_set", daoClass = TileMatrixSetDao.class) public class TileMatrixSet { /** * Table name */ public static final String TABLE_NAME = "gpkg_tile_matrix_set"; /** * tableName field name */ public static final String COLUMN_TABLE_NAME = Contents.COLUMN_TABLE_NAME; /** * id field name, tableName */ public static final String COLUMN_ID = COLUMN_TABLE_NAME; /** * srsId field name */ public static final String COLUMN_SRS_ID = SpatialReferenceSystem.COLUMN_SRS_ID; /** * minX field name */ public static final String COLUMN_MIN_X = "min_x"; /** * minY field name */ public static final String COLUMN_MIN_Y = "min_y"; /** * maxX field name */ public static final String COLUMN_MAX_X = "max_x"; /** * maxY field name */ public static final String COLUMN_MAX_Y = "max_y"; /** * Foreign key to Contents by table name */ @DatabaseField(columnName = COLUMN_TABLE_NAME, canBeNull = false, foreign = true, foreignAutoRefresh = true) private Contents contents; /** * Tile Pyramid User Data Table Name */ @DatabaseField(columnName = COLUMN_TABLE_NAME, id = true, canBeNull = false, readOnly = true) private String tableName; /** * Spatial Reference System ID: gpkg_spatial_ref_sys.srs_id */ @DatabaseField(columnName = COLUMN_SRS_ID, canBeNull = false, foreign = true, foreignAutoRefresh = true) private SpatialReferenceSystem srs; /** * Unique identifier for each Spatial Reference System within a GeoPackage */ @DatabaseField(columnName = COLUMN_SRS_ID, canBeNull = false, readOnly = true) private long srsId; /** * Bounding box minimum easting or longitude for all content in table_name */ @DatabaseField(columnName = COLUMN_MIN_X, canBeNull = false) private double minX; /** * Bounding box minimum northing or latitude for all content in table_name */ @DatabaseField(columnName = COLUMN_MIN_Y, canBeNull = false) private double minY; /** * Bounding box maximum easting or longitude for all content in table_name */ @DatabaseField(columnName = COLUMN_MAX_X, canBeNull = false) private double maxX; /** * Bounding box maximum northing or latitude for all content in table_name */ @DatabaseField(columnName = COLUMN_MAX_Y, canBeNull = false) private double maxY; /** * Default Constructor */ public TileMatrixSet() { } /** * Copy Constructor * * @param tileMatrixSet * tile matrix set to copy * @since 1.3.0 */ public TileMatrixSet(TileMatrixSet tileMatrixSet) { contents = tileMatrixSet.contents; tableName = tileMatrixSet.tableName; srs = tileMatrixSet.srs; srsId = tileMatrixSet.srsId; minX = tileMatrixSet.minX; minY = tileMatrixSet.minY; maxX = tileMatrixSet.maxX; maxY = tileMatrixSet.maxY; } public String getId() { return tableName; } public void setId(String id) { this.tableName = id; } public Contents getContents() { return contents; } public void setContents(Contents contents) { this.contents = contents; if (contents != null) { // Verify the Contents have a tiles data type (Spec Requirement 33) if (!contents.isTilesTypeOrUnknown()) { throw new GeoPackageException("The " + Contents.class.getSimpleName() + " of a " + TileMatrixSet.class.getSimpleName() + " must have a data type of " + ContentsDataType.TILES.getName() + ". actual type: " + contents.getDataTypeName()); } tableName = contents.getId(); } else { tableName = null; } } public String getTableName() { return tableName; } public SpatialReferenceSystem getSrs() { return srs; } public void setSrs(SpatialReferenceSystem srs) { this.srs = srs; srsId = srs != null ? srs.getId() : -1; } public long getSrsId() { return srsId; } public double getMinX() { return minX; } public void setMinX(double minX) { this.minX = minX; } public double getMinY() { return minY; } public void setMinY(double minY) { this.minY = minY; } public double getMaxX() { return maxX; } public void setMaxX(double maxX) { this.maxX = maxX; } public double getMaxY() { return maxY; } public void setMaxY(double maxY) { this.maxY = maxY; } /** * Get a bounding box * * @return bounding box */ public BoundingBox getBoundingBox() { BoundingBox boundingBox = new BoundingBox(getMinX(), getMinY(), getMaxX(), getMaxY()); return boundingBox; } /** * Get a bounding box in the provided projection * * @param projection * desired projection * * @return bounding box * @since 3.1.0 */ public BoundingBox getBoundingBox(Projection projection) { BoundingBox boundingBox = getBoundingBox(); if (projection != null) { GeometryTransform transform = GeometryTransform .create(getProjection(), projection); if (!transform.isSameProjection()) { boundingBox = boundingBox.transform(transform); } } return boundingBox; } /** * Set a bounding box * * @param boundingBox * bounding box */ public void setBoundingBox(BoundingBox boundingBox) { setMinX(boundingBox.getMinLongitude()); setMaxX(boundingBox.getMaxLongitude()); setMinY(boundingBox.getMinLatitude()); setMaxY(boundingBox.getMaxLatitude()); } /** * Get the projection * * @return projection * @since 3.1.0 */ public Projection getProjection() { return getSrs().getProjection(); } }
package com.dancingqueen.walladog.aws.downloader.service; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.support.v4.util.LongSparseArray; import android.util.Log; import com.dancingqueen.walladog.aws.downloader.policy.DownloadPolicyProvider; import com.dancingqueen.walladog.aws.downloader.query.DownloadQueueProvider; import com.dancingqueen.walladog.aws.downloader.query.DownloadState; import com.dancingqueen.walladog.aws.downloader.query.QueryHelper; import java.io.File; import java.net.HttpURLConnection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * This classes handles downloading files using DownloadTasks */ public class BasicDownloader implements DownloadTask.DownloadListener, DownloadTask.NetworkStatusProvider, Downloader { /** Logging tag for this class. */ private static final String LOG_TAG = BasicDownloader.class.getSimpleName(); /** How many threads in the download pool by default. */ private static final int MAX_DOWNLOAD_THREADS = 2; /** Minimum Android SDK that support WIFI_MODE_FULL_HIGH_PERF. */ private static final int ANDROID_SDK_VERSION_12 = 12; /** Whether we're still reading in the downloads. */ private boolean initializing = true; /** The executor which is going to download the files for us. */ private final ExecutorService downloader; /** The context to use. */ private final Context context; /** The DownloadStatusUpdater to use. */ private final DownloadStatusUpdater statusUpdater; /** The download policy which is in force. */ private final DownloadPolicyProvider policyProvider; /** The in-memory list of downloads queued to run. The number of these tasks that are actually running * is limited by {@link #MAX_DOWNLOAD_THREADS} . */ private final LongSparseArray<DLTaskInfo> runningDownloads; /** Keeps track of whether downloads are using wifi locks .*/ private final LongSparseArray<Boolean> wifiLocks; /** Wifi Lock to use for downloads that require a wifi lock. */ private final WifiLock wifiLock; private class DLTaskInfo { private final DownloadTask downloadTask; private final Future<Boolean> runningDownload; private DLTaskInfo(final DownloadTask downloadTask, final Future<Boolean> runningDownload) { this.downloadTask = downloadTask; this.runningDownload = runningDownload; } } /** * Create a new instance. * * @param aContext * the context to use for accessing the content provider etc * @param aPolicyProvider * the download policy provider to use * @param aStatusUpdater * the download status updater to use */ public BasicDownloader(final Context aContext, final DownloadPolicyProvider aPolicyProvider, final DownloadStatusUpdater aStatusUpdater) { Log.d(LOG_TAG, "BasicDownloader()"); downloader = Executors.newFixedThreadPool(MAX_DOWNLOAD_THREADS, new MinPriorityThreadFactory(this.getClass() .getSimpleName())); context = aContext; statusUpdater = aStatusUpdater; policyProvider = aPolicyProvider; runningDownloads = new LongSparseArray<>(); wifiLocks = new LongSparseArray<>(); final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int wifiMode = WifiManager.WIFI_MODE_FULL; if (android.os.Build.VERSION.SDK_INT >= ANDROID_SDK_VERSION_12) { wifiMode = WifiManager.WIFI_MODE_FULL_HIGH_PERF; } wifiLock = wifiManager.createWifiLock(wifiMode, this.getClass().getSimpleName()); startReadingQueueFromContentProvider(); } /** * See {@link Downloader#isIdle()} */ @Override public boolean isIdle() { final boolean result; synchronized (runningDownloads) { result = !initializing && 0 == runningDownloads.size(); } Log.d(LOG_TAG, "isIdle() returning " + result); return result; } /** * See {@link Downloader#addDownloadTask(long)} */ @Override public boolean addDownloadTask(final long id) { Log.d(LOG_TAG, String.format("Adding download task with id %d", id)); synchronized (runningDownloads) { if (runningDownloads.get(id) != null) { // Consider adding the task to fail if already downloading. return false; } final DownloadTask downloadTask = createDownloadTask(id); // Fail fast if attempting to add a task that doesn't exist. if (downloadTask == null) { // Can't find the download task in the database. return false; } final Future<Boolean> receipt = downloader.submit(downloadTask); runningDownloads.put(id, new DLTaskInfo(downloadTask, receipt)); } return true; } private boolean stopDownloadTask(final long downloadId, final DownloadTask.TaskCancelReason cancelReason) { final DLTaskInfo dlTaskInfo; final Future<Boolean> receipt; synchronized (runningDownloads) { dlTaskInfo = runningDownloads.get(downloadId); if (dlTaskInfo == null) { // No download task was running for the specified id. return false; } receipt = dlTaskInfo.runningDownload; runningDownloads.delete(downloadId); } if (!receipt.isDone()) { dlTaskInfo.downloadTask.setCancelReason(cancelReason); final boolean result = receipt.cancel(true); Log.d(LOG_TAG, String.format("Cancelled task by pausing for id (%d) result = %s", downloadId, Boolean.toString(result))); return true; } // The download task already completed. return false; } /** * See {@link Downloader#pauseDownloadTask(long)} */ @Override public boolean pauseDownloadTask(final long downloadId) { // If we're pausing the execution of a download, its task is no longer // relevant and can be canceled since a new task will be created when // the download is resumed. return stopDownloadTask(downloadId, DownloadTask.TaskCancelReason.PAUSED_BY_USER); } /** * See {@link Downloader#resumeDownloadTask(long)} */ @Override public boolean resumeDownloadTask(final long downloadId) { return addDownloadTask(downloadId); } /** * See {@link Downloader#shutdownNow()} */ @Override public void shutdownNow() { // Shut the executor service down downloader.shutdownNow(); synchronized (runningDownloads) { // Clear the runningDownloads map. runningDownloads.clear(); // Set initializing to be false so that isIdle returns true initializing = false; } } /** * Set initializing to false. */ public void doneInitializing() { synchronized (runningDownloads) { initializing = false; } notifyDownloadServiceInitializationComplete(); } /** * Trigger DownloadService to check Downloader.isIdle() * so that it may shutdown after initializing. */ private void notifyDownloadServiceInitializationComplete() { Intent intent = new Intent(context, DownloadService.class); intent.setAction(DownloadService.ACTION_NO_OPERATION); context.startService(intent); } @Override public boolean cancelDownloadTask(final long downloadId) { return stopDownloadTask(downloadId, DownloadTask.TaskCancelReason.CANCELED_BY_USER); } /** Download Task column types for DB query. */ private enum DownloadTaskColumns { /** url. */ COL_URL(DownloadQueueProvider.COLUMN_DOWNLOAD_URL), /** file location. */ COL_FILE_LOCATION(DownloadQueueProvider.COLUMN_DOWNLOAD_FILE_LOCATION), /** the download ETAG. */ COL_TAG(DownloadQueueProvider.COLUMN_DOWNLOAD_ETAG), /** Current size. */ COL_CURRENT_SIZE(DownloadQueueProvider.COLUMN_DOWNLOAD_CURRENT_SIZE), /** user flags. */ COL_USER_FLAGS(DownloadQueueProvider.COLUMN_DOWNLOAD_USER_FLAGS), /** download status. */ COL_DOWNLOAD_STATUS(DownloadQueueProvider.COLUMN_DOWNLOAD_STATUS), /** Total size of download. */ COL_TOTAL_SIZE(DownloadQueueProvider.COLUMN_DOWNLOAD_TOTAL_SIZE); /** Name of the column. */ String columnName; /** * Set column name. * @param s the column name. */ DownloadTaskColumns(final String s) { columnName = s; } /** Array of column names for db query. */ private static final String[] COLUMNS; static { COLUMNS = new String[DownloadTaskColumns.values().length]; for (DownloadTaskColumns colType : DownloadTaskColumns.values()) { COLUMNS[colType.ordinal()] = colType.columnName; } } /** * @return column names. */ public static String[] getColumnNames() { return COLUMNS; } } /** * Get a callable to download a given ID. * * @param id * the ID to look up and create the runnable for * @return the callable. */ public DownloadTask createDownloadTask(final long id) { Log.d(LOG_TAG, "createDownloadTask()"); final String query = DownloadQueueProvider.COLUMN_DOWNLOAD_ID + " = ?"; final String[] args = new String[] {String.valueOf(id)}; final String[] cols = QueryHelper.runDownloadQueryForRow(context, DownloadTaskColumns.getColumnNames(), query, args); if (null != cols) { final int userFlags = DownloadFlags.parseUserFlags( cols[DownloadTaskColumns.COL_USER_FLAGS.ordinal()]); final boolean ars = DownloadState.PAUSED.toString() .equals(cols[DownloadTaskColumns.COL_DOWNLOAD_STATUS.ordinal()]); final DownloadTask.Builder builder = new DownloadTask.Builder(id) .withListener(this) .withNetworkStatusProvider(this) .withProvider(policyProvider) .withUri(cols[DownloadTaskColumns.COL_URL.ordinal()]) .withDestination(cols[DownloadTaskColumns.COL_FILE_LOCATION.ordinal()]) .withTag(cols[DownloadTaskColumns.COL_TAG.ordinal()]) .withOffset(cols[DownloadTaskColumns.COL_CURRENT_SIZE.ordinal()]) .withDownloadFlags(userFlags) .withAutoRestart(ars) .withTotalBytes(cols[DownloadTaskColumns.COL_TOTAL_SIZE.ordinal()]); return builder.build(); } return null; } private int getFlagsForDownloadById(final long id) { final String[] projection = new String[] { DownloadQueueProvider.COLUMN_DOWNLOAD_USER_FLAGS }; final String query = DownloadQueueProvider.COLUMN_DOWNLOAD_ID + " = ?"; final String[] args = new String[] { Long.toString(id) }; final String[] cols = QueryHelper.runDownloadQueryForRow(context, projection, query, args); // This query is expected to always succeed in finding a row. if (cols == null) { Log.e(LOG_TAG, String.format( "Couldn't find download id (%d) in the queue to check download flags.", id)); return 0; } return DownloadFlags.parseUserFlags(cols[0]); } /** * Indicates whether a Wifi lock is required or not for a specific download request. * * @param id the download request id. * @return true if wifi lock is required. False otherwise. */ /* package */ boolean wifiLockRequired(final long id) { return DownloadFlags.isWifiLockFlagSet(getFlagsForDownloadById(id)); } /* begin DownloadTask.listener implementation */ /** * Receive notification that a download started. * * @param longDownloadId * the ID */ @Override public void start(final long longDownloadId) { statusUpdater.start(longDownloadId); } /** * Receive notification that we got headers etc. * example headers: [ * Date: Thu, 01 Nov 2012 20:21:54 GMT, * Server: Apache/2.2.22 (Fedora), * Last-Modified: Sun, 28 Oct 2012 19:38:20 GMT, * ETag: "75c317b-4fb985a-4cd23b1f4c300", * Accept-Ranges: bytes, * Content-Length: 83597402, * Keep-Alive: timeout=5, max=1000, * Connection: Keep-Alive, * Content-Type: application/x-bzip2 * ] * * @param longDownloadId * the ID * @param connection * the HttpUrlConnection containing response headers to examine. */ @Override public void headersReceived(final long longDownloadId, final HttpURLConnection connection) { statusUpdater.headersReceived(longDownloadId, connection); } /** * Receive notification that progress happened. * We send a progress broadcast, and optionally update the content provider. * * @param longDownloadId * the task of which to update progress * @param bytesRead * number of bytes transferred * @param totalBytes * total number of bytes if known, or -1 if not known */ @Override public void sendProgress(final long longDownloadId, final long bytesRead, final long totalBytes) { statusUpdater.sendProgress(longDownloadId, bytesRead, totalBytes); } /** * Receive notification that the download terminated, whether sucessfully or not. * * @param downloadId * the id * @param withStatus * whether it worked or not * @param completionMessage * the completion message if any * @param bytesRead * the bytes successfully downloaded * @param totalBytes * the total size of the entity to download * @param autoRestart * whether this was an automatic restart of something * @param downloadError * error code with a DownloadError enum value */ @Override public void finish(final long downloadId, final CompletionStatus withStatus, final String completionMessage, final long bytesRead, final long totalBytes, final boolean autoRestart, final String downloadError) { Log.i(LOG_TAG, String.format("downloadTaskComplete, id = %d withStatus = %s", downloadId, withStatus)); // remove task from our list synchronized (runningDownloads) { runningDownloads.remove(downloadId); } if (withStatus == CompletionStatus.FAILED) { Log.d(LOG_TAG, "cleanUpPartialFile for Failed Downloads"); cleanUpPartialFile(downloadId); } statusUpdater.finish(downloadId, withStatus, completionMessage, bytesRead, totalBytes, autoRestart, downloadError); final int downloadFlags = getFlagsForDownloadById(downloadId); // at this point check whether we still have a network if (!isNetworkAvailable(DownloadFlags.isCellNetworkProhibited(downloadFlags))) { shutdownNow(); } if (withStatus != CompletionStatus.SUCCEEDED) { NetworkStateListener.enable(context); } Log.d(LOG_TAG, "done with downloadTaskComplete, id = " + downloadId); } /** * If a download fails, cleanup the partial file to regain the space. * If there was any chance of success, then the download should have paused instead of failing. * * @param downloadId long DownloadId. */ private void cleanUpPartialFile(final long downloadId) { final Uri downloadQueueContentUri = DownloadQueueProvider.getDownloadContentUri(context); final Cursor downloadCursor = context.getContentResolver().query(downloadQueueContentUri, new String[]{ DownloadQueueProvider.COLUMN_DOWNLOAD_FILE_LOCATION }, DownloadQueueProvider.COLUMN_DOWNLOAD_ID + " = " + downloadId, null, null); if (downloadCursor != null) { downloadCursor.moveToFirst(); if (!downloadCursor.isAfterLast()) { final String filePath = downloadCursor.getString( downloadCursor.getColumnIndex( DownloadQueueProvider.COLUMN_DOWNLOAD_FILE_LOCATION)); File downloadedFile = new File(filePath); if (downloadedFile.exists()) { Log.d(LOG_TAG, String.format("Cleaning up partial failed download: %s", filePath)); if (!downloadedFile.delete()) { Log.e(LOG_TAG, String.format( "Unable to delete failed partially downloaded file: %s", filePath)); } } } downloadCursor.close(); } } /* end DownloadTask.listener implementation */ /* begin DownloadTask.NetworkStatusProvider implementation */ /** * Report whether the network is available. * * @return true if it is */ @Override public boolean isNetworkAvailable(boolean isMobileNetworkProhibited) { final ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null == mgr) { return false; } final NetworkInfo networkInfo = mgr.getActiveNetworkInfo(); return null != networkInfo && networkInfo.isConnected() && (!isMobileNetworkProhibited || networkInfo.getType() != ConnectivityManager.TYPE_MOBILE); } /** * Acquire a wifi lock and associate it with a download Id. * The wifi lock will be acquired only if it was specified as part of the request intent for that download Id. * * @param downloadId the download id. */ @Override public void acquireWifiLock(final long downloadId) { // Acquire a wifi lock if required if (wifiLockRequired(downloadId)) { synchronized (wifiLocks) { wifiLock.acquire(); // Keep track that a wifi lock was required for this download. wifiLocks.append(downloadId, true); } Log.d(LOG_TAG, "Acquired wifi lock for download: " + downloadId); } } /** * This releases the wifi lock (if any) associated with a particular download ID. * * @param downloadId the download id. */ @Override public void releaseWifiLock(final long downloadId) { // release wifi lock if required boolean wasWifiLockRequired = false; synchronized (wifiLocks) { final Boolean wifiLockRequired = wifiLocks.get(downloadId); if (wifiLockRequired != null) { wifiLocks.delete(downloadId); if (wifiLockRequired) { wasWifiLockRequired = true; } } } if (wasWifiLockRequired) { if (wifiLock.isHeld()) { wifiLock.release(); Log.d(LOG_TAG, String.format("Released wifi lock for download id(%d).", downloadId)); } else { Log.e(LOG_TAG, String.format("Download with id(%d) expected the wifi lock to be held, but it wasn't.", downloadId)); } } } /* end DownloadTask.NetworkStatusProvider implementation */ /** * Read the queue out of the content provider on a separate thread. */ /* package */void startReadingQueueFromContentProvider() { Log.i(LOG_TAG, "start reading queue"); downloader.submit(new QueueReaderTask(this, this.context)); Log.i(LOG_TAG, "queue read job submitted"); } /** * @see Downloader#onCleanupAction() */ @Override public void onCleanupAction() { } }
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.PersistenceException; import javax.persistence.PreRemove; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Created by <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> on 2014-11-23. * * Class that maps the artifacts created and/or used by the builds of the projects. * The "type" indicates the genesis of the artifact, whether it has been imported from * external repositories, or built internally. * * The repoType indicated the type of repository which is used to distributed the artifact. * The repoType repo indicates the format for the identifier field. * */ @Entity @Table( uniqueConstraints = @UniqueConstraint(columnNames = { "identifier", "sha256", "targetRepository_id"}), indexes = { @Index(name="idx_artifact_targetRepository", columnList = "targetRepository_id"), @Index(name="idx_artifact_identifier", columnList = "identifier"), @Index(name="idx_artifact_sha256", columnList = "sha256") } ) public class Artifact implements GenericEntity<Integer> { private static final long serialVersionUID = 1L; public static final String SEQUENCE_NAME = "artifact_id_seq"; @Id @SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME, initialValue = 100, allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_NAME) private Integer id; /** * Contains a string which uniquely identifies the artifact in a repository. * For example, for a maven artifact this is the GATVC (groupId:artifactId:type:version[:qualifier] * The format of the identifier string is determined by the repoType */ @NotNull @Size(max=1024) @Column(updatable=false) private String identifier; @NotNull @Size(max=32) @Column(updatable=false) private String md5; @NotNull @Size(max=40) @Column(updatable=false) private String sha1; @NotNull @Size(max=64) @Column(updatable=false) private String sha256; @Column(updatable = false) private Long size; @NotNull @Enumerated(EnumType.STRING) //TODO store as set, to keep history private Artifact.Quality artifactQuality; /** * The type of repository which hosts this artifact (Maven, NPM, etc). This field determines * the format of the identifier string. */ @JoinColumn(foreignKey = @ForeignKey(name = "fk_artifact_targetRepository")) @NotNull @ManyToOne private TargetRepository targetRepository; @Size(max=255) @Column(updatable=false) private String filename; /** * Repository URL where the artifact file is available. */ @Size(max=500) @Column(updatable=false, length=500) private String deployPath; /** * The record of the build which produced this artifact. * Usually there should be only one build record that produced this artifact. * However some other build may produce the same artifact (same checksum) * in such case we link the BuildRecord to the same artifact. */ @ManyToMany(mappedBy = "builtArtifacts") private Set<BuildRecord> buildRecords; /** * The list of builds which depend on this artifact. * For example, if the build downloaded this artifact as a Maven dependency. */ @ManyToMany(mappedBy = "dependencies") private Set<BuildRecord> dependantBuildRecords; /** * The location from which this artifact was originally downloaded for import */ @Size(max=500) @Column(unique=false, updatable=false, length=500) private String originUrl; /** * The date when this artifact was originally imported */ @Column(updatable=false) private Date importDate; /** * The product milestone releases which distribute this artifact */ @ManyToMany(mappedBy = "distributedArtifacts") private Set<ProductMilestone> distributedInProductMilestones; @Transient public IdentifierSha256 getIdentifierSha256() { return new IdentifierSha256(identifier, sha256); } public enum Quality { /** * The artifact has not yet been verified or tested */ NEW, /** * The artifact has been verified by an automated process, but has not yet been tested against * a complete product or other large set of components. */ VERIFIED, /** * The artifact has passed integration testing. */ TESTED, /** * The artifact should no longer be used due to lack of support and/or a better alternative * being available. */ DEPRECATED, /** * The artifact contains a severe defect, possibly a functional or security issue. */ BLACKLISTED, /** * Artifact with DELETED quality is used to show BuildRecord dependencies although the artifact itself was deleted. * DELETED can be set only from TEMPORARY */ DELETED, /** * The artifact is from a snapshot or a Pull Request build */ TEMPORARY } /** * Try to use the {@link Artifact.Builder} instead. * * Basic no-arg constructor. Initializes the buildRecords and dependantBuildRecords to * empty set. */ Artifact() { buildRecords = new HashSet<>(); dependantBuildRecords = new HashSet<>(); distributedInProductMilestones = new HashSet<>(); } @PreRemove public void preRemove() { if(artifactQuality != Quality.TEMPORARY) { throw new PersistenceException("The non-temporary artifacts cannot be deleted! Only deletion of temporary artifacts is supported "); } } /** * Gets the id. * * @return the id */ @Override public Integer getId() { return id; } /** * Sets the id. * * @param id the new id */ @Override public void setId(Integer id) { this.id = id; } /** * Gets the identifier. * * The identifier should contain different logic depending on the artifact type: i.e Maven should contain the GAV, NPM and * CocoaPOD should be identified differently * * @return the identifier */ public String getIdentifier() { return identifier; } /** * Sets the identifier. * * @param identifier the new identifier */ public void setIdentifier(String identifier) { this.identifier = identifier; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public String getSha1() { return sha1; } public void setSha1(String sha1) { this.sha1 = sha1; } public String getSha256() { return sha256; } public void setSha256(String sha256) { this.sha256 = sha256; } public Artifact.Quality getArtifactQuality() { return artifactQuality; } public void setArtifactQuality(Artifact.Quality artifactQuality) { if (Quality.DELETED.equals(artifactQuality)) { if (!Quality.TEMPORARY.equals(this.artifactQuality)) { throw new PersistenceException("Deleted quality can be set only to temporary artifacts."); } } this.artifactQuality = artifactQuality; } /** * Check if this artifact has an associated build record * @return true if there is a build record for this artifact, false otherwise */ public boolean isBuilt() { return (buildRecords != null && buildRecords.size() > 0); } /** Check if this artifact was imported from a remote URL * @return true if there is an originUrl */ public boolean isImported() { return (originUrl != null && !originUrl.isEmpty()); } public boolean isTrusted() { return (isBuilt() || TargetRepository.isTrusted(originUrl, targetRepository)); } /** * Gets the filename. * * @return the filename */ public String getFilename() { return filename; } /** * Sets the filename. * * @param filename the new filename */ public void setFilename(String filename) { this.filename = filename; } /** * Gets the deploy url. * * @return the deploy url */ public String getDeployPath() { return deployPath; } /** * Sets the deploy path. * * @param deployPath the new deploy url */ public void setDeployPath(String deployPath) { this.deployPath = deployPath; } /** * Gets the set of build records which produced this artifact. * * @return the set of build records */ public Set<BuildRecord> getBuildRecords() { return buildRecords; } /** * Sets the project build record. * * @param buildRecords the set of build records */ public void setBuildRecords(Set<BuildRecord> buildRecords) { this.buildRecords = buildRecords; } /** * Add a build record which produced this artifact * * @param buildRecord the new project build record * @return */ public boolean addBuildRecord(BuildRecord buildRecord) { return this.buildRecords.add(buildRecord); } public Set<BuildRecord> getDependantBuildRecords() { return dependantBuildRecords; } public void setDependantBuildRecords(Set<BuildRecord> buildRecords) { this.dependantBuildRecords = buildRecords; } public void addDependantBuildRecord(BuildRecord buildRecord) { if (!dependantBuildRecords.contains(buildRecord)) { this.dependantBuildRecords.add(buildRecord); } } public String getOriginUrl() { return originUrl; } public void setOriginUrl(String originUrl) { this.originUrl = originUrl; } public Date getImportDate() { return importDate; } public void setImportDate(Date importDate) { this.importDate = importDate; } public Set<ProductMilestone> getDistributedInProductMilestones() { return distributedInProductMilestones; } public void setDistributedInProductMilestones(Set<ProductMilestone> distributedInProductMilestones) { this.distributedInProductMilestones = distributedInProductMilestones; } public boolean addDistributedInProductMilestone(ProductMilestone productMilestone) { return this.distributedInProductMilestones.add(productMilestone); } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public TargetRepository getTargetRepository() { return targetRepository; } public void setTargetRepository(TargetRepository targetRepository) { this.targetRepository = targetRepository; } @Override public String toString() { return "Artifact [id: " + id + ", identifier=" + identifier + ", quality=" + artifactQuality + ", targetRepository=[id: " + targetRepository.getId() + ", identifier: " + targetRepository.getIdentifier() + ", repositoryPath: " + targetRepository.getRepositoryPath() + ", repositoryType: " + targetRepository.getRepositoryType() + ", temporaryRepo: " + targetRepository.getTemporaryRepo() + "]]"; } public String getDescriptiveString() { return String.format("Identifier=%s, Sha256=%s, Target repository=%s, Deploy path=%s, Quality=%s", identifier, sha256, targetRepository.getId(), deployPath, artifactQuality); } @Override public boolean equals(Object obj) { if (!(obj instanceof Artifact)) { return false; } if (identifier == null || md5 == null || sha1 == null || sha256 == null) { return this == obj; } Artifact compare = (Artifact)obj; return identifier.equals(compare.getIdentifier()) && md5.equals(compare.getMd5()) && sha1.equals(compare.getSha1()) && sha256.equals(compare.getSha256()); } @Override public int hashCode() { return (identifier + md5 + sha1 + sha256).hashCode(); } public static class Builder { private Integer id; private String identifier; private String md5; private String sha1; private String sha256; private Long size; private Quality artifactQuality; private TargetRepository targetRepository; private String filename; private String deployPath; private Set<BuildRecord> dependantBuildRecords; private Set<BuildRecord> buildRecords; private Set<ProductMilestone> distributedInProductMilestones; private String originUrl; private Date importDate; private Builder() { buildRecords = new HashSet<>(); dependantBuildRecords = new HashSet<>(); distributedInProductMilestones = new HashSet<>(); } public static Builder newBuilder() { return new Builder(); } public Artifact build() { Artifact artifact = new Artifact(); artifact.setId(id); artifact.setIdentifier(identifier); artifact.setMd5(md5); artifact.setSha1(sha1); artifact.setSha256(sha256); artifact.setSize(size); if (artifactQuality == null) { artifactQuality = Quality.NEW; } artifact.setArtifactQuality(artifactQuality); artifact.setTargetRepository(targetRepository); artifact.setFilename(filename); artifact.setDeployPath(deployPath); if (dependantBuildRecords != null) { artifact.setDependantBuildRecords(dependantBuildRecords); } artifact.setBuildRecords(buildRecords); artifact.setDistributedInProductMilestones(distributedInProductMilestones); artifact.setOriginUrl(originUrl); artifact.setImportDate(importDate); return artifact; } public Builder id(Integer id) { this.id = id; return this; } public Builder identifier(String identifier) { this.identifier = identifier; return this; } public Builder md5(String md5) { this.md5 = md5; return this; } public Builder sha1(String sha1) { this.sha1 = sha1; return this; } public Builder sha256(String sha256) { this.sha256 = sha256; return this; } public Builder size(Long size) { this.size = size; return this; } public Builder artifactQuality(Artifact.Quality artifactQuality) { this.artifactQuality = artifactQuality; return this; } public Builder targetRepository(TargetRepository targetRepository) { this.targetRepository = targetRepository; return this; } public Builder filename(String filename) { this.filename = filename; return this; } public Builder deployPath(String deployPath) { this.deployPath = deployPath; return this; } public Builder buildRecord(BuildRecord buildRecord) { this.buildRecords.add(buildRecord); return this; } public Builder buildRecords(Set<BuildRecord> buildRecords) { this.buildRecords = buildRecords; return this; } public Builder dependantBuildRecord(BuildRecord dependantBuildRecord) { this.dependantBuildRecords.add(dependantBuildRecord); return this; } public Builder dependantBuildRecords(Set<BuildRecord> dependantBuildRecords) { this.dependantBuildRecords = dependantBuildRecords; return this; } public Builder distributedInProductMilestones(Set<ProductMilestone> distributedInProductMilestones) { this.distributedInProductMilestones = distributedInProductMilestones; return this; } public Builder originUrl(String originUrl) { this.originUrl = originUrl; return this; } public Builder importDate(Date importDate) { this.importDate = importDate; return this; } } public static class IdentifierSha256 { private String identifier; private String sha256; public IdentifierSha256(String identifier, String sha256) { this.identifier = identifier; this.sha256 = sha256; } public String getSha256() { return sha256; } public String getIdentifier() { return identifier; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IdentifierSha256)) { return false; } IdentifierSha256 that = (IdentifierSha256) o; if (!identifier.equals(that.identifier)) { return false; } return sha256.equals(that.sha256); } @Override public int hashCode() { int result = identifier.hashCode(); result = 31 * result + sha256.hashCode(); return result; } } }
/** * Copyright 2016 Myrle Krantz * * 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.fineract.module.stellar; import com.google.common.base.Preconditions; import javafx.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stellar.sdk.Asset; import org.stellar.sdk.AssetTypeCreditAlphaNum; import org.stellar.sdk.KeyPair; import org.stellar.sdk.requests.EffectsRequestBuilder; import org.stellar.sdk.requests.EventListener; import org.stellar.sdk.responses.effects.AccountCreditedEffectResponse; import org.stellar.sdk.responses.effects.EffectResponse; import java.math.BigDecimal; import java.net.URI; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.fineract.module.stellar.StellarBridgeTestHelpers.getStellarAccountIdForTenantId; import static org.fineract.module.stellar.StellarBridgeTestHelpers.getStellarVaultAccountIdForTenantId; public class AccountListener { static class Credit { private final String toTenantId; private final BigDecimal amount; private final String assetCode; private final String issuingTenantVault; private Credit(final String toTenantId, final BigDecimal amount, final String assetCode, final String issuingTenantVault) { this.toTenantId = toTenantId; this.amount = amount; this.assetCode = assetCode; this.issuingTenantVault = issuingTenantVault; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Credit)) return false; Credit credit = (Credit) o; return Objects.equals(toTenantId, credit.toTenantId) && Objects.equals(assetCode, credit.assetCode) && (amount.compareTo(credit.amount) == 0) && Objects.equals(issuingTenantVault, credit.issuingTenantVault); } @Override public int hashCode() { return Objects.hash(toTenantId, amount, assetCode, issuingTenantVault); } @Override public String toString() { return "Credit{" + "toTenantId='" + toTenantId + '\'' + ", amount=" + amount + ", asset='" + assetCode + '@' + issuingTenantVault + '\'' + '}'; } } static class CreditMatcher { private final String toTenantId; private final BigDecimal amount; private final String assetCode; private final Set<String> issuingTenantVaults; private CreditMatcher(final String toTenantId, final BigDecimal amount, final String assetCode, final Set<String> issuingTenantVaults) { this.toTenantId = toTenantId; this.amount = amount; this.assetCode = assetCode; this.issuingTenantVaults = issuingTenantVaults; } boolean matches(final Credit credit) { return toTenantId.equals(credit.toTenantId) && amount.compareTo(credit.amount) == 0 && assetCode.equals(credit.assetCode) && issuingTenantVaults.contains(credit.issuingTenantVault); } @Override public String toString() { return "CreditMatcher{" + "toTenantId='" + toTenantId + '\'' + ", amount=" + amount + ", assetCode='" + assetCode + '\'' + ", issuingTenantVaults=" + issuingTenantVaults + '}'; } } static Set<String> vaultMatcher(final String... issuingTenantVaults) { final Set<String> ret = new HashSet<>(); Collections.addAll(ret, issuingTenantVaults); return ret; } static CreditMatcher creditMatcher(final String toTenantId, final BigDecimal amount, final String assetCode, final Set<String> issuingTenantVaults) { return new CreditMatcher(toTenantId, amount, assetCode, issuingTenantVaults); } static CreditMatcher creditMatcher(final String toTenantId, final BigDecimal amount, final String assetCode, final String issuingTenantVaults) { return new CreditMatcher(toTenantId, amount, assetCode, vaultMatcher(issuingTenantVaults)); } class Listener implements EventListener<EffectResponse> { @Override public void onEvent(final EffectResponse effect) { logger.info("OnEvent with cursor {}", effect.getPagingToken()); synchronized (operationsAlreadySeen) { if (operationsAlreadySeen.contains(effect.getPagingToken())) { return; } operationsAlreadySeen.add(effect.getPagingToken()); } if (effect instanceof AccountCreditedEffectResponse) { final String to = stellarIdToTenantId.get(effect.getAccount().getAccountId()); final BigDecimal amount = BigDecimal.valueOf(Double.parseDouble(((AccountCreditedEffectResponse) effect).getAmount())); final Asset asset = ((AccountCreditedEffectResponse) effect).getAsset(); final String code; final String issuer; if (asset instanceof AssetTypeCreditAlphaNum) { code = ((AssetTypeCreditAlphaNum) asset).getCode(); issuer = stellarVaultIdToTenantId .get(((AssetTypeCreditAlphaNum) asset).getIssuer().getAccountId()); } else { code = "XLM"; issuer = ""; } final Credit credit = new Credit(to, amount, code, issuer); logger.info("adding credit to queue {}", credit); credits.add(credit); } } } private Logger logger = LoggerFactory.getLogger(AccountListener.class.getName()); private final BlockingQueue<Credit> credits = new LinkedBlockingQueue<>(); private final Set<String> operationsAlreadySeen = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final Map<String, String> stellarIdToTenantId = new HashMap<>(); private final Map<String, String> stellarVaultIdToTenantId = new HashMap<>(); AccountListener(final String serverAddress, final String... tenantIds) { Preconditions.checkNotNull(tenantIds); Preconditions.checkState(tenantIds.length != 0); Arrays.asList(tenantIds).stream() .filter(tenantId -> tenantId != null) .map(tenantId -> new Pair<>(getStellarAccountIdForTenantId(tenantId), tenantId)) .filter(pair -> pair.getKey().isPresent()) .forEachOrdered(pair -> stellarIdToTenantId.put(pair.getKey().get(), pair.getValue()) ); Arrays.asList(tenantIds).stream() .filter(tenantId -> tenantId != null) .map(tenantId -> new Pair<>(getStellarVaultAccountIdForTenantId(tenantId), tenantId)) .filter(pair -> pair.getKey().isPresent()) .forEachOrdered(pair -> stellarVaultIdToTenantId.put(pair.getKey().get(), pair.getValue())); stellarIdToTenantId.entrySet().stream().forEach( mapEntry -> installPaymentListener(serverAddress, mapEntry.getKey())); } private void installPaymentListener(final String serverAddress, final String stellarAccountId) { final EffectsRequestBuilder effectsRequestBuilder = new EffectsRequestBuilder(URI.create(serverAddress)); effectsRequestBuilder.forAccount(KeyPair.fromAccountId(stellarAccountId)).cursor("now"); final Listener listener = new Listener(); effectsRequestBuilder.stream(listener); } public void waitForCredits(final long maxWait, final CreditMatcher... creditsExpected) throws Exception { waitForCredits(maxWait, Arrays.asList(creditsExpected)); } public void waitForCredits(final long maxWait, final List<CreditMatcher> creditsExpected) throws Exception { logger.info("Waiting maximum {} milliseconds for credits {}.", maxWait, creditsExpected); final List<CreditMatcher> incompleteCredits = new LinkedList<>(creditsExpected); final long startTime = new Date().getTime(); long waitedSoFar = 0; try (final Cleanup cleanup = new Cleanup()) { while (!incompleteCredits.isEmpty()) { final Credit credit = credits.poll(maxWait, TimeUnit.MILLISECONDS); final long now = new Date().getTime(); waitedSoFar = now - startTime; if (credit != null) { final Optional<CreditMatcher> match = incompleteCredits.stream() .filter(incompleteCredit -> incompleteCredit.matches(credit)).findAny(); match.ifPresent(incompleteCredits::remove); if (!match.isPresent()) cleanup.addStep(() -> credits.put(credit)); } if ((waitedSoFar > maxWait) && credits.isEmpty()) { logger.info("Waited {} milliseconds, and there are {} incomplete credits {} of the expected credits {}", waitedSoFar, incompleteCredits.size(), incompleteCredits, creditsExpected); return; } } logger.info("Waited {} milliseconds, and there are {} incomplete credits {} of the expected credits {}", waitedSoFar, incompleteCredits.size(), incompleteCredits, creditsExpected); } } public void waitForCreditsToAccumulate(final long maxWait, final CreditMatcher sumCreditExpected) throws Exception { logger.info("Waiting maximum {} milliseconds for creditMatcher accumulation to tenant {}.", maxWait, sumCreditExpected.toTenantId); BigDecimal missingBalance = sumCreditExpected.amount; final long startTime = new Date().getTime(); long waitedSoFar = 0; try (final Cleanup cleanup = new Cleanup()) { while (missingBalance.compareTo(BigDecimal.ZERO) > 0) { final Credit credit = credits.poll(maxWait, TimeUnit.MILLISECONDS); final long now = new Date().getTime(); waitedSoFar = now - startTime; if (credit != null) { final boolean matched = sumCreditExpected.assetCode.equals(credit.assetCode) && sumCreditExpected.issuingTenantVaults.contains(credit.issuingTenantVault) && sumCreditExpected.toTenantId.equals(credit.toTenantId); if (!matched) cleanup.addStep(() -> credits.put(credit)); else missingBalance = missingBalance.subtract(credit.amount); } if ((waitedSoFar > maxWait) && credits.isEmpty()) { logger.info("Waited {} milliseconds for creditMatcher accumulation is up. Missing balance is {} of {}", waitedSoFar, missingBalance, sumCreditExpected); return; } } logger.info("Waited {} milliseconds for creditMatcher accumulation is up. Missing balance is {} of {}", waitedSoFar, missingBalance, sumCreditExpected); } } }
/* * 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.gemstone.gemfire.pdx; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import com.gemstone.gemfire.pdx.PdxReader; import com.gemstone.gemfire.pdx.PdxSerializable; import com.gemstone.gemfire.pdx.PdxWriter; import org.json.JSONException; import org.json.JSONObject; enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } public class TestObjectForPdxFormatter implements PdxSerializable { private boolean p_bool; private byte p_byte; private short p_short; private int p_int; private long p_long; private float p_float; private double p_double; //wrapper private Boolean w_bool; private Byte w_byte; private Short w_short; private Integer w_int; private Long w_long; private BigInteger w_bigInt; private Float w_float; private BigDecimal w_bigDec; private Double w_double; private String w_string; //Primitive_Arrays private boolean[] p_boolArray; private byte[] p_byteArray; private short[] p_shortArray; private int[] p_intArray; private long[] p_longArray; private float[] p_floatArray; private double[] p_doubleArray; //Wrapper_Arrays private Boolean[] w_boolArray; private Byte[] w_byteArray; private Short[] w_shortArray; private Integer[] w_intArray; private Long[] w_longArray; private BigInteger[] w_bigIntArray; private Float[] w_floatArray; private BigDecimal[] w_bigDecArray; private Double[] w_doubleArray; private String [] w_strArray; //Collection Type: List, Set, Queue, Deque private List<String> c_list; private Set<Object> c_set; private Queue<String> c_queue; private Deque<Integer> c_deque; private Stack<String> c_stack; //Map - Classify Person objects by city Map<String, List<Employee>> m_empByCity; //Enum private Day day; private Employee employee; public TestObjectForPdxFormatter(){ } public String addClassTypeToJson(String json) throws JSONException { JSONObject jsonObj = new JSONObject(json); jsonObj.put("@type", "com.gemstone.gemfire.pdx.TestObjectForPdxFormatter"); return jsonObj.toString(); } public void defaultInitialization(){ employee = new Employee(1010L, "NilkanthKumar", "Patel"); //Initialize Map type member Employee e1 = new Employee(1L, "Nilkanth", "Patel"); Employee e2 = new Employee(2L, "Amey", "Barve"); Employee e3 = new Employee(3L, "Shankar", "Hundekar"); Employee e4 = new Employee(4L, "Avinash", "Dongre"); Employee e5 = new Employee(5L, "supriya", "Patil"); Employee e6 = new Employee(6L, "Rajesh", "Kumar"); Employee e7 = new Employee(7L, "Vishal", "Rao"); Employee e8 = new Employee(8L, "Hitesh", "Khamesara"); Employee e9 = new Employee(9L, "Sudhir", "Menon"); m_empByCity = new HashMap<String, List<Employee>>(); List<Employee> list1 = new ArrayList<Employee>(); List<Employee> list2 = new ArrayList<Employee>(); List<Employee> list3 = new ArrayList<Employee>(); list1.add(e1); list1.add(e2); list1.add(e3); list2.add(e4); list2.add(e5); list2.add(e6); list3.add(e7); list3.add(e8); list3.add(e9); m_empByCity.put("Ahmedabad", list1); m_empByCity.put("mumbai", list2); m_empByCity.put("Pune", list3); //Initialize Collection types members c_list = new ArrayList<String>(); c_list.add("Java"); c_list.add("scala"); c_list.add("closure"); c_set = new HashSet<Object>(); c_set.add("element 0"); c_set.add("element 1"); c_set.add("element 2"); c_queue = new PriorityQueue<String>(3); c_queue.add("short"); c_queue.add("very long indeed"); c_queue.add("medium"); c_deque = new ArrayDeque<Integer>(4); c_deque.add(15); c_deque.add(30); c_deque.add(20); c_deque.add(18); c_stack = new Stack(); c_stack.push( "bat" ); c_stack.push( "cat" ); c_stack.push( "dog" ); //Initialize primitive types members p_bool = true; p_byte = 101; p_short = 32001; p_int = 100001; p_long = 1234567898765432L; p_float = 123.456f; p_double = 98765.12345d; //Wrapper type member initialization w_bool = new Boolean(false); w_byte = new Byte((byte)11); w_short = new Short((short)101); w_int = new Integer(1001); w_long = new Long(987654321234567L); w_bigInt = new BigInteger("12345678910"); w_float = new Float(789.456f); w_bigDec = new BigDecimal(8866333); w_double = new Double(123456.9876d); w_string = new String("Nilkanth Patel"); //Initialization for members of type primitive arrays p_boolArray = new boolean[]{ true, false, false}; p_byteArray = new byte[]{10, 11, 12}; p_shortArray = new short[]{101, 102, 103}; p_intArray = new int[]{1001,1002, 1003, 1004, 1005, 1006}; p_longArray = new long[]{ 12345678910L, 12345678911L, 12345678912L }; p_floatArray = new float[]{ 123.45f, 456.78f, -91011.123f}; p_doubleArray = new double[]{1234.5678d, -91011.1213d, 1415.1617d }; //Initialization for members of type wrapper arrays w_boolArray = new Boolean[3]; w_byteArray = new Byte[3]; w_shortArray = new Short[3]; w_intArray = new Integer[3]; w_longArray = new Long[3]; w_floatArray = new Float[3]; w_doubleArray = new Double[3]; w_strArray = new String[3]; for (int i=0; i< 3; i++){ w_boolArray[i] = p_boolArray[i]; w_byteArray[i] = p_byteArray[i]; w_shortArray[i] = p_shortArray[i]; w_intArray[i] = p_intArray[i]; w_longArray[i] = p_longArray[i]; w_floatArray[i] = p_floatArray[i]; w_doubleArray[i] = p_doubleArray[i]; } w_bigIntArray = new BigInteger[] {BigInteger.ZERO, BigInteger.ONE, new BigInteger("12345678910")}; w_bigDecArray = new BigDecimal[] {BigDecimal.TEN, new BigDecimal("143.145"), new BigDecimal("10.01")}; w_strArray = new String[]{"Nilkanth", "Vishal", "Hitesh"}; //Enum type initialization day = Day.Thursday; } public TestObjectForPdxFormatter(boolean p_bool, byte p_byte, short p_short, int p_int, long p_long, float p_float, double p_double, Boolean w_bool, Byte w_byte, Short w_short, Integer w_int, Long w_long, BigInteger w_bigInt, Float w_float, BigDecimal w_bigDec, Double w_double, String w_string) { super(); this.p_bool = p_bool; this.p_byte = p_byte; this.p_short = p_short; this.p_int = p_int; this.p_long = p_long; this.p_float = p_float; this.p_double = p_double; this.w_bool = w_bool; this.w_byte = w_byte; this.w_short = w_short; this.w_int = w_int; this.w_long = w_long; this.w_bigInt = w_bigInt; this.w_float = w_float; this.w_bigDec = w_bigDec; this.w_double = w_double; this.w_string = w_string; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public List<String> getC_list() { return c_list; } public void setC_list(List<String> c_list) { this.c_list = c_list; } public Set<Object> getC_set() { return c_set; } public void setC_set(Set<Object> c_set) { this.c_set = c_set; } public Queue<String> getC_queue() { return c_queue; } public void setC_queue(Queue<String> c_queue) { this.c_queue = c_queue; } public Deque<Integer> getC_deque() { return c_deque; } public void setC_deque(Deque<Integer> c_deque) { this.c_deque = c_deque; } public Map<String, List<Employee>> getM_empByCity() { return m_empByCity; } public void setM_empByCity(Map<String, List<Employee>> m_empByCity) { this.m_empByCity = m_empByCity; } public Day getDay() { return day; } public void setDay(Day day) { this.day = day; } public boolean isP_bool() { return p_bool; } public void setP_bool(boolean p_bool) { this.p_bool = p_bool; } public byte getP_byte() { return p_byte; } public void setP_byte(byte p_byte) { this.p_byte = p_byte; } public short getP_short() { return p_short; } public void setP_short(short p_short) { this.p_short = p_short; } public int getP_int() { return p_int; } public void setP_int(int p_int) { this.p_int = p_int; } public long getP_long() { return p_long; } public void setP_long(long p_long) { this.p_long = p_long; } public float getP_float() { return p_float; } public void setP_float(float p_float) { this.p_float = p_float; } public double getP_double() { return p_double; } public void setP_double(double p_double) { this.p_double = p_double; } public Boolean getW_bool() { return w_bool; } public void setW_bool(Boolean w_bool) { this.w_bool = w_bool; } public Byte getW_byte() { return w_byte; } public void setW_byte(Byte w_byte) { this.w_byte = w_byte; } public Short getW_short() { return w_short; } public void setW_short(Short w_short) { this.w_short = w_short; } public Integer getW_int() { return w_int; } public void setW_int(Integer w_int) { this.w_int = w_int; } public Long getW_long() { return w_long; } public void setW_long(Long w_long) { this.w_long = w_long; } public BigInteger getW_bigInt() { return w_bigInt; } public void setW_bigInt(BigInteger w_bigInt) { this.w_bigInt = w_bigInt; } public Float getW_float() { return w_float; } public void setW_float(Float w_float) { this.w_float = w_float; } public BigDecimal getW_bigDec() { return w_bigDec; } public void setW_bigDec(BigDecimal w_bigDec) { this.w_bigDec = w_bigDec; } public Double getW_double() { return w_double; } public void setW_double(Double w_double) { this.w_double = w_double; } public String getW_string() { return w_string; } public void setW_string(String w_string) { this.w_string = w_string; } public boolean[] getP_boolArray() { return p_boolArray; } public void setP_boolArray(boolean[] p_boolArray) { this.p_boolArray = p_boolArray; } public byte[] getP_byteArray() { return p_byteArray; } public void setP_byteArray(byte[] p_byteArray) { this.p_byteArray = p_byteArray; } public short[] getP_shortArray() { return p_shortArray; } public void setP_shortArray(short[] p_shortArray) { this.p_shortArray = p_shortArray; } public int[] getP_intArray() { return p_intArray; } public void setP_intArray(int[] p_intArray) { this.p_intArray = p_intArray; } public long[] getP_longArray() { return p_longArray; } public void setP_longArray(long[] p_longArray) { this.p_longArray = p_longArray; } public float[] getP_floatArray() { return p_floatArray; } public void setP_floatArray(float[] p_floatArray) { this.p_floatArray = p_floatArray; } public double[] getP_doubleArray() { return p_doubleArray; } public void setP_doubleArray(double[] p_doubleArray) { this.p_doubleArray = p_doubleArray; } public Boolean[] getW_boolArray() { return w_boolArray; } public void setW_boolArray(Boolean[] w_boolArray) { this.w_boolArray = w_boolArray; } public Byte[] getW_byteArray() { return w_byteArray; } public void setW_byteArray(Byte[] w_byteArray) { this.w_byteArray = w_byteArray; } public Short[] getW_shortArray() { return w_shortArray; } public void setW_shortArray(Short[] w_shortArray) { this.w_shortArray = w_shortArray; } public Integer[] getW_intArray() { return w_intArray; } public void setW_intArray(Integer[] w_intArray) { this.w_intArray = w_intArray; } public Long[] getW_longArray() { return w_longArray; } public void setW_longArray(Long[] w_longArray) { this.w_longArray = w_longArray; } public BigInteger[] getW_bigIntArray() { return w_bigIntArray; } public void setW_bigIntArray(BigInteger[] w_bigIntArray) { this.w_bigIntArray = w_bigIntArray; } public Float[] getW_floatArray() { return w_floatArray; } public void setW_floatArray(Float[] w_floatArray) { this.w_floatArray = w_floatArray; } public BigDecimal[] getW_bigDecArray() { return w_bigDecArray; } public void setW_bigDecArray(BigDecimal[] w_bigDecArray) { this.w_bigDecArray = w_bigDecArray; } public Double[] getW_doubleArray() { return w_doubleArray; } public void setW_doubleArray(Double[] w_doubleArray) { this.w_doubleArray = w_doubleArray; } public String[] getW_strArray() { return w_strArray; } public void setW_strArray(String[] w_strArray) { this.w_strArray = w_strArray; } public Stack<String> getC_stack() { return c_stack; } public void setC_stack(Stack<String> c_stack) { this.c_stack = c_stack; } // Getters for returning field names public String getP_boolFN() { return "p_bool"; } public String getP_byteFN() { return "p_byte"; } public String getP_shortFN() { return "p_short"; } public String getP_intFN() { return "p_int"; } public String getP_longFN() { return "p_long"; } public String getP_floatFn() { return "p_float"; } public String getP_doubleFN() { return "p_double"; } public String getW_boolFN() { return "w_bool"; } public String getW_byteFN() { return "w_byte"; } public String getW_shortFN() { return "w_short"; } public String getW_intFN() { return "w_int"; } public String getW_longFN() { return "w_long"; } public String getW_bigIntFN() { return "w_bigInt"; } public String getW_floatFN() { return "w_float"; } public String getW_bigDecFN() { return "w_bigDec"; } public String getW_doubleFN() { return "w_double"; } public String getW_stringFN() { return "w_string"; } public String getP_boolArrayFN() { return "p_boolArray"; } public String getP_byteArrayFN() { return "p_byteArray"; } public String getP_shortArrayFN() { return "p_shortArray"; } public String getP_intArrayFN() { return "p_intArray"; } public String getP_longArrayFN() { return "p_longArray"; } public String getP_floatArrayFN() { return "p_floatArray"; } public String getP_doubleArrayFN() { return "p_doubleArray"; } public String getW_boolArrayFN() { return "w_boolArray"; } public String getW_byteArrayFN() { return "w_byteArray"; } public String getW_shortArrayFN() { return "w_shortArray"; } public String getW_intArrayFN() { return "w_intArray"; } public String getW_longArrayFN() { return "w_longArray"; } public String getW_bigIntArrayFN() { return "w_bigIntArray"; } public String getW_floatArrayFN() { return "w_floatArray"; } public String getW_bigDecArrayFN() { return "w_bigDecArray"; } public String getW_doubleArrayFN() { return "w_doubleArray"; } public String getW_strArrayFN() { return "w_strArray"; } public String getC_listFN() { return "c_list"; } public String getC_setFN() { return "c_set"; } public String getC_queueFN() { return "c_queue"; } public String getC_dequeFN() { return "c_deque"; } public String getC_stackFN() { return "c_stack"; } public String getM_empByCityFN() { return "m_empByCity"; } public String getDayFN() { return "day"; } @Override public void fromData(PdxReader in) { this.p_bool = in.readBoolean("p_bool"); this.p_byte = in.readByte("p_byte"); this.p_short = in.readShort("p_short"); this.p_int = in.readInt("p_int"); this.p_long = in.readLong("p_long"); this.p_float = in.readFloat("p_float"); this.p_double = in.readDouble("p_double"); this.w_bool = in.readBoolean("w_bool"); this.w_byte = in.readByte("w_byte"); this.w_short = in.readShort("w_short"); this.w_int = in.readInt("w_int"); this.w_long = in.readLong("w_long"); this.w_float = in.readFloat("w_float"); this.w_double = in.readDouble("w_double"); this.w_string = in.readString("w_string"); this.w_bigInt = (BigInteger) in.readObject("w_bigInt"); this.w_bigDec = (BigDecimal) in.readObject("w_bigDec"); // P_Arrays this.p_boolArray = in.readBooleanArray("p_boolArray"); this.p_byteArray = in.readByteArray("p_byteArray"); this.p_shortArray = in.readShortArray("p_shortArray"); this.p_intArray = in.readIntArray("p_intArray"); this.p_longArray = in.readLongArray("p_longArray"); this.p_floatArray = in.readFloatArray("p_floatArray"); this.p_doubleArray = in.readDoubleArray("p_doubleArray"); // W_Arrays this.w_boolArray = (Boolean[]) in.readObjectArray("w_boolArray"); this.w_byteArray = (Byte[]) in.readObjectArray("w_byteArray"); this.w_shortArray = (Short[]) in.readObjectArray("w_shortArray"); this.w_intArray = (Integer[]) in.readObjectArray("w_intArray"); this.w_longArray = (Long[]) in.readObjectArray("w_longArray"); this.w_floatArray = (Float[]) in.readObjectArray("w_floatArray"); this.w_doubleArray = (Double[]) in.readObjectArray("w_doubleArray"); this.w_strArray = in.readStringArray("w_strArray"); this.w_bigIntArray = (BigInteger[]) in.readObjectArray("w_bigIntArray"); this.w_bigDecArray = (BigDecimal[]) in.readObjectArray("w_bigDecArray"); // Collections this.c_list = (List<String>) in.readObject("c_list"); this.c_set = (Set<Object>) in.readObject("c_set"); this.c_queue = (Queue<String>) in.readObject("c_queue"); this.c_deque = (Deque<Integer>) in.readObject("c_deque"); this.c_stack = (Stack<String>) in.readObject("c_stack"); // Map this.m_empByCity = (Map<String, List<Employee>>) in.readObject("m_empByCity"); // Enum this.day = (Day) (in.readObject("day")); //User Object this.employee = (Employee) in.readObject("employee"); //String type= in.readString("@type"); } @Override public void toData(PdxWriter out) { //if(m_unreadFields != null){ out.writeUnreadFields(m_unreadFields); } out.writeBoolean("p_bool", this.p_bool); out.writeByte("p_byte", this.p_byte); out.writeShort("p_short", p_short); out.writeInt("p_int", p_int); out.writeLong("p_long", p_long); out.writeFloat("p_float", p_float); out.writeDouble("p_double", p_double); out.writeBoolean("w_bool", w_bool); out.writeByte("w_byte", w_byte); out.writeShort("w_short", w_short); out.writeInt("w_int", w_int); out.writeLong("w_long", w_long); out.writeFloat("w_float", w_float); out.writeDouble("w_double", w_double); out.writeString("w_string", w_string); out.writeObject("w_bigInt", w_bigInt); out.writeObject("w_bigDec", w_bigDec); // P_Arrays out.writeBooleanArray("p_boolArray", p_boolArray); out.writeByteArray("p_byteArray", p_byteArray); out.writeShortArray("p_shortArray", p_shortArray); out.writeIntArray("p_intArray", p_intArray); out.writeLongArray("p_longArray", p_longArray); out.writeFloatArray("p_floatArray", p_floatArray); out.writeDoubleArray("p_doubleArray", p_doubleArray); // W_Arrays out.writeObjectArray("w_boolArray", w_boolArray); out.writeObjectArray("w_byteArray", w_byteArray); out.writeObjectArray("w_shortArray", w_shortArray); out.writeObjectArray("w_intArray", w_intArray); out.writeObjectArray("w_longArray", w_longArray); out.writeObjectArray("w_floatArray", w_floatArray); out.writeObjectArray("w_doubleArray", w_doubleArray); out.writeStringArray("w_strArray", w_strArray); out.writeObjectArray("w_bigIntArray", w_bigIntArray); out.writeObjectArray("w_bigDecArray", w_bigDecArray); // Collections out.writeObject("c_list", c_list); out.writeObject("c_set", c_set); out.writeObject("c_queue", c_queue); out.writeObject("c_deque", c_deque); out.writeObject("c_stack", c_stack); // Map out.writeObject("m_empByCity", m_empByCity); // Enum out.writeObject("day", day); out.writeObject("employee", this.employee); //out.writeString("@type", "com.gemstone.gemfire.pdx.TestObjectForPdxFormatter"); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestObjectForPdxFormatter other = (TestObjectForPdxFormatter) obj; // primitive type if (p_bool != other.p_bool) return false; if (p_byte != other.p_byte) return false; if (p_short != other.p_short) return false; if (p_int != other.p_int) return false; if (p_long != other.p_long) return false; if (p_float != other.p_float) return false; if (p_double != other.p_double) return false; // wrapper type if (w_bool.booleanValue() != other.w_bool.booleanValue()) return false; if (w_byte.byteValue() != other.w_byte.byteValue()) return false; if (w_short.shortValue() != other.w_short.shortValue()) return false; if (w_int.intValue() != other.w_int.intValue()) return false; if (w_long.longValue() != other.w_long.longValue()) return false; if (w_float.floatValue() != other.w_float.floatValue()) return false; if (w_double.doubleValue() != other.w_double.doubleValue()) return false; if (!w_string.equals(other.w_string)) return false; if (w_bigInt.longValue() != other.w_bigInt.longValue()) return false; if (w_bigDec.longValue() != other.w_bigDec.longValue()) return false; // Primitive arrays if (!Arrays.equals(p_boolArray, other.p_boolArray)) return false; if (!Arrays.equals(p_byteArray, other.p_byteArray)) return false; if (!Arrays.equals(p_shortArray, other.p_shortArray)) return false; if (!Arrays.equals(p_intArray, other.p_intArray)) return false; if (!Arrays.equals(p_longArray, other.p_longArray)) return false; if (!Arrays.equals(p_floatArray, other.p_floatArray)) return false; if (!Arrays.equals(p_doubleArray, other.p_doubleArray)) return false; // wrapper Arrays if (!Arrays.equals(w_boolArray, other.w_boolArray)) return false; if (!Arrays.equals(w_byteArray, other.w_byteArray)) return false; if (!Arrays.equals(w_shortArray, other.w_shortArray)) return false; if (!Arrays.equals(w_intArray, other.w_intArray)) return false; if (!Arrays.equals(w_longArray, other.w_longArray)) return false; if (!Arrays.equals(w_floatArray, other.w_floatArray)) return false; if (!Arrays.equals(w_doubleArray, other.w_doubleArray)) return false; if (!Arrays.equals(w_strArray, other.w_strArray)) return false; if (!Arrays.equals(w_bigIntArray, other.w_bigIntArray)) return false; if (!Arrays.equals(w_bigDecArray, other.w_bigDecArray)) return false; // comparing Collections based on content, order not considered if (!(c_list.size() == other.c_list.size() && c_list.containsAll(other.c_list) && other.c_list.containsAll(c_list))) return false; if (!(c_set.size() == other.c_set.size() && c_set.containsAll(other.c_set) && other.c_set.containsAll(c_set))) return false; if (!(c_queue.size() == other.c_queue.size() && c_queue.containsAll(other.c_queue) && other.c_queue.containsAll(c_queue))) return false; if (!(c_deque.size() == other.c_deque.size() && c_deque.containsAll(other.c_deque) && other.c_deque.containsAll(c_deque))) return false; // map comparision. if (!(compareMaps(m_empByCity, other.m_empByCity))) return false; // Enum validation if (!(day.equals(other.day))) return false; return true; } boolean compareMaps(Map m1, Map m2) { if (m1.size() != m2.size()) return false; for (Object key : m1.keySet()) if (!m1.get(key).equals(m2.get(key))) return false; return true; } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.job.plan; import static org.mockito.Mockito.mock; import alluxio.client.file.FileSystem; import alluxio.client.file.FileSystemContext; import alluxio.collections.Pair; import alluxio.grpc.JobCommand; import alluxio.job.JobConfig; import alluxio.job.plan.PlanDefinition; import alluxio.job.plan.PlanDefinitionRegistry; import alluxio.job.JobServerContext; import alluxio.job.SelectExecutorsContext; import alluxio.job.wire.Status; import alluxio.job.wire.TaskInfo; import alluxio.master.job.command.CommandManager; import alluxio.underfs.UfsManager; import alluxio.wire.WorkerInfo; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Tests {@link PlanCoordinator}. */ @RunWith(PowerMockRunner.class) @PrepareForTest({PlanDefinitionRegistry.class, FileSystemContext.class}) public final class PlanCoordinatorTest { private WorkerInfo mWorkerInfo; private long mJobId; private JobConfig mJobconfig; private JobServerContext mJobServerContext; private CommandManager mCommandManager; private PlanDefinition<JobConfig, Serializable, Serializable> mPlanDefinition; private List<WorkerInfo> mWorkerInfoList; @Before public void before() throws Exception { mCommandManager = new CommandManager(); // Create mock JobServerContext FileSystem fs = mock(FileSystem.class); FileSystemContext fsCtx = PowerMockito.mock(FileSystemContext.class); UfsManager ufsManager = Mockito.mock(UfsManager.class); mJobServerContext = new JobServerContext(fs, fsCtx, ufsManager); // Create mock job info. mJobconfig = Mockito.mock(JobConfig.class, Mockito.withSettings().serializable()); Mockito.when(mJobconfig.getName()).thenReturn("mock"); mJobId = 1; // Create mock job definition. @SuppressWarnings("unchecked") PlanDefinition<JobConfig, Serializable, Serializable> mockPlanDefinition = Mockito.mock(PlanDefinition.class); PlanDefinitionRegistry singleton = PowerMockito.mock(PlanDefinitionRegistry.class); Whitebox.setInternalState(PlanDefinitionRegistry.class, "INSTANCE", singleton); Mockito.when(singleton.getJobDefinition(mJobconfig)).thenReturn(mockPlanDefinition); mPlanDefinition = mockPlanDefinition; // Create test worker. mWorkerInfo = new WorkerInfo(); mWorkerInfo.setId(0); mWorkerInfoList = Lists.newArrayList(mWorkerInfo); } @Test public void createJobCoordinator() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator.create( mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); List<JobCommand> commands = mCommandManager.pollAllPendingCommands(mWorkerInfo.getId()); Assert.assertEquals(1, commands.size()); Assert.assertEquals(mJobId, commands.get(0).getRunTaskCommand().getJobId()); Assert.assertEquals(0, commands.get(0).getRunTaskCommand().getTaskId()); } @Test public void updateStatusFailure() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); setTasksWithStatuses(planCoordinator, Status.RUNNING, Status.FAILED, Status.COMPLETED); Assert.assertEquals(Status.FAILED, planCoordinator.getPlanInfoWire(true).getStatus()); Assert.assertTrue( planCoordinator.getPlanInfoWire(true).getErrorMessage().contains("Task execution failed")); } @Test public void updateStatusFailureOverCancel() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); setTasksWithStatuses(planCoordinator, Status.RUNNING, Status.FAILED, Status.COMPLETED); Assert.assertEquals(Status.FAILED, planCoordinator.getPlanInfoWire(true).getStatus()); } @Test public void updateStatusCancel() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); setTasksWithStatuses(planCoordinator, Status.CANCELED, Status.RUNNING, Status.COMPLETED); Assert.assertEquals(Status.CANCELED, planCoordinator.getPlanInfoWire(true).getStatus()); } @Test public void updateStatusRunning() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); setTasksWithStatuses(planCoordinator, Status.COMPLETED, Status.RUNNING, Status.COMPLETED); Assert.assertEquals(Status.RUNNING, planCoordinator.getPlanInfoWire(true).getStatus()); } @Test public void updateStatusCompleted() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); setTasksWithStatuses(planCoordinator, Status.COMPLETED, Status.COMPLETED, Status.COMPLETED); Assert.assertEquals(Status.COMPLETED, planCoordinator.getPlanInfoWire(true).getStatus()); } @Test public void updateStatusJoinFailure() throws Exception { mockSelectExecutors(mWorkerInfo); Mockito .when(mPlanDefinition.join(Mockito.eq(mJobconfig), Mockito.anyMapOf(WorkerInfo.class, Serializable.class))) .thenThrow(new UnsupportedOperationException("test exception")); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); setTasksWithStatuses(planCoordinator, Status.COMPLETED, Status.COMPLETED, Status.COMPLETED); Assert.assertEquals(Status.FAILED, planCoordinator.getPlanInfoWire(true).getStatus()); Assert.assertEquals("test exception", planCoordinator.getPlanInfoWire(true).getErrorMessage()); } @Test public void noTasks() throws Exception { mockSelectExecutors(); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); Assert.assertEquals(Status.COMPLETED, planCoordinator.getPlanInfoWire(true).getStatus()); } @Test public void failWorker() throws Exception { mockSelectExecutors(mWorkerInfo); PlanCoordinator planCoordinator = PlanCoordinator.create(mCommandManager, mJobServerContext, mWorkerInfoList, mJobId, mJobconfig, null); planCoordinator.failTasksForWorker(mWorkerInfo.getId()); Assert.assertEquals(Status.FAILED, planCoordinator.getPlanInfoWire(true).getStatus()); } /** * @param workerInfos the worker infos to return from the mocked selectExecutors method */ private void mockSelectExecutors(WorkerInfo... workerInfos) throws Exception { Set<Pair<WorkerInfo, Serializable>> taskAddressToArgs = Sets.newHashSet(); for (WorkerInfo workerInfo : workerInfos) { taskAddressToArgs.add(new Pair<>(workerInfo, null)); } Mockito .when(mPlanDefinition.selectExecutors(Mockito.eq(mJobconfig), Mockito.eq(Lists.newArrayList(mWorkerInfo)), Mockito.any(SelectExecutorsContext.class))) .thenReturn(taskAddressToArgs); } private void setTasksWithStatuses(PlanCoordinator planCoordinator, Status... statuses) throws Exception { List<TaskInfo> taskInfos = new ArrayList<>(); int taskId = 0; for (Status status : statuses) { taskInfos.add(new TaskInfo().setTaskId(taskId++).setJobId(mJobId).setStatus(status)); } planCoordinator.updateTasks(taskInfos); } }
package edu.missouristate.mote.effectsizes; import edu.missouristate.mote.Constants; import edu.missouristate.mote.propertygrid.CategoryAnnotation; import edu.missouristate.mote.propertygrid.DescriptionAnnotation; import edu.missouristate.mote.propertygrid.IndexAnnotation; import edu.missouristate.mote.propertygrid.NameAnnotation; /** * Eta-squared, F test omnibus. */ public final class Eta2FOmni extends AbstractNonCentralTest { // ************************************************************************* // INPUT FIELDS // ************************************************************************* private double confidence; private double ssEffect; private double ssTotal; private double dfEffect; private double dfError; private double testStatistic; // ************************************************************************* // RESULT FIELDS // ************************************************************************* private transient double measure; private transient double lowerMeasure; private transient double lowerNc; private transient double[][] lowerPdf; private transient double upperMeasure; private transient double upperNc; private transient double[][] upperPdf; /** * True if the measure should be calculated from inputs; false if from F */ private transient boolean useInputs; // ************************************************************************* // CONSTRUCTORS // ************************************************************************* /** * Initialize a new instance of an Eta2FOmni. */ public Eta2FOmni() { super(); reset(); } // ************************************************************************* // PRIVATE METHODS // ************************************************************************* /** * Return the value for eta-squared. * * @param ssEffect sum of squares of the effect * @param ssTotal sum of squares total * @return d value */ private static double calcEtaSquared(final double ssEffect, final double ssTotal) { if (ssTotal != 0) { return ssEffect / ssTotal; } else { return 0; } } /** * Return the value for F. * * @param ms mean of the squares * @param mse mean squared error * @return F value */ private static double calcF(final double ms, final double mse) { if (mse == 0) { return 0; } else { return ms / mse; } } /** * Calculate the effect size. */ private void calculate() { setErrorMessage(""); if (useInputs) { testStatistic = calcF(getMs(), getMse()); measure = calcEtaSquared(ssEffect, ssTotal); } else { measure = (dfEffect * testStatistic) / ((dfEffect * testStatistic) + dfError); } if (testStatistic <= 0 || Double.isNaN(testStatistic)) { setErrorMessage("F is zero"); doStateChanged(); return; } // Lower, upper non-centrality parameters final double alpha = 1 - confidence; try { lowerNc = ConfIntNcf.findNonCentrality(testStatistic, dfEffect, dfError, 1 - (alpha * 0.5)); upperNc = ConfIntNcf.findNonCentrality(testStatistic, dfEffect, dfError, alpha * 0.5); } catch (ArithmeticException ex) { setErrorMessage(ex.getLocalizedMessage()); doStateChanged(); return; } // Lower, upper measure lowerMeasure = lowerNc / (lowerNc + dfEffect + dfError + 1); upperMeasure = upperNc / (upperNc + dfEffect + dfError + 1); // PDF curves lowerPdf = ConfIntNcf.createPdf(testStatistic, dfEffect, dfError, lowerNc, lowerNc, upperNc); upperPdf = ConfIntNcf.createPdf(testStatistic, dfEffect, dfError, upperNc, lowerNc, upperNc); doStateChanged(); } // ************************************************************************* // PUBLIC METHODS // ************************************************************************* @Override public String getMeasureName() { return Constants.ETA_LOWER + Constants.SUPERSCRIPT2; } @Override public String getMeasureSymbol() { return Constants.ETA_LOWER + Constants.SUPERSCRIPT2; } @Override public String getTestName() { return "F Test Omnibus"; } @Override public String getTestStatisticSymbol() { return "F"; } @Override public void reset() { useInputs = true; setSsEffect(1); setSsTotal(1); setDfEffect(0); setDfError(0); setConfidence(0.95); } // ************************************************************************* // INPUT GETTER/SETTERS // ************************************************************************* @CategoryAnnotation(value = Constants.INPUT_CATEGORY) @NameAnnotation(value = "Effect Sum of Squares") @IndexAnnotation(value = 1) @DescriptionAnnotation(value = "Sum of squares of the effect.") public double getSsEffect() { return ssEffect; } public void setSsEffect(final double value) { ssEffect = value; useInputs = true; calculate(); } @CategoryAnnotation(value = Constants.INPUT_CATEGORY) @NameAnnotation(value = "Total Sum of Squares") @IndexAnnotation(value = 2) @DescriptionAnnotation(value = "Total sum of squares.") public double getSsTotal() { return ssTotal; } public void setSsTotal(final double value) { ssTotal = value; useInputs = true; calculate(); } @CategoryAnnotation(value = Constants.INPUT_CATEGORY) @NameAnnotation(value = "Effect Deg Free") @IndexAnnotation(value = 3) @DescriptionAnnotation(value = "Degrees of freedom of the effect.") public double getDfEffect() { return dfEffect; } public void setDfEffect(final double value) { dfEffect = Math.max(Constants.MIN_DF, value); useInputs = true; calculate(); } @CategoryAnnotation(value = Constants.INPUT_CATEGORY) @NameAnnotation(value = "Error Deg Free") @IndexAnnotation(value = 4) @DescriptionAnnotation(value = "Degrees of freedom of the error.") public double getDfError() { return dfError; } public void setDfError(final double value) { dfError = Math.max(Constants.MIN_DF, value); useInputs = true; calculate(); } @CategoryAnnotation(value = Constants.INPUT_CATEGORY) @NameAnnotation(value = "F Statistic") @IndexAnnotation(value = 5) @DescriptionAnnotation(value = "F statistic. If this value is entered, " + "the sums of squares will clear to zero and " + Constants.ETA_LOWER + Constants.SUPERSCRIPT2 + " will be " + "calculated from the F statistic.") @Override public double getTestStatistic() { return testStatistic; } public void setTestStatistic(final double value) { testStatistic = value; useInputs = false; ssEffect = 0; ssTotal = 0; calculate(); } @CategoryAnnotation(value = Constants.INPUT_CATEGORY) @NameAnnotation(value = "Confidence (1 - " + Constants.ALPHA_LOWER + ")") @IndexAnnotation(value = 6) @DescriptionAnnotation(value = "Confidence interval expressed as a " + "percentage in the range 0...1.") @Override public double getConfidence() { return confidence; } public void setConfidence(final double value) { confidence = Math.min(Constants.MAX_CONFIDENCE, Math.max(Constants.MIN_CONFIDENCE, value)); calculate(); } // ************************************************************************* // DERIVED GETTERS // ************************************************************************* @CategoryAnnotation(value = Constants.DERIVED_CATEGORY) @NameAnnotation(value = "Error Sum of Squares") @IndexAnnotation(value = 8) @DescriptionAnnotation(value = "Sum of squares of the error.") public double getSsError() { return ssTotal - ssEffect; } @CategoryAnnotation(value = Constants.DERIVED_CATEGORY) @NameAnnotation(value = "Effect Mean Squares") @IndexAnnotation(value = 9) @DescriptionAnnotation(value = "Mean of the effect squares.") public double getMs() { return ssEffect / dfEffect; } @CategoryAnnotation(value = Constants.DERIVED_CATEGORY) @NameAnnotation(value = "Error Mean Squares") @IndexAnnotation(value = 10) @DescriptionAnnotation(value = "Mean of the error squares.") public double getMse() { return getSsError() / dfError; } // ************************************************************************* // RESULT GETTERS // ************************************************************************* @Override public double getAlpha() { return 1 - confidence; } @CategoryAnnotation(value = Constants.OUTPUT_CATEGORY) @NameAnnotation(value = "Lower " + Constants.ETA_LOWER + Constants.SUPERSCRIPT2) @IndexAnnotation(value = 11) @DescriptionAnnotation(value = "Minimum value of " + Constants.ETA_LOWER + Constants.SUPERSCRIPT2 + " on the confidence interval.") @Override public double getLowerMeasure() { return lowerMeasure; } @CategoryAnnotation(value = Constants.OUTPUT_CATEGORY) @NameAnnotation(value = Constants.ETA_LOWER + Constants.SUPERSCRIPT2) @IndexAnnotation(value = 12) @DescriptionAnnotation(value = Constants.ETA_LOWER + Constants.SUPERSCRIPT2 + ".") @Override public double getMeasure() { return measure; } @CategoryAnnotation(value = Constants.OUTPUT_CATEGORY) @NameAnnotation(value = "Upper " + Constants.ETA_LOWER + Constants.SUPERSCRIPT2) @IndexAnnotation(value = 13) @DescriptionAnnotation(value = "Maximum value of " + Constants.ETA_LOWER + Constants.SUPERSCRIPT2 + " on the confidence interval.") @Override public double getUpperMeasure() { return upperMeasure; } @CategoryAnnotation(value = Constants.OUTPUT_CATEGORY) @NameAnnotation(value = "Lower NC (" + Constants.LAMBDA_LOWER + "min)") @IndexAnnotation(value = 14) @DescriptionAnnotation(value = "Non-centrality parameter (" + Constants.LAMBDA_LOWER + ") corresponding to the minimum value of " + "the measure on the confidence interval.") @Override public double getLowerNc() { return lowerNc; } @Override public double[][] getLowerPdf() { return lowerPdf; } @CategoryAnnotation(value = Constants.OUTPUT_CATEGORY) @NameAnnotation(value = "Upper NC (" + Constants.LAMBDA_LOWER + "max)") @IndexAnnotation(value = 15) @DescriptionAnnotation(value = "Non-centrality parameter (" + Constants.LAMBDA_LOWER + ") corresponding to the maximum value of " + "the measure on the confidence interval.") @Override public double getUpperNc() { return upperNc; } @Override public double[][] getUpperPdf() { return upperPdf; } }
/******************************************************************************* * Copyright (c) 2016 Alex Shapiro - github.com/shpralex * This program and the accompanying materials * are made available under the terms of the The MIT License (MIT) * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. *******************************************************************************/ package com.sproutlife.panel.gamepanel; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.OutputStream; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import com.sproutlife.panel.PanelController; import com.sproutlife.renderer.RendererUtils; public class ImageManager { public interface PaintImageListener { public void paintImage(); } public enum LogoStyle { None, Small, Large; } private static Color BACK_COLOR = Color.white; private static int SAVE_IMAGE_PAD = 0; public static void setBackgroundColor(Color color) { BACK_COLOR = color; } public static void setImagePad(int pad) { SAVE_IMAGE_PAD = pad; } private PanelController panelController; private LogoStyle logoStyle; public static final Image applicationLogoImage = null; public static Image smallLogoImage = null; public static Image largeLogoImage = null; private Image drawImage; private boolean imageIsDirty; private String message = null; private boolean enablePaint = true; //Set enable paint to false to prevent updating a dirty image protected Vector<PaintImageListener> paintImageListeners; public ImageManager(PanelController panelController, LogoStyle logoStyle) { this.panelController = panelController; this.logoStyle = logoStyle; paintImageListeners = new Vector<PaintImageListener>(); try { smallLogoImage = new ImageIcon(ImageManager.class.getResource("/images/SproutLife_Logo.png")).getImage(); } catch (Exception ex) { //This exception probably means that /resources/ should be added to the classpath ex.printStackTrace(); } largeLogoImage = smallLogoImage; } private boolean testAndClearImageDirtyFlag() { // Image Dirty Flag must be cleared immediately after testing to avoid // potential race conditions when repainting from multiple threads at once. boolean imageWasDirty = imageIsDirty && enablePaint; if (enablePaint) { imageIsDirty = false; } return imageWasDirty; } public void setEnablePaint(boolean enablePaint) { this.enablePaint = enablePaint; } private void flagImageAsDirty() { imageIsDirty = true; } protected synchronized void paint(Graphics2D g2) { if ( drawImage == null ) { createImage(); } if ( testAndClearImageDirtyFlag() ) { Image logoImage = getLogoImage(); paintImage(drawImage, logoImage, panelController.getBoardRenderer().getTransform()); firePaintImage(); } g2.drawImage(drawImage, 0, 0, null); } protected Image getLogoImage() { if ( logoStyle == LogoStyle.Large ) { return largeLogoImage; } else if ( logoStyle == LogoStyle.Small ) { return applicationLogoImage; } return null; } public Image getLogoImage(double w, double h) { Image logoImage = smallLogoImage; if ( w > 1024 && h > 768 ) { logoImage = largeLogoImage; } return logoImage; } public void repaintNewImage() { panelController.getBoardRenderer().updateVisibleRenderers(panelController.getScrollController().getViewportRendererBounds()); flagImageAsDirty(); panelController.getScrollPanel().repaint(); } protected void paintImage(Image image, Image logoImage, AffineTransform transform) { if ( panelController.getBoardRenderer() != null ) { paintBackground(image); Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setTransform(transform); panelController.getBoardRenderer().paint(g2); // Currently when the application is running the logoImage is null, but when a // png/gif is being exported, the logoImage is set. if (logoImage==null) { paintMessage(image); } g2.setTransform(new AffineTransform()); if ( logoImage != null ) { // draw the logo in the bottom right corner g2.setTransform(new AffineTransform()); g2.drawImage(logoImage, image.getWidth(null)-logoImage.getWidth(null), image.getHeight(null)-logoImage.getHeight(null)-5, null); } } } protected ByteArrayOutputStream paintImagePdf(Image logoImage, int width, int height, AffineTransform transform) { try { Class<?> documentClass = Class.forName("com.lowagie.text.Document"); Class<?> pageSizeClass = Class.forName("com.lowagie.text.PageSize"); Class<?> defaultFontMapperClass = Class.forName("com.lowagie.text.pdf.DefaultFontMapper"); Class<?> fontMapperClass = Class.forName("com.lowagie.text.pdf.FontMapper"); Class<?> pdfContentByteClass = Class.forName("com.lowagie.text.pdf.PdfContentByte"); Class<?> pdfTemplateClass = Class.forName("com.lowagie.text.pdf.PdfTemplate"); Class<?> pdfWriterClass = Class.forName("com.lowagie.text.pdf.PdfWriter"); Class<?> rectangleClass = Class.forName("com.lowagie.text.Rectangle"); /* Class<?> documentClass = Class.forName("com.itextpdf.text.Document"); Class<?> pageSizeClass = Class.forName("com.itextpdf.text.PageSize"); Class<?> defaultFontMapperClass = Class.forName("com.itextpdf.text.pdf.DefaultFontMapper"); Class<?> fontMapperClass = Class.forName("com.itextpdf.text.pdf.FontMapper"); Class<?> pdfContentByteClass = Class.forName("com.itextpdf.text.pdf.PdfContentByte"); Class<?> pdfTemplateClass = Class.forName("com.itextpdf.text.pdf.PdfTemplate"); Class<?> pdfWriterClass = Class.forName("com.itextpdf.text.pdf.PdfWriter"); Class<?> rectangleClass = Class.forName("com.itextpdf.text.Rectangle"); */ if ( panelController.getBoardRenderer() != null ) { Object doc = documentClass.getConstructor().newInstance(); documentClass.getMethod("addProducer").invoke(doc); documentClass.getMethod("addTitle",String.class).invoke(doc,"Navigator"); Object rectangle = pageSizeClass.getField("_11X17").get(pageSizeClass); //doc.setPageSize(new com.lowagie.text.Rectangle(PageSize.LETTER.getHeight()*2,PageSize.LETTER.getWidth()*2)); documentClass.getMethod("setPageSize", rectangleClass).invoke(doc,rectangleClass.getMethod("rotate").invoke(rectangle)); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); Object docWriter = null; Object dc = null; try { //docWriter = PdfWriter.getInstance((Document) doc, baosPDF); docWriter = pdfWriterClass.getMethod("getInstance",documentClass,OutputStream.class).invoke(pdfWriterClass, doc, baosPDF); //doc.open(); documentClass.getMethod("open").invoke(doc); //dc = docWriter.getDirectContent(); dc = pdfWriterClass.getMethod("getDirectContent").invoke(docWriter); } catch (Exception ex) { ex.printStackTrace();} // get a pdf template from the direct content //PdfTemplate tp = ((PdfContentByte) dc).createTemplate(width, height); Object tp = pdfContentByteClass.getMethod("createTemplate",float.class, float.class).invoke(dc,width,height); // create an AWT renderer from the pdf template //Graphics2D g2 = tp.createGraphics(image.getWidth(null), image.getHeight(null), new DefaultFontMapper() ); Graphics2D g2 = (Graphics2D) pdfTemplateClass.getMethod("createGraphics",float.class,float.class,fontMapperClass).invoke( tp,width, height,defaultFontMapperClass.getConstructor().newInstance()); paintBackground(g2,width,height); //Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setTransform(transform); AffineTransform oldTransform = new AffineTransform(); oldTransform.setTransform(panelController.getBoardRenderer().getTransform()); panelController.getBoardRenderer().getTransform().setToScale(1,1); //panelController.getBoardRenderer().updateLabels(); panelController.getBoardRenderer().paint(g2); panelController.getBoardRenderer().getTransform().setTransform(oldTransform); if ( logoImage != null ) { // draw the logo in the bottom right corner g2.setTransform(new AffineTransform()); g2.drawImage(logoImage, width-logoImage.getWidth(null), height-logoImage.getHeight(null), null); } //((PdfContentByte) dc).addTemplate(tp, (1224-image.getWidth(null))/2 ,(792-image.getHeight(null))/2); pdfContentByteClass.getMethod("addTemplate", pdfTemplateClass,float.class,float.class).invoke( dc, tp,(1224-width)/2 ,(792-height)/2); g2.dispose(); try { if (doc != null && (Boolean) documentClass.getMethod("isOpen").invoke(doc)) { documentClass.getMethod("close").invoke(doc); //doc.close(); } if (docWriter != null) { pdfWriterClass.getMethod("close").invoke(docWriter); //docWriter.close(); } } catch (Exception ex) { ex.printStackTrace();} return baosPDF; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public BufferedImage generateScaledImage(int maxImageWidth, int maxImageHeight, Image logoImage, int pad) { Rectangle2D.Double imageRectangle = panelController.getScrollController().getRendererRectangle(); Rectangle newImageDimension = RendererUtils.getAspectScaledRectangle(imageRectangle, maxImageWidth, maxImageHeight); return generateImage(newImageDimension.width, newImageDimension.height, logoImage, pad); } public BufferedImage generateImage(int imageWidth, int imageHeight, Image logoImage, int pad) { try { panelController.getInteractionLock().readLock().lock(); if ( panelController.getScrollController().getVisibleRectangle().width == 0 || panelController.getScrollController().getVisibleRectangle().height == 0 ) { return null; } BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); int actualImageWidth = imageWidth-2*pad; int actualImageHeight = imageHeight-2*pad; Rectangle2D.Double imageRectangle = panelController.getScrollController().getRendererRectangle(); Rectangle newImageDimension = RendererUtils.getAspectScaledRectangle(imageRectangle, actualImageWidth, actualImageHeight); double xZoomFactor = (newImageDimension.width / imageRectangle.width); double yZoomFactor = (newImageDimension.height / imageRectangle.height); int xOffset = 0, yOffset = 0; if ( newImageDimension.width < actualImageWidth ) { xOffset = (actualImageWidth - newImageDimension.width) / 2; } if ( newImageDimension.height < actualImageHeight ) { yOffset = (actualImageHeight - newImageDimension.height) / 2; } AffineTransform transform = new AffineTransform(); transform.translate(pad+xOffset, pad+yOffset); transform.scale(xZoomFactor*panelController.getScrollController().getScalingZoomFactor(), yZoomFactor*panelController.getScrollController().getScalingZoomFactor()); transform.translate(-imageRectangle.getMinX()/panelController.getScrollController().getScalingZoomFactor(), -imageRectangle.getMinY()/panelController.getScrollController().getScalingZoomFactor()); paintImage(image, logoImage, transform); return image; } finally { panelController.getInteractionLock().readLock().unlock(); } } public ByteArrayOutputStream generatePdf() { Rectangle2D.Double imageRectangle1 = getPaddedExportImageSize(); Rectangle imageRectangle2 = RendererUtils.getAspectScaledRectangle(imageRectangle1, 1224, 792); Image logoImage = smallLogoImage; int imageWidth = imageRectangle2.width; int imageHeight = imageRectangle2.height; int pad = SAVE_IMAGE_PAD; try { panelController.getInteractionLock().readLock().lock(); if ( panelController.getScrollController().getVisibleRectangle().width == 0 || panelController.getScrollController().getVisibleRectangle().height == 0 ) { return null; } //BufferedImage image = new BufferedImage(imageWidth, imageHeight, // BufferedImage.TYPE_INT_RGB); int actualImageWidth = imageWidth-2*pad; int actualImageHeight = imageHeight-2*pad; Rectangle2D.Double imageRectangle = panelController.getScrollController().getRendererRectangle(); Rectangle newImageDimension = RendererUtils.getAspectScaledRectangle(imageRectangle, actualImageWidth, actualImageHeight); double xZoomFactor = (newImageDimension.width / imageRectangle.width); double yZoomFactor = (newImageDimension.height / imageRectangle.height); int xOffset = 0, yOffset = 0; if ( newImageDimension.width < actualImageWidth ) { xOffset = (actualImageWidth - newImageDimension.width) / 2; } if ( newImageDimension.height < actualImageHeight ) { yOffset = (actualImageHeight - newImageDimension.height) / 2; } AffineTransform transform = new AffineTransform(); transform.translate(pad+xOffset, pad+yOffset); transform.scale(xZoomFactor*panelController.getScrollController().getScalingZoomFactor(), yZoomFactor*panelController.getScrollController().getScalingZoomFactor()); transform.translate(-imageRectangle.getMinX()/panelController.getScrollController().getScalingZoomFactor(), -imageRectangle.getMinY()/panelController.getScrollController().getScalingZoomFactor()); return paintImagePdf(logoImage, imageWidth, imageHeight, transform); } finally { panelController.getInteractionLock().readLock().unlock(); } } public Rectangle2D.Double getRendererBounds(int imageWidth, int imageHeight, Point2D.Double centerLocation) { double actualWidth = imageWidth / panelController.getBoardRenderer().getZoom(); double actualHeight = imageHeight / panelController.getBoardRenderer().getZoom(); return new Rectangle2D.Double(centerLocation.x - actualWidth/2, centerLocation.y - actualHeight/2, actualWidth, actualHeight); } public BufferedImage generateCenteredImage(int imageWidth, int imageHeight, Point2D.Double centerLocation, Image logoImage) { try { panelController.getInteractionLock().readLock().lock(); if ( panelController.getScrollController().getVisibleRectangle().width == 0 || panelController.getScrollController().getVisibleRectangle().height == 0 ) { return null; } BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Rectangle2D.Double bounds = getRendererBounds(imageWidth, imageHeight, centerLocation); AffineTransform transform = new AffineTransform(); transform.scale(panelController.getScrollController().getScalingZoomFactor(), panelController.getScrollController().getScalingZoomFactor()); transform.translate(-bounds.getMinX(),-bounds.getMinY()); paintImage(image, logoImage, transform); return image; } finally { panelController.getInteractionLock().readLock().unlock(); } } public BufferedImage generateCenteredImage(Rectangle2D.Double bounds) { Image logoImage = getLogoImage(bounds.height, bounds.width); return generateCenteredImage(bounds, logoImage); } public BufferedImage generateCenteredImage(Rectangle2D.Double bounds, Image logoImage) { try { panelController.getInteractionLock().readLock().lock(); if ( panelController.getScrollController().getVisibleRectangle().width == 0 || panelController.getScrollController().getVisibleRectangle().height == 0 ) { return null; } double scalingZoomFactor = panelController.getScrollController().getScalingZoomFactor(); BufferedImage image = new BufferedImage( (int)Math.ceil(bounds.width * scalingZoomFactor), (int)Math.ceil(bounds.height * scalingZoomFactor), BufferedImage.TYPE_INT_RGB); AffineTransform transform = new AffineTransform(); transform.scale(scalingZoomFactor, scalingZoomFactor); transform.translate(-bounds.getMinX(),-bounds.getMinY()); paintImage(image, logoImage, transform); return image; } finally { panelController.getInteractionLock().readLock().unlock(); } } public Rectangle2D.Double getPaddedExportImageSize() { return panelController.getScrollController().getRendererRectangle(SAVE_IMAGE_PAD); } public BufferedImage getExportImage() { Rectangle2D.Double imageRectangle = getPaddedExportImageSize(); Image logoImage = getLogoImage(imageRectangle.width, imageRectangle.height); BufferedImage image = generateImage((int)imageRectangle.width, (int)imageRectangle.height, logoImage, SAVE_IMAGE_PAD); return image; } public BufferedImage getScaledExportImage(int imageWidth, int imageHeight) { Image logoImage = getLogoImage(imageWidth, imageHeight); BufferedImage scaledImage = generateImage(imageWidth,imageHeight, logoImage, SAVE_IMAGE_PAD); return scaledImage; } public BufferedImage getCroppedExportImage(int imageWidth, int imageHeight) { Image logoImage = getLogoImage(imageWidth, imageHeight); BufferedImage image = generateCenteredImage(imageWidth, imageHeight, panelController.getScrollController().getCenterDrawPosition(), logoImage); return image; } public void saveImage(File saveFile) throws Exception { BufferedImage image = getExportImage(); if( image != null ) { try { // save the drawing to a PNG file ImageIO.write(image, "png", saveFile); System.gc(); } catch (Exception ex) { ex.printStackTrace(); } } } public void saveCroppedImage(File saveFile, int imageWidth, int imageHeight) throws Exception { BufferedImage image = getCroppedExportImage(imageWidth, imageHeight); if( image != null ) { try { // save the drawing to a PNG file ImageIO.write(image, "png", saveFile); } catch (Exception ex) { ex.printStackTrace(); } } } public void saveScaledImage(File saveFile, int imageWidth, int imageHeight) throws Exception { BufferedImage scaledImage = getScaledExportImage(imageWidth, imageHeight); if( scaledImage != null ) { try { // save the drawing to a PNG file ImageIO.write(scaledImage, "png", saveFile); System.gc(); } catch (Exception ex) { ex.printStackTrace(); } } } protected synchronized void createImage() { drawImage = new BufferedImage(panelController.getScrollController().getVisibleRectangle().width, panelController.getScrollController().getVisibleRectangle().height, BufferedImage.TYPE_INT_ARGB); //Does this need to be here? paintBackground(drawImage); } protected void paintBackground(Image image) { paintBackground((Graphics2D)image.getGraphics(),image.getWidth(null),image.getHeight(null)); } protected void paintBackground(Graphics2D g2, int width, int height) { g2.setColor(BACK_COLOR); g2.fillRect(0,0,width,height); } public void addPaintImageListener(PaintImageListener paintImageListener) { paintImageListeners.add(paintImageListener); } public void removePaintImageListener(PaintImageListener paintImageListener) { paintImageListeners.remove(paintImageListener); } private void firePaintImage() { for ( PaintImageListener paintImageListener : paintImageListeners ) { paintImageListener.paintImage(); } } public void paintMessage(Image image) { String message = getMessage(); if (message==null) return; Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setColor(new Color(224,224,224)); RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHints(rh); g2.setFont(new Font("Courier",Font.PLAIN,15)); int left = Math.max(15, image.getWidth(null)/2-360); g2.drawString(message, left,image.getHeight(null)-10); } public String getMessage() { if (this.panelController.getDisplayControlPanel().getStatisticsBarCheckbox().isSelected()) { return this.panelController.getGameModel().getStats().getStatsSummary(); } return null; } public void setMessage(String message) { this.message = message; } }
import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.awt.image.*; /*<applet code="Puzzle.java" width=900 height=600> <param name="img" value="Kangaroo.jpg"> <param name="mould" value="mould8x5.jpg"> </applet> */ public class Puzzle1 extends Applet implements MouseListener, Runnable, MouseMotionListener// ActionListener {int ij, nbrows, nbcolumns, piecewidth, pieceheight,distancex, distancey, totalnbpieces; int correctionx, correctiony, screen, swidth, sheight, picturewidth, pictureheight, di; int piecedragged=-1, groupdragged=-1, nbofgrps=0; int piececenter[]; int PosX[]; int PosY[]; int pictpix[]; int mouldpix[]; int mcol[]; Image board, mypicture=null, mould=null; Graphics bg; Image piece[]; Group[] grp= new Group[80]; Thread walk; //only for beginning boolean isbusy=false; boolean isloading=true; boolean dragpiece=false, draggroup=false; Font f=new Font("Dialog", Font.BOLD,18); Color lightblue = new Color(128,255,255); public void init() {sheight=Integer.parseInt(getParameter("height")); swidth=Integer.parseInt(getParameter("width")); nbcolumns=Integer.parseInt(getParameter("nbcolumns")); nbrows=Integer.parseInt(getParameter("nbrows")); di=Integer.parseInt(getParameter("piecedistance")); totalnbpieces=nbrows*nbcolumns; piececenter=new int[120]; PosX=new int[120]; PosY=new int[120]; piecewidth=(int)(di*1.6); pieceheight=(int)(di*1.6); board=createImage(swidth,sheight); bg=board.getGraphics(); addMouseListener(this); addMouseMotionListener(this); picturewidth=nbcolumns*di; pictureheight=nbrows*di; piece= new Image[totalnbpieces]; pictpix=new int[picturewidth*pictureheight]; mouldpix=new int[picturewidth*pictureheight]; mcol=new int[picturewidth*pictureheight]; MediaTracker tracker = new MediaTracker(this); try{if(getParameter("mode").equals("zip")){mypicture=getImage(getClass().getResource(getParameter("img")));} else {mypicture=getImage(getDocumentBase(), getParameter("img"));} tracker.addImage(mypicture, 0); mould=getImage(getClass().getResource(getParameter("mould"))); tracker.addImage(mould, 1); tracker.waitForAll(); }catch(InterruptedException e){showStatus("No picture found");} pictpix=getPixels(mypicture, picturewidth, pictureheight); mouldpix=getPixels(mould, picturewidth, pictureheight); for(int i=0; i<mouldpix.length; i++) {int p= mouldpix[i]; int green=0xff&(p>>8);int blue=0xff&(p); if((green>220)&&(blue>220)){mcol[i]=1;} else {mcol[i]=0;} } Random r= new Random(); for(int i=0; i<totalnbpieces; i++) {PosX[i]=r.nextInt()%(swidth-di); if(PosX[i]<0) {PosX[i]=-PosX[i];} PosY[i]=r.nextInt()%(sheight-di); if(PosY[i]<0) {PosY[i]=-PosY[i];} } } public void start() {if(walk==null) {walk=new Thread(this);} isloading=true; walk.start(); } public void run() {while(isloading==true) { for(screen=1; screen<3;screen++) {repaint(); try{walk.sleep(200);}catch(InterruptedException ie){showStatus("Interrupted");} } for(int ii=0;ii<totalnbpieces; ii++) { piececenter[ii]=defineCenter(ii); piece[ii]=definePiece(piececenter[ii]); screen=3; ij=ii; repaint(); //try{ Thread.sleep(200);}catch(InterruptedException ie){showStatus("Interrupted");} } isloading=false; repaint(); }} public int[] getPixels(Image img, int width, int height) {int pixels[]= new int[width*height]; PixelGrabber pg= new PixelGrabber(img,0,0, width, height, pixels, 0, width); try{pg.grabPixels();} catch(InterruptedException iie){showStatus("Dont get Pixels");} return pixels; } public int defineCenter (int k) {int center =(((int )(k/nbcolumns))*picturewidth*di)+(picturewidth*di/2)+(((int)(k%nbcolumns))*di)+di/2; return center; } public Image definePiece(int center) {isbusy=true; int lowerlimitx=center%picturewidth-(piecewidth/2); int higherlimitx=center%picturewidth+(piecewidth/2); int lowerlimity=center/picturewidth-(piecewidth/2); int higherlimity=center/picturewidth+(piecewidth/2); int area=piecewidth*pieceheight; int piecepix[] = new int [area]; Image img; int nborig=1, oldnborig=0, nbexpanded=1; int contorig[]=new int [area]; int contexp[]=new int[area]; for(int j=0; j<area; j++) {contorig[j]=-1; contexp[j]=-1;} contexp[0]=center; int cycle=0; do{ for(int i=0; i<nbexpanded; i++) {contorig[i]=contexp[i];} nborig=nbexpanded; if(nborig>(int)(di*di*2.2)) break; for (int i=oldnborig; i<nborig; i++) { // expanding to west if((contorig[i]%picturewidth!=0)&&(itcontains((contorig[i]-1), contexp,nbexpanded)==false)&&((contorig[i])%picturewidth>lowerlimitx)) {if(mcol[contorig[i]-1]==1) {contexp[nbexpanded]=(contorig[i]-1); nbexpanded++;} } //east if(((contorig[i]+1)%picturewidth!=0)&&(itcontains((contorig[i]+1), contexp,nbexpanded)==false)&&((contorig[i])%picturewidth<higherlimitx)) {if(mcol[contorig[i]+1]==1) {contexp[nbexpanded]=(contorig[i]+1); nbexpanded++;} } //north if((contorig[i]>(picturewidth-1))&&(itcontains((contorig[i]-picturewidth), contexp,nbexpanded)==false)&&((contorig[i])/picturewidth>lowerlimity)) {if(mcol[contorig[i]-picturewidth]==1) {contexp[nbexpanded]=(contorig[i]-picturewidth); nbexpanded++;} } //south if((contorig[i]<(picturewidth*(pictureheight-1)))&&(itcontains((contorig[i]+picturewidth), contexp,nbexpanded)==false)&&((contorig[i])/picturewidth<higherlimity)) {if(mcol[contorig[i]+picturewidth]==1) {contexp[nbexpanded]=(contorig[i]+picturewidth); nbexpanded++;} } cycle++; oldnborig=nborig; //showStatus("nb= "+nbexpanded+ " for center at "+center+ " in "+cycle+ " cycles"); } }while((nbexpanded<area)&&(nborig<nbexpanded)&&(cycle<(di*di*2))); int kp=0; for (int kk=center-picturewidth*(piecewidth/2) - (piecewidth/2); kk<center+picturewidth*(piecewidth/2-1)+(piecewidth/2-1);kk=kk+picturewidth) {for(int kl=kk; kl<kk+(piecewidth); kl++,kp++) {if(itcontains(kl,contexp,nbexpanded)==true) {piecepix[kp]=pictpix[kl];} else {piecepix[kp]=0x00000000;} }} img=createImage(new MemoryImageSource(piecewidth, pieceheight,piecepix,0,piecewidth)); isbusy=false; return img; } public boolean itcontains(int k, int[]contexp, int nbexpanded) { for (int ik=0; ik<nbexpanded; ik++) {if(k==contexp[ik]){return true;} } return false; } public void mousePressed(MouseEvent me) {if(isloading==false) //&&(isreleased==false)) { int px=me.getX();int py=me.getY(); for (int jj=0; jj<totalnbpieces; jj++) {if((px>PosX[jj])&&(px<(PosX[jj]+piecewidth))&&(py>PosY[jj])&&(py<(PosY[jj]+piecewidth)) ) { int pixxy=py*swidth+px; // showStatus("got piece "+jj+", with "+PosY[jj]+" < "+py+" < "+(PosY[jj]+piecewidth) ); boolean opacity=checkForOpacity(jj, pixxy, piece[jj]); if (opacity==true) { for(int g=0; g<=nbofgrps; g++) {if(g==nbofgrps) {dragpiece=true; piecedragged=jj;//groupdragged=-1; //jj is local variable distancex=px-(PosX[jj]);distancey=py-(PosY[jj]); } else if ((grp[g]).doescontain(jj)==true) {groupdragged=g; draggroup=true; // int members[]=new int[grp[g].getsize()]; int leader=(grp[g]).leaderr; distancex=px-(PosX[leader]); distancey=py-(PosY[leader]); // showStatus(" pressed group "+g+ "at distance"+distancex); break; } else{}; } // try{ Thread.sleep(200);}catch(InterruptedException ie){showStatus("Interrupted");} } else{};// dragpiece=false;groupdragged=-1;} //opacity=false } else{}; }} } public void mouseDragged(MouseEvent me) {int dX=me.getX(); int dY=me.getY(); if(dragpiece==true) {PosX[piecedragged]=dX -distancex; PosY[piecedragged]=dY -distancey; repaint(); } else if (groupdragged>=0) {showStatus("in group dragging"); int N=(grp[groupdragged]).sizeofgroup; int Cont[]= new int[N]; int offX[]= new int[N]; int offY[]= new int[N]; Cont=(grp[groupdragged]).getContent(); int leader= (grp[groupdragged]).leaderr; showStatus("groupdragged= " + groupdragged); for(int pp=0; pp<N; pp++) {PosX[Cont[pp]]=dX -distancex+(((Cont[pp])%nbcolumns)-(leader%nbcolumns))*di; PosY[Cont[pp]]=dY -distancey +((Cont[pp])/nbcolumns-leader/nbcolumns)*di; } repaint(); } else{} } public void mouseReleased(MouseEvent me) { int rX=me.getX(); int rY=me.getY(); int itsgrp=-1; if(dragpiece==true) { PosX[piecedragged]=rX -distancex; PosY[piecedragged]=rY -distancey; int targetL = piecedragged-1; int targetU = piecedragged-nbcolumns; int targetR = piecedragged+1; int targetD = piecedragged+nbcolumns; //approach from below if((piecedragged>=nbcolumns)&&(Math.abs(PosY[piecedragged]-PosY[targetU]-di)<3)&&(Math.abs(PosX[piecedragged]-PosX[targetU])<3)) {itsgrp=findGroup(targetU,piecedragged); // showStatus("groupU "+targetU+"," +piecedragged); } //approach from the right else if((piecedragged%nbcolumns!=0)&&(Math.abs(PosX[piecedragged]-PosX[targetL]-di)<3)&&(Math.abs(PosY[piecedragged]-PosY[targetL])<3)) {itsgrp= findGroup(targetL,piecedragged); // showStatus("groupL "+targetL+"," +piecedragged); } else if(((piecedragged%nbcolumns)<(nbcolumns-1))&&(Math.abs(PosX[piecedragged]-PosX[targetR]+di)<3)&&(Math.abs(PosY[piecedragged]-PosY[targetR])<3)) {itsgrp=findGroup(targetR,piecedragged); // showStatus("groupR "+targetR+"," +piecedragged); } else if((piecedragged<(totalnbpieces- nbcolumns))&&(Math.abs(PosY[piecedragged]-PosY[targetD]+di)<3)&&(Math.abs(PosX[piecedragged]-PosX[targetD])<3)) {itsgrp=findGroup(targetD,piecedragged); // showStatus("groupD "+targetD+"," +piecedragged); } if(itsgrp>=0) {int leader=(grp[itsgrp]).leaderr; // ask for repainting the whole new group int N=(grp[itsgrp]).sizeofgroup; int Cont[]= new int[N]; Cont=(grp[itsgrp]).getContent(); for(int pp=0; pp<N; pp++) {PosX[Cont[pp]]=rX -distancex+(((Cont[pp])%nbcolumns)-(leader%nbcolumns))*di; PosY[Cont[pp]]=rY -distancey +((Cont[pp])/nbcolumns-leader/nbcolumns)*di; } repaint(); } dragpiece=false; piecedragged=-1; } else if (groupdragged>=0) {int N=(grp[groupdragged]).getsize(); int Cont[]=new int[N]; Cont=(grp[groupdragged]).getContent(); showStatus("Just released group "+groupdragged); for(int pp=0; pp<N; pp++) { int targetU = pp-nbcolumns; int targetL = pp-1; int targetR = pp+1; int targetD = pp+nbcolumns; if((pp>=nbcolumns)&&((grp[groupdragged]).doescontain(targetU)==false)&&(Math.abs(PosY[pp]-PosY[targetU]-di)<3)&&(Math.abs(PosX[pp]-PosX[targetU])<3)) {itsgrp=findGroup(targetU,pp); break;} //approach from the right else if((pp%nbcolumns!=0)&&((grp[groupdragged]).doescontain(pp)==false)&&(Math.abs(PosX[pp]-PosX[targetL]-di)<3)&&(Math.abs(PosY[pp]-PosY[targetL])<3)) {itsgrp= findGroup(targetL,pp); break;} //approach from left else if(((pp%nbcolumns)<(nbcolumns-1))&&((grp[groupdragged]).doescontain(pp)==false)&&(Math.abs(PosX[pp]-PosX[targetR]+di)<3)&&(Math.abs(PosY[pp]-PosY[targetR])<3)) {itsgrp=findGroup(targetR,pp);break;} else if((pp<(totalnbpieces- nbcolumns))&&((grp[groupdragged]).doescontain(pp)==false)&&(Math.abs(PosY[pp]-PosY[targetD]+di)<3)&&(Math.abs(PosX[pp]-PosX[targetD])<3)) {itsgrp=findGroup(targetD,pp); break; } } // next pp // ask for repainting the whole new group int NN=(grp[itsgrp]).sizeofgroup; int NCont[]= new int[NN]; NCont=(grp[itsgrp]).getContent(); int leader=(grp[itsgrp]).leaderr; for(int pp=0; pp<NN; pp++) {PosX[NCont[pp]]=rX -distancex+(((NCont[pp])%nbcolumns)-(leader%nbcolumns))*di; PosY[NCont[pp]]=rY -distancey +(NCont[pp]/nbcolumns-leader/nbcolumns)*di; } repaint(); draggroup=false; groupdragged=-1; } //end of draggroup=true //draggroup=false; groupdragged=-1; } } public int findGroup (int target, int piecedragged) { int g=0; if(dragpiece==true) { int oldnbofgrps=nbofgrps; if(oldnbofgrps==0){grp[0]=new Group(target, piecedragged); distancex=correctionx+distancex; distancey=correctiony+distancey; nbofgrps++; return g; } //g=0; else {for(g=0; g<oldnbofgrps; g++) { if((grp[g]).doescontain(target)==true) {(grp[g]).setin(piecedragged); distancex=correctionx+distancex; distancey=correctiony+distancey; return g;} } g=oldnbofgrps; grp[oldnbofgrps]= new Group(target, piecedragged); nbofgrps++; distancex=correctionx+distancex; distancey=correctiony+distancey; showStatus("new groupnb "+g+"with"+target+ " , "+piecedragged); } } else if(groupdragged>=0) //put the existing groupmb in groupdragged { for( g=0; g<nbofgrps; g++) {if((grp[g]).doescontain(target)==true) {int N=(grp[g]).getsize(); int Cont[]=new int[N]; Cont=(grp[g]).getContent(); for(int dr=0; dr<N; dr++) {(grp[groupdragged]).setin(Cont[dr]); } (grp[g]).setToNull(); return g; } else{}; } //end of for if (g==nbofgrps) (grp[groupdragged]).setin(target); } showStatus("found group = "+g); return g;} public boolean checkForOpacity(int jj, int pixxy, Image p) {boolean opaque=true; int pxinpiece=pixxy%swidth-(PosX[jj]); int pyinpiece=pixxy/swidth-(PosY[jj]); int pixels[]= new int[piecewidth*pieceheight]; PixelGrabber pg= new PixelGrabber(piece[jj],0,0, piecewidth, pieceheight, pixels, 0, piecewidth); try{pg.grabPixels();} catch(InterruptedException iie){showStatus("Dont get Pixels");} if( pixels[(pxinpiece+piecewidth*pyinpiece)]!=0x00000000) {opaque=true;} else {opaque=false;} return opaque; } public void mouseClicked(MouseEvent me){} public void mouseEntered(MouseEvent me) {} public void mouseExited(MouseEvent me) {} public void mouseMoved(MouseEvent me) {} public void update(Graphics g) {if(isloading==true) { if(screen==1) {if(mypicture==null){bg.drawString("Sorry, no picture to cut", 10, 50);} else{bg.drawImage(mypicture,(swidth-picturewidth)/2, (sheight-pictureheight)/2, this);} } else if (screen==2) {if(mould==null){bg.drawString("Sorry, no mould", 10, 100);} else{bg.drawImage(mould,(swidth-picturewidth)/2, (sheight-pictureheight)/2, this);} try{Thread.sleep(30);}catch(InterruptedException ie){}; } else if(screen==3) {bg.drawImage(piece[ij],piececenter[ij]%picturewidth, (piececenter[ij]/picturewidth), this); bg.setColor(Color.black);bg.setFont(f); bg.drawString("cutting the puzzle, please wait", 50,250); showStatus("Program written by annemarie.govindraj@gmail.com"); } } else if (isloading==false) {bg.setColor(lightblue); bg.fillRect(0,0,swidth,sheight); for(int i=0; i<totalnbpieces; i++) {bg.drawImage(piece[i],PosX[i], PosY[i],this);} } paint(g); } public void paint (Graphics g) {g.drawImage(board,0,0,this);} class Group {int content[]= new int[totalnbpieces]; int leaderr; // leftmost piece because % int sizeofgroup; Group (int target, int piecedragged) {sizeofgroup=1; content[0]=target; leaderr=target; setin(piecedragged); } public void setin (int p) {content[sizeofgroup]=p; int oldleaderr=leaderr; correctionx=0;correctiony=0; if((p%nbcolumns)<(leaderr%nbcolumns)) {leaderr=p;} else{ correctionx=((p%nbcolumns)-(leaderr%nbcolumns))*di;correctiony=(p/nbcolumns-leaderr/nbcolumns)*di;} sizeofgroup++; } public int getsize(){return sizeofgroup;} public int[] getContent(){return content;} public void setToNull() {for (int ik=0;ik<sizeofgroup;ik++) {content[ik]=-1;} sizeofgroup=0; } public boolean doescontain (int k) {for (int ik=0;ik<sizeofgroup;ik++) { if(k==content[ik]) {return true;} } return false; }}}
/* * $Id$ * * Copyright (c) 2018, Simsilica, LLC * 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 com.simsilica.bullet.debug; import java.util.*; import org.slf4j.*; import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.bullet.util.DebugShapeFactory; import com.jme3.material.Material; import com.jme3.material.MatParamOverride; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.*; import com.jme3.scene.shape.Box; import com.jme3.scene.debug.Arrow; import com.jme3.shader.VarType; import com.simsilica.es.*; import com.simsilica.lemur.GuiGlobals; import com.simsilica.bullet.Contact; /** * * * @author Paul Speed */ public class ContactDebugState extends BaseAppState { static Logger log = LoggerFactory.getLogger(ContactDebugState.class); private EntityData ed; private Node debugRoot; private ContactDebugContainer contacts; private List<ContactView> contactViews = new ArrayList<>(); private Material contactMaterial; public ContactDebugState( EntityData ed ) { this.ed = ed; setEnabled(false); } public void toggleEnabled() { setEnabled(!isEnabled()); } @Override protected void initialize( Application app ) { this.contactMaterial = GuiGlobals.getInstance().createMaterial(ColorRGBA.Green, false).getMaterial(); contactMaterial.getAdditionalRenderState().setWireframe(true); contactMaterial.getAdditionalRenderState().setDepthTest(false); this.debugRoot = new Node("contactDebugRoot"); this.contacts = new ContactDebugContainer(ed); } @Override protected void cleanup( Application app ) { } @Override protected void onEnable() { ((SimpleApplication)getApplication()).getRootNode().attachChild(debugRoot); contacts.start(); } @Override public void update( float tpf ) { contacts.update(); updateContactViews(); } @Override protected void onDisable() { contacts.stop(); debugRoot.removeFromParent(); } protected void updateContactViews() { // Try to reuse items when we can int i = 0; for( Contact c : contacts.getArray() ) { if( i >= contactViews.size() ) { ContactView view = new ContactView(c); debugRoot.attachChild(view); contactViews.add(view); } else { ContactView existing = contactViews.get(i); existing.update(c); debugRoot.attachChild(existing); } i++; } // "Hide" any of the existing ones we aren't using anymore for( ; i < contactViews.size(); i++ ) { ContactView existing = contactViews.get(i); existing.removeFromParent(); } } protected float getContactScale( Contact c ) { float energy = c.getEnergy(); return 0.5f + energy/10f; } protected ColorRGBA getContactColor( Contact c ) { float energy = c.getEnergy(); if( energy < 1 ) { return ColorRGBA.Green; } if( energy < 10 ) { return ColorRGBA.Red; } if( energy < 60 ) { return ColorRGBA.Yellow; } return ColorRGBA.White; } private class ContactView extends Node { private Contact contact; private Geometry arrowGeom; private Arrow arrow; private MatParamOverride arrowColor = new MatParamOverride(VarType.Vector4, "Color", ColorRGBA.Red); public ContactView( Contact contact ) { super("Contact:" + contact.getEntity1() + " -> " + contact.getEntity2()); setQueueBucket(Bucket.Translucent); arrowGeom = new Geometry(getName() + ":arrow"); attachChild(arrowGeom); arrowGeom.setMaterial(contactMaterial); arrowGeom.addMatParamOverride(arrowColor); this.contact = contact; this.arrow = new Arrow(contact.getNormal().mult(0.5f * getContactScale(contact))); arrowGeom.setMesh(arrow); arrowGeom.updateModelBound(); arrowColor.setValue(getContactColor(contact)); setLocalTranslation(contact.getLocation()); } public void update( Contact contact ) { this.contact = contact; arrow.setArrowExtent(contact.getNormal().mult(0.5f * getContactScale(contact))); arrowGeom.updateModelBound(); arrowColor.setValue(getContactColor(contact)); setLocalTranslation(contact.getLocation()); } } private class ContactDebugContainer extends EntityContainer<Contact> { public ContactDebugContainer( EntityData ed ) { super(ed, Contact.class); } @Override public Contact[] getArray() { return super.getArray(); } @Override protected Contact addObject( Entity e ) { return e.get(Contact.class); } @Override protected void updateObject( Contact contact, Entity e ) { } @Override protected void removeObject( Contact object, Entity e ) { } } }
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * 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.jkiss.dbeaver.ui.data.managers; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.Separator; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPMessageType; import org.jkiss.dbeaver.model.DBValueFormatting; import org.jkiss.dbeaver.model.data.DBDContent; import org.jkiss.dbeaver.model.data.DBDContentCached; import org.jkiss.dbeaver.model.data.DBDContentStorage; import org.jkiss.dbeaver.model.data.DBDDisplayFormat; import org.jkiss.dbeaver.model.data.storage.ExternalContentStorage; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.preferences.DBPPropertyManager; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.controls.resultset.ResultSetPreferences; import org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages; import org.jkiss.dbeaver.ui.data.IValueController; import org.jkiss.dbeaver.ui.data.IValueEditor; import org.jkiss.dbeaver.ui.data.dialogs.TextViewDialog; import org.jkiss.dbeaver.ui.data.editors.ContentInlineEditor; import org.jkiss.dbeaver.ui.data.editors.ContentPanelEditor; import org.jkiss.dbeaver.ui.data.editors.StringInlineEditor; import org.jkiss.dbeaver.ui.dialogs.DialogUtils; import org.jkiss.dbeaver.ui.editors.content.ContentEditor; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import java.awt.*; import java.io.*; import java.lang.reflect.InvocationTargetException; /** * JDBC Content value handler. * Handle LOBs, LONGs and BINARY types. * * @author Serge Rider */ public class ContentValueManager extends BaseValueManager { private static final Log log = Log.getLog(ContentValueManager.class); public static final String PROP_CATEGORY_CONTENT = "CONTENT"; public static void contributeContentActions(@NotNull IContributionManager manager, @NotNull final IValueController controller, final IValueEditor activeEditor) throws DBCException { if (controller.getValue() instanceof DBDContent) { if (!((DBDContent) controller.getValue()).isNull()) { manager.add(new Action(ResultSetMessages.model_jdbc_save_to_file_, DBeaverIcons.getImageDescriptor(UIIcon.SAVE_AS)) { @Override public void run() { saveToFile(controller); } }); } // Logo can be changed manager.add(new Action("Open in external editor", DBeaverIcons.getImageDescriptor(UIIcon.DOTS_BUTTON)) { @Override public void run() { try { final Object value = controller.getValue(); if (value == null) { DBWorkbench.getPlatformUI().showError("Data is empty", "Can not save null data value"); } if (value instanceof DBDContent) { getDBDContent(value); } else { String str = controller.getValueHandler() .getValueDisplayString(controller.getValueType(), controller.getValue(), DBDDisplayFormat.EDIT); String charset = DBValueFormatting.getDefaultBinaryFileEncoding(controller.getExecutionContext().getDataSource()); byte[] bytes = str.getBytes(charset); openOctetStream(bytes); } } catch (IOException e) { DBWorkbench.getPlatformUI().showError("Open content", "Error while trying to open the value", e); } catch (Exception e) { DBWorkbench.getPlatformUI().showError("Error", "Unexpected error while trying to open the selected value", e); } } }); manager.add(new Action(ResultSetMessages.model_jdbc_load_from_file_, DBeaverIcons.getImageDescriptor(UIIcon.LOAD)) { @Override public void run() { if (loadFromFile(controller)) { if (activeEditor != null) { try { activeEditor.primeEditorValue(controller.getValue()); } catch (DBException e) { DBWorkbench.getPlatformUI().showError("Load from file", "Error loading contents from file", e); } } } } }); manager.add(new Separator()); } } private static void getDBDContent(Object value) throws IOException, DBCException { DBDContent content = (DBDContent) value; try { UIUtils.runInProgressService(monitor -> { String charset = null; DBDContentStorage storage; try { storage = content.getContents(monitor); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); if (storage != null) { try (InputStream inputStream = storage.getContentStream()) { ContentUtils.copyStreams(inputStream, -1, buffer, monitor); } catch (IOException e) { DBWorkbench.getPlatformUI().showError("IOException", "File exception", e); } charset = storage.getCharset(); } else { charset = DBValueFormatting.getDefaultBinaryFileEncoding(content.getDataSource()); } byte[] byteData = buffer.toByteArray(); openOctetStream(byteData); } catch (DBCException e1) { DBWorkbench.getPlatformUI().showError("DBCException", "Error reading contents", e1); } catch (IOException e) { DBWorkbench.getPlatformUI().showError("IOException", "File exception while opening", e); } }); } catch (InvocationTargetException | InterruptedException e) { DBWorkbench.getPlatformUI().showError("Reading from content", "Error loading contents from file", e); } } private static void openOctetStream(byte[] data) throws IOException { File tmpFile = File.createTempFile("dbtmp", ".octet-stream"); FileOutputStream fos = new FileOutputStream(tmpFile); if (data == null) { DBWorkbench.getPlatformUI().showError("Open Content", "Raw value was null"); fos.close(); } if (data.length == 0) { log.info("file has no content"); fos.close(); tmpFile.delete(); } else { fos.write(data); fos.close(); // use OS to open the file Desktop.getDesktop().open(tmpFile); // delete the file when the user closes the DBeaver application tmpFile.deleteOnExit(); } } public static IValueEditor openContentEditor(@NotNull IValueController controller) { Object value = controller.getValue(); IValueController.EditType binaryEditType = IValueController.EditType.valueOf( controller.getExecutionContext().getDataSource().getContainer().getPreferenceStore().getString(ResultSetPreferences.RESULT_SET_BINARY_EDITOR_TYPE)); if (controller.getValueType().getDataKind() == DBPDataKind.STRING) { // String return new TextViewDialog(controller); } else if (binaryEditType != IValueController.EditType.EDITOR && value instanceof DBDContentCached) { // Use string editor for cached content return new TextViewDialog(controller); } else if (value instanceof DBDContent) { return ContentEditor.openEditor(controller); } else { controller.showMessage(ResultSetMessages.model_jdbc_unsupported_content_value_type_, DBPMessageType.ERROR); return null; } } public static boolean loadFromFile(final IValueController controller) { if (!(controller.getValue() instanceof DBDContent)) { log.error(ResultSetMessages.model_jdbc_bad_content_value_ + controller.getValue()); return false; } Shell shell = UIUtils.getShell(controller.getValueSite()); final File openFile = DialogUtils.openFile(shell); if (openFile == null) { return false; } final DBDContent value = (DBDContent)controller.getValue(); UIUtils.runInUI(PlatformUI.getWorkbench().getActiveWorkbenchWindow(), monitor -> { try { DBDContentStorage storage; if (ContentUtils.isTextContent(value)) { storage = new ExternalContentStorage(DBWorkbench.getPlatform(), openFile, GeneralUtils.UTF8_ENCODING); } else { storage = new ExternalContentStorage(DBWorkbench.getPlatform(), openFile); } value.updateContents(monitor, storage); controller.updateValue(value, true); } catch (Exception e) { throw new InvocationTargetException(e); } }); return true; } public static void saveToFile(IValueController controller) { if (!(controller.getValue() instanceof DBDContent)) { log.error(ResultSetMessages.model_jdbc_bad_content_value_ + controller.getValue()); return; } Shell shell = UIUtils.getShell(controller.getValueSite()); final File saveFile = DialogUtils.selectFileForSave(shell, controller.getValueName()); if (saveFile == null) { return; } final DBDContent value = (DBDContent)controller.getValue(); try { UIUtils.runInProgressService(monitor -> { try { DBDContentStorage storage = value.getContents(monitor); if (ContentUtils.isTextContent(value)) { try (Reader cr = storage.getContentReader()) { ContentUtils.saveContentToFile( cr, saveFile, GeneralUtils.UTF8_ENCODING, monitor ); } } else { try (InputStream cs = storage.getContentStream()) { ContentUtils.saveContentToFile(cs, saveFile, monitor); } } } catch (Exception e) { throw new InvocationTargetException(e); } }); } catch (InvocationTargetException e) { DBWorkbench.getPlatformUI().showError( ResultSetMessages.model_jdbc_could_not_save_content, ResultSetMessages.model_jdbc_could_not_save_content_to_file_ + saveFile.getAbsolutePath() + "'", //$NON-NLS-2$ e.getTargetException()); } catch (InterruptedException e) { // do nothing } } @Override public void contributeActions(@NotNull IContributionManager manager, @NotNull final IValueController controller, @Nullable IValueEditor activeEditor) throws DBCException { super.contributeActions(manager, controller, activeEditor); contributeContentActions(manager, controller, activeEditor); } @Override public void contributeProperties(@NotNull DBPPropertyManager propertySource, @NotNull IValueController controller) { super.contributeProperties(propertySource, controller); try { Object value = controller.getValue(); if (value instanceof DBDContent) { propertySource.addProperty( PROP_CATEGORY_CONTENT, "content_type", //$NON-NLS-1$ ResultSetMessages.model_jdbc_content_type, ((DBDContent)value).getContentType()); final long contentLength = ((DBDContent) value).getContentLength(); if (contentLength >= 0) { propertySource.addProperty( PROP_CATEGORY_CONTENT, "content_length", //$NON-NLS-1$ ResultSetMessages.model_jdbc_content_length, contentLength); } } } catch (Exception e) { log.warn("Can't extract CONTENT value information", e); //$NON-NLS-1$ } } @NotNull @Override public IValueController.EditType[] getSupportedEditTypes() { return new IValueController.EditType[] {IValueController.EditType.PANEL, IValueController.EditType.EDITOR}; } @Override public IValueEditor createEditor(@NotNull final IValueController controller) throws DBException { switch (controller.getEditType()) { case INLINE: // Open inline/panel editor Object value = controller.getValue(); if (controller.getValueType().getDataKind() == DBPDataKind.STRING) { return new StringInlineEditor(controller); } else if (value instanceof DBDContentCached && ContentUtils.isTextValue(((DBDContentCached) value).getCachedValue())) { return new ContentInlineEditor(controller); } else { return null; } case EDITOR: return openContentEditor(controller); case PANEL: return new ContentPanelEditor(controller); default: return null; } } }
package com.googlecode.mp4parser.boxes.piff; import com.coremedia.iso.IsoFile; import com.coremedia.iso.IsoTypeReader; import com.coremedia.iso.IsoTypeWriter; import com.googlecode.mp4parser.util.Path; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Specifications > Microsoft PlayReady Format Specification > 2. PlayReady Media Format > 2.7. ASF GUIDs * <p/> * <p/> * ASF_Protection_System_Identifier_Object * 9A04F079-9840-4286-AB92E65BE0885F95 * <p/> * ASF_Content_Protection_System_Microsoft_PlayReady * F4637010-03C3-42CD-B932B48ADF3A6A54 * <p/> * ASF_StreamType_PlayReady_Encrypted_Command_Media * 8683973A-6639-463A-ABD764F1CE3EEAE0 * <p/> * <p/> * Specifications > Microsoft PlayReady Format Specification > 2. PlayReady Media Format > 2.5. Data Objects > 2.5.1. Payload Extension for AES in Counter Mode * <p/> * The sample Id is used as the IV in CTR mode. Block offset, starting at 0 and incremented by 1 after every 16 bytes, from the beginning of the sample is used as the Counter. * <p/> * The sample ID for each sample (media object) is stored as an ASF payload extension system with the ID of ASF_Payload_Extension_Encryption_SampleID = {6698B84E-0AFA-4330-AEB2-1C0A98D7A44D}. The payload extension can be stored as a fixed size extension of 8 bytes. * <p/> * The sample ID is always stored in big-endian byte order. */ public class PlayReadyHeader extends ProtectionSpecificHeader { private long length; private List<PlayReadyRecord> records; public PlayReadyHeader() { } @Override public void parse(ByteBuffer byteBuffer) { /* Length DWORD 32 PlayReady Record Count WORD 16 PlayReady Records See Text Varies */ length = IsoTypeReader.readUInt32BE(byteBuffer); int recordCount = IsoTypeReader.readUInt16BE(byteBuffer); records = PlayReadyRecord.createFor(byteBuffer, recordCount); } @Override public ByteBuffer getData() { int size = 4 + 2; for (PlayReadyRecord record : records) { size += 2 + 2; size += record.getValue().rewind().limit(); } ByteBuffer byteBuffer = ByteBuffer.allocate(size); IsoTypeWriter.writeUInt32BE(byteBuffer, size); IsoTypeWriter.writeUInt16BE(byteBuffer, records.size()); for (PlayReadyRecord record : records) { IsoTypeWriter.writeUInt16BE(byteBuffer, record.type); IsoTypeWriter.writeUInt16BE(byteBuffer, record.getValue().limit()); ByteBuffer tmp4debug = record.getValue(); byteBuffer.put(tmp4debug); } return byteBuffer; } public void setRecords(List<PlayReadyRecord> records) { this.records = records; } public List<PlayReadyRecord> getRecords() { return Collections.unmodifiableList(records); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("PlayReadyHeader"); sb.append("{length=").append(length); sb.append(", recordCount=").append(records.size()); sb.append(", records=").append(records); sb.append('}'); return sb.toString(); } public static abstract class PlayReadyRecord { int type; public PlayReadyRecord(int type) { this.type = type; } public static List<PlayReadyRecord> createFor(ByteBuffer byteBuffer, int recordCount) { List<PlayReadyRecord> records = new ArrayList<PlayReadyRecord>(recordCount); for (int i = 0; i < recordCount; i++) { PlayReadyRecord record; int type = IsoTypeReader.readUInt16BE(byteBuffer); int length = IsoTypeReader.readUInt16BE(byteBuffer); switch (type) { case 0x1: record = new RMHeader(); break; case 0x2: record = new DefaulPlayReadyRecord(0x02); break; case 0x3: record = new EmeddedLicenseStore(); break; default: record = new DefaulPlayReadyRecord(type); } record.parse((ByteBuffer) byteBuffer.slice().limit(length)); byteBuffer.position(byteBuffer.position() + length); records.add(record); } return records; } public abstract void parse(ByteBuffer bytes); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("PlayReadyRecord"); sb.append("{type=").append(type); sb.append(", length=").append(getValue().limit()); // sb.append(", value=").append(Hex.encodeHex(getValue())).append('\''); sb.append('}'); return sb.toString(); } public abstract ByteBuffer getValue(); public static class RMHeader extends PlayReadyRecord { String header; public RMHeader() { super(0x01); } @Override public void parse(ByteBuffer bytes) { try { byte[] str = new byte[bytes.slice().limit()]; bytes.get(str); header = new String(str, "UTF-16LE"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public ByteBuffer getValue() { byte[] headerBytes; try { headerBytes = header.getBytes("UTF-16LE"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return ByteBuffer.wrap(headerBytes); } public void setHeader(String header) { this.header = header; } public String getHeader() { return header; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("RMHeader"); sb.append("{length=").append(getValue().limit()); sb.append(", header='").append(header).append('\''); sb.append('}'); return sb.toString(); } } public static class EmeddedLicenseStore extends PlayReadyRecord { ByteBuffer value; public EmeddedLicenseStore() { super(0x03); } @Override public void parse(ByteBuffer bytes) { this.value = bytes.duplicate(); } @Override public ByteBuffer getValue() { return value; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("EmeddedLicenseStore"); sb.append("{length=").append(getValue().limit()); //sb.append(", value='").append(Hex.encodeHex(getValue())).append('\''); sb.append('}'); return sb.toString(); } } public static class DefaulPlayReadyRecord extends PlayReadyRecord { ByteBuffer value; public DefaulPlayReadyRecord(int type) { super(type); } @Override public void parse(ByteBuffer bytes) { this.value = bytes.duplicate(); } @Override public ByteBuffer getValue() { return value; } } } }
package alien4cloud.rest.csar; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.Resource; import javax.validation.Valid; import alien4cloud.audit.annotation.Audit; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.common.collect.Maps; import org.elasticsearch.common.collect.Sets; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import alien4cloud.application.DeploymentSetupService; import alien4cloud.application.InvalidDeploymentSetupException; import alien4cloud.cloud.CloudResourceMatcherService; import alien4cloud.cloud.CloudService; import alien4cloud.cloud.DeploymentService; import alien4cloud.component.ICSARRepositoryIndexerService; import alien4cloud.component.repository.CsarFileRepository; import alien4cloud.component.repository.exception.CSARVersionAlreadyExistsException; import alien4cloud.component.repository.exception.CSARVersionNotFoundException; import alien4cloud.csar.services.CsarService; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.dao.model.FacetedSearchResult; import alien4cloud.exception.AlreadyExistException; import alien4cloud.exception.DeleteReferencedObjectException; import alien4cloud.exception.NotFoundException; import alien4cloud.model.application.DeploymentSetup; import alien4cloud.model.application.DeploymentSetupMatchInfo; import alien4cloud.model.cloud.Cloud; import alien4cloud.model.components.CSARDependency; import alien4cloud.model.components.Csar; import alien4cloud.model.components.IndexedNodeType; import alien4cloud.model.deployment.Deployment; import alien4cloud.model.topology.Topology; import alien4cloud.paas.exception.CloudDisabledException; import alien4cloud.rest.component.SearchRequest; import alien4cloud.rest.model.RestError; import alien4cloud.rest.model.RestErrorBuilder; import alien4cloud.rest.model.RestErrorCode; import alien4cloud.rest.model.RestResponse; import alien4cloud.rest.model.RestResponseBuilder; import alien4cloud.rest.topology.TopologyService; import alien4cloud.security.AuthorizationUtil; import alien4cloud.security.CloudRole; import alien4cloud.tosca.ArchiveUploadService; import alien4cloud.tosca.parser.ParsingError; import alien4cloud.tosca.parser.ParsingErrorLevel; import alien4cloud.tosca.parser.ParsingException; import alien4cloud.tosca.parser.ParsingResult; import alien4cloud.tosca.parser.impl.ErrorCode; import alien4cloud.utils.FileUploadUtil; import alien4cloud.utils.FileUtil; import alien4cloud.utils.VersionUtil; import alien4cloud.utils.YamlParserUtil; import com.google.common.collect.Lists; import com.mangofactory.swagger.annotations.ApiIgnore; import com.wordnik.swagger.annotations.ApiOperation; @RestController @RequestMapping("/rest/csars") @Slf4j public class CloudServiceArchiveController { private static final String DEFAULT_TEST_FOLDER = "test"; @Resource private ArchiveUploadService csarUploadService; @Resource(name = "alien-es-dao") private IGenericSearchDAO csarDAO; @Resource private DeploymentService deploymentService; @Resource private ICSARRepositoryIndexerService indexerService; @Resource private CsarFileRepository alienRepository; private Path tempDirPath; @Resource private CsarService csarService; @Resource private TopologyService topologyService; @Resource private CloudService cloudService; @Resource private CloudResourceMatcherService cloudResourceMatcherService; @Resource private DeploymentSetupService deploymentSetupService; @ApiOperation(value = "Upload a csar zip file.") @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Audit public RestResponse<CsarUploadResult> uploadCSAR(@RequestParam("file") MultipartFile csar) throws IOException { Path csarPath = null; try { log.info("Serving file upload with name [" + csar.getOriginalFilename() + "]"); csarPath = Files.createTempFile(tempDirPath, "", '.' + CsarFileRepository.CSAR_EXTENSION); // save the archive in the temp directory FileUploadUtil.safeTransferTo(csarPath, csar); // load, parse the archive definitions and save on disk ParsingResult<Csar> result = csarUploadService.upload(csarPath); RestError error = null; if (ArchiveUploadService.hasError(result, ParsingErrorLevel.ERROR)) { error = RestErrorBuilder.builder(RestErrorCode.CSAR_PARSING_ERROR).build(); } return RestResponseBuilder.<CsarUploadResult> builder().error(error).data(toUploadResult(result)).build(); } catch (ParsingException e) { log.error("Error happened while parsing csar file <" + e.getFileName() + ">", e); String fileName = e.getFileName() == null ? csar.getOriginalFilename() : e.getFileName(); CsarUploadResult uploadResult = new CsarUploadResult(); uploadResult.getErrors().put(fileName, e.getParsingErrors()); return RestResponseBuilder.<CsarUploadResult> builder().error(RestErrorBuilder.builder(RestErrorCode.CSAR_INVALID_ERROR).build()) .data(uploadResult).build(); } catch (CSARVersionAlreadyExistsException e) { log.error("A CSAR with the same name and the same version already existed in the repository", e); CsarUploadResult uploadResult = new CsarUploadResult(); uploadResult.getErrors().put( csar.getOriginalFilename(), Lists.newArrayList(new ParsingError(ErrorCode.CSAR_ALREADY_EXISTS, "CSAR already exists", null, "Unable to override an existing CSAR if the version is not a SNAPSHOT version.", null, null))); return RestResponseBuilder.<CsarUploadResult> builder().error(RestErrorBuilder.builder(RestErrorCode.ALREADY_EXIST_ERROR).build()) .data(uploadResult).build(); } finally { if (csarPath != null) { // Clean up try { FileUtil.delete(csarPath); } catch (IOException e) { // The repository might just move the file instead of copying to save IO disk access } } } } private CsarUploadResult toUploadResult(ParsingResult<Csar> result) { CsarUploadResult uploadResult = new CsarUploadResult(); uploadResult.setCsar(result.getResult()); addAllSubResultErrors(result, uploadResult); return uploadResult; } private void addAllSubResultErrors(ParsingResult<?> result, CsarUploadResult uploadResult) { if (result.getContext().getParsingErrors() != null && !result.getContext().getParsingErrors().isEmpty()) { uploadResult.getErrors().put(result.getContext().getFileName(), result.getContext().getParsingErrors()); } for (ParsingResult<?> subResult : result.getContext().getSubResults()) { addAllSubResultErrors(subResult, uploadResult); } } /** * Create a CSAR in SNAPSHOT version * * @param request * @return */ @ApiOperation(value = "Create a CSAR in SNAPSHOT version.") @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(value = HttpStatus.CREATED) @Audit public RestResponse<String> createSnapshot(@Valid @RequestBody CreateCsarRequest request) { // new csar instance to save Csar csar = new Csar(); csar.setName(request.getName()); csar.setDescription(request.getDescription()); String version = request.getVersion().endsWith("-SNAPSHOT") ? request.getVersion() : request.getVersion() + "-SNAPSHOT"; csar.setVersion(version); if (csarDAO.count(Csar.class, QueryBuilders.termQuery("id", csar.getId())) > 0) { log.debug("Create csar <{}> impossible (already exists)", csar.getId()); // an csar already exist with the given name. throw new AlreadyExistException("An csar with the given name already exists."); } else { log.debug("Create csar <{}>", csar.getId()); } csarDAO.save(csar); return RestResponseBuilder.<String> builder().data(csar.getId()).build(); } @ApiOperation(value = "Add dependency to the csar with given id.") @RequestMapping(value = "/{csarId:.+?}/dependencies", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Audit public RestResponse<Boolean> addDependency(@PathVariable String csarId, @Valid @RequestBody CSARDependency dependency) { Csar csar = csarDAO.findById(Csar.class, csarId); if (csar == null) { throw new NotFoundException("Cannot add dependency to csar [" + csarId + "] as it cannot be found"); } Set<CSARDependency> existingDependencies = csar.getDependencies(); if (existingDependencies == null) { existingDependencies = Sets.newHashSet(); csar.setDependencies(existingDependencies); } boolean couldBeSaved = existingDependencies.add(dependency); csarDAO.save(csar); return RestResponseBuilder.<Boolean> builder().data(couldBeSaved).build(); } @ApiOperation(value = "Delete a CSAR given its id.") @RequestMapping(value = "/{csarId:.+?}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @Audit public RestResponse<Void> delete(@PathVariable String csarId) { Csar csar = csarService.getMandatoryCsar(csarId); // a csar that is a dependency of another csar can not be deleted Csar[] result = csarService.getDependantCsars(csar.getName(), csar.getVersion()); if (result != null && result.length > 0) { throw new DeleteReferencedObjectException("This csar can not be deleted since it's a dependencie for others"); } // check if some of the nodes are used in topologies. Topology[] topologies = csarService.getDependantTopologies(csar.getName(), csar.getVersion()); if (topologies != null && topologies.length > 0) { throw new DeleteReferencedObjectException("This csar can not be deleted since it's a dependencie for others"); } // latest version indicator will be recomputed to match this new reality indexerService.deleteElements(csar.getName(), csar.getVersion()); csarDAO.delete(Csar.class, csarId); // physically delete files alienRepository.removeCSAR(csar.getName(), csar.getVersion()); return RestResponseBuilder.<Void> builder().build(); } @ApiOperation(value = "Get a CSAR given its id.", notes = "Returns a CSAR.") @RequestMapping(value = "/{csarId:.+?}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public RestResponse<Csar> read(@PathVariable String csarId) { Csar data = csarDAO.findById(Csar.class, csarId); return RestResponseBuilder.<Csar> builder().data(data).build(); } @ApiOperation(value = "Search for cloud service archives.") @RequestMapping(value = "/search", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public RestResponse<FacetedSearchResult> search(@RequestBody SearchRequest searchRequest) { Map<String, String[]> filters = searchRequest.getFilters(); if (filters == null) { filters = Maps.newHashMap(); } FacetedSearchResult searchResult = csarDAO.facetedSearch(Csar.class, searchRequest.getQuery(), filters, null, searchRequest.getFrom(), searchRequest.getSize()); return RestResponseBuilder.<FacetedSearchResult> builder().data(searchResult).build(); } @ApiIgnore // @ApiOperation(value = "Create or update a node type in the given cloud service archive.") @RequestMapping(value = "/{csarId:.+?}/nodetypes", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @Audit public RestResponse<Void> saveNodeType(@PathVariable String csarId, @RequestBody IndexedNodeType nodeType) { Csar csar = csarService.getMandatoryCsar(csarId); // check that the csar version is snapshot. if (VersionUtil.isSnapshot(csar.getVersion())) { nodeType.setArchiveName(csar.getName()); nodeType.setArchiveVersion(csar.getVersion()); indexerService.indexInheritableElement(csar.getName(), csar.getVersion(), nodeType, csar.getDependencies()); return RestResponseBuilder.<Void> builder().build(); } return RestResponseBuilder.<Void> builder().error(RestErrorBuilder.builder(RestErrorCode.CSAR_RELEASE_IMMUTABLE).build()).build(); } @Required @Value("${directories.alien}/${directories.upload_temp}") public void setTempDirPath(String tempDirPath) throws IOException { this.tempDirPath = FileUtil.createDirectoryIfNotExists(tempDirPath); log.info("Temporary folder for upload was set to [" + this.tempDirPath + "]"); } private static class YamlTestFileVisitor extends SimpleFileVisitor<Path> { @Getter private Path yamlTestFile; @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".yaml")) { yamlTestFile = file; } return FileVisitResult.TERMINATE; } } /** * Get only the active deployment for the given application on the given cloud * * @param csarId id of the topology * @return the active deployment */ @ApiOperation(value = "Get active deployment for the given csar snapshot's test topology on the given cloud.", notes = "Application role required [ APPLICATION_MANAGER | APPLICATION_DEVOPS ]") @RequestMapping(value = "/{csarId:.+?}/active-deployment", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public RestResponse<Deployment> getActiveDeployment(@PathVariable String csarId) { Csar csar = csarService.getMandatoryCsar(csarId); if (csar.getTopologyId() == null || csar.getCloudId() == null) { return RestResponseBuilder.<Deployment> builder().build(); } Deployment deployment = deploymentService.getActiveDeployment(csar.getCloudId(), csar.getTopologyId()); return RestResponseBuilder.<Deployment> builder().data(deployment).build(); } @ApiOperation(value = "Deploy snapshot archive on a given cloud.") @RequestMapping(value = "/{csarName:.+?}/version/{csarVersion:.+?}/cloudid/{cloudId:.+?}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Audit public RestResponse<String> deploySnapshot(@PathVariable String csarName, @PathVariable String csarVersion, @PathVariable String cloudId) throws CSARVersionNotFoundException, IOException { Cloud cloud = cloudService.getMandatoryCloud(cloudId); AuthorizationUtil.checkAuthorizationForCloud(cloud, CloudRole.values()); String archiveId = csarName + ":" + csarVersion; Csar csar = csarDAO.findById(Csar.class, archiveId); String deploymentId = null; if (csar == null) { throw new NotFoundException("Cannot find the CSAR with name [" + csarName + "] and version [" + csarVersion + "]"); } if (deploymentService.getActiveDeployment(csar.getTopologyId(), csar.getCloudId()) != null) { throw new AlreadyExistException("You cannot have more than a single deployment for a given CSAR."); } String version = csar.getVersion(); if (!version.contains("-SNAPSHOT")) { throw new NotFoundException("Csar with id [" + csarName + "] is not in SNAPSHOT"); } else { try { // load topology yaml file from "test" folder Path myCsar = alienRepository.getCSAR(csarName, csarVersion); FileSystem csarFS = FileSystems.newFileSystem(myCsar, null); Path definitionsFolderPath = csarFS.getPath(DEFAULT_TEST_FOLDER); if (!Files.exists(definitionsFolderPath)) { throw new NotFoundException("yaml template should exist in folder [" + DEFAULT_TEST_FOLDER + "]"); } // read the first yaml file found (only one currently) YamlTestFileVisitor testFileExtractor = new YamlTestFileVisitor(); Files.walkFileTree(definitionsFolderPath, testFileExtractor); testFileExtractor.getYamlTestFile(); Path yamlFilePath = testFileExtractor.getYamlTestFile(); if (yamlFilePath == null) { throw new NotFoundException("Cannot find a yaml file in subfolder [" + DEFAULT_TEST_FOLDER + "]"); } // define a new topology String topologyId = csar.getTopologyId(); if (topologyId == null) { topologyId = UUID.randomUUID().toString(); csar.setTopologyId(topologyId); } csar.setCloudId(cloudId); csarDAO.save(csar); // update the topology object for the CSAR. Topology topology = YamlParserUtil.parseFromUTF8File(yamlFilePath, Topology.class); topology.setId(topologyId); csarDAO.save(topology); // deploy this topology DeploymentSetup deploymentSetup = new DeploymentSetup(); DeploymentSetupMatchInfo deploymentSetupMatchInfo = deploymentSetupService.generateCloudResourcesMapping(deploymentSetup, topology, cloud, false); if (!deploymentSetupMatchInfo.isValid()) { throw new InvalidDeploymentSetupException("Test topology for CSAR [" + csar.getId() + "] is not deployable on the cloud [" + cloud.getId() + "] because it contains unmatchable resources"); } deploymentSetupService.generatePropertyDefinition(deploymentSetup, cloud); deploymentId = deploymentService.deployTopology(topology, csar, deploymentSetup, cloudId); } catch (CloudDisabledException e) { return RestResponseBuilder.<String> builder().data(null).error(new RestError(RestErrorCode.CLOUD_DISABLED_ERROR.getCode(), e.getMessage())) .build(); } } return RestResponseBuilder.<String> builder().data(deploymentId).build(); } }
package io.searchbox.client; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.junit.Test; import org.skyscreamer.jsonassert.JSONAssert; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.searchbox.annotations.JestId; /** * @author Dogukan Sonmez */ public class JestResultTest { JestResult result = new JestResult(new Gson()); @Test public void extractGetResource() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); Map<String, Object> expectedResultMap = new LinkedHashMap<String, Object>(); expectedResultMap.put("user", "kimchy"); expectedResultMap.put("postDate", "2009-11-15T14:12:12"); expectedResultMap.put("message", "trying out Elastic Search"); expectedResultMap.put(JestResult.ES_METADATA_ID, "1"); JsonObject actualResultMap = result.extractSource().get(0).getAsJsonObject(); assertEquals(expectedResultMap.size(), actualResultMap.entrySet().size()); for (String key : expectedResultMap.keySet()) { assertEquals(expectedResultMap.get(key).toString(), actualResultMap.get(key).getAsString()); } } @Test public void extractGetResourceWithoutMetadata() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); Map<String, Object> expectedResultMap = new LinkedHashMap<String, Object>(); expectedResultMap.put("user", "kimchy"); expectedResultMap.put("postDate", "2009-11-15T14:12:12"); expectedResultMap.put("message", "trying out Elastic Search"); JsonObject actualResultMap = result.extractSource(false).get(0).getAsJsonObject(); assertEquals(expectedResultMap.size(), actualResultMap.entrySet().size()); for (String key : expectedResultMap.keySet()) { assertEquals(expectedResultMap.get(key).toString(), actualResultMap.get(key).getAsString()); } } @Test public void extractGetResourceWithLongId() { Long actualId = Integer.MAX_VALUE + 10l; String response = "{\n" + " \"_index\" : \"blog\",\n" + " \"_type\" : \"comment\",\n" + " \"_id\" : \"" + actualId.toString() + "\", \n" + " \"_source\" : {\n" + " \"someIdName\" : \"" + actualId.toString() + "\"\n," + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); Comment actual = result.getSourceAsObject(Comment.class); assertNotNull(actual); assertEquals(new Long(Integer.MAX_VALUE + 10l), actual.getSomeIdName()); } @Test public void extractGetResourceWithLongIdNotInSource() { Long actualId = Integer.MAX_VALUE + 10l; String response = "{\n" + " \"_index\" : \"blog\",\n" + " \"_type\" : \"comment\",\n" + " \"_id\" : \"" + actualId.toString() + "\", \n" + " \"_source\" : {\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); SimpleComment actual = result.getSourceAsObject(SimpleComment.class); assertNotNull(actual); assertEquals(new Long(Integer.MAX_VALUE + 10l), actual.getSomeIdName()); } @Test public void extractUnFoundGetResource() { String response = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"13333\",\"exists\":false}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); List<JsonElement> resultList = result.extractSource(); assertNotNull(resultList); assertEquals(0, resultList.size()); } @Test public void getGetSourceAsObject() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); Twitter twitter = result.getSourceAsObject(Twitter.class); assertNotNull(twitter); assertEquals("kimchy", twitter.getUser()); assertEquals("trying out Elastic Search", twitter.getMessage()); assertEquals("2009-11-15T14:12:12", twitter.getPostDate()); } @Test public void getGetSourceAsObjectWithoutMetadata() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); Map twitter = result.getSourceAsObject(Map.class, false); assertNotNull(twitter); assertEquals("kimchy", twitter.get("user")); assertEquals("trying out Elastic Search", twitter.get("message")); assertEquals("2009-11-15T14:12:12", twitter.get("postDate")); assertNull(twitter.get(JestResult.ES_METADATA_ID)); assertNull(twitter.get(JestResult.ES_METADATA_VERSION)); } @Test public void getGetSourceAsString() throws JSONException { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); String onlySource = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2009-11-15T14:12:12\"," + "\"message\":\"trying out Elastic Search\"" + "}"; JSONAssert.assertEquals(onlySource, result.getSourceAsString(), false); } @Test public void getGetSourceAsStringArray() throws JSONException { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : [" + " { \"user\" : \"kimch\" }, " + " { \"user\" : \"bello\" }," + " { \"user\" : \"ionex\" }" + " ]\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); String onlySource = "[" + "{\"user\":\"kimch\"}," + "{\"user\":\"bello\"}," + "{\"user\":\"ionex\"}" + "]"; JSONAssert.assertEquals(onlySource, result.getSourceAsString(), false); } @Test public void getGetSourceAsStringNoResult() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\" \n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); result.setSucceeded(true); assertNull(result.getSourceAsString()); } @Test public void getUnFoundGetResultAsAnObject() { String response = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"13333\",\"exists\":false}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); assertNull(result.getSourceAsObject(Twitter.class)); } @Test public void extractUnFoundMultiGetResource() { String response = "{\n" + "\n" + "\"docs\":\n" + "[\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"1\",\"exists\":false},\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"2\",\"exists\":false}\n" + "]\n" + "\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); List<JsonElement> actual = result.extractSource(); assertEquals(expected.size(), actual.size()); } @Test public void extractMultiGetWithSourcePartlyFound() { String response = "{\"docs\":" + "[" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"2\",\"exists\":false},\n" + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":2,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}" + "]}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); Map<String, Object> expectedMap1 = new LinkedHashMap<String, Object>(); expectedMap1.put("user", "kimchy"); expectedMap1.put("post_date", "2009-11-15T14:12:12"); expectedMap1.put("message", "trying out Elastic Search"); expected.add(expectedMap1); List<JsonElement> actual = result.extractSource(); assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { Map<String, Object> expectedMap = expected.get(i); JsonObject actualMap = actual.get(i).getAsJsonObject(); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key).toString(), actualMap.get(key).getAsString()); } } } @Test public void extractMultiGetWithSource() { String response = "{\"docs\":" + "[" + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":9,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}," + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":2,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}" + "]}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); Map<String, Object> expectedMap1 = new LinkedHashMap<String, Object>(); expectedMap1.put("user", "kimchy"); expectedMap1.put("post_date", "2009-11-15T14:12:12"); expectedMap1.put("message", "trying out Elastic Search"); Map<String, Object> expectedMap2 = new LinkedHashMap<String, Object>(); expectedMap2.put("user", "kimchy"); expectedMap2.put("post_date", "2009-11-15T14:12:12"); expectedMap2.put("message", "trying out Elastic Search"); expected.add(expectedMap1); expected.add(expectedMap2); List<JsonElement> actual = result.extractSource(); for (int i = 0; i < expected.size(); i++) { Map<String, Object> expectedMap = expected.get(i); JsonObject actualMap = actual.get(i).getAsJsonObject(); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key).toString(), actualMap.get(key).getAsString()); } } } @Test public void getMultiGetSourceAsObject() { String response = "{\"docs\":" + "[" + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":9,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}," + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":2,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"dogukan\",\n" + " \"postDate\" : \"2012\",\n" + " \"message\" : \"My message\"\n" + "}}" + "]}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); result.setSucceeded(true); List<Twitter> twitterList = result.getSourceAsObjectList(Twitter.class); assertEquals(2, twitterList.size()); assertEquals("kimchy", twitterList.get(0).getUser()); assertEquals("trying out Elastic Search", twitterList.get(0).getMessage()); assertEquals("2009-11-15T14:12:12", twitterList.get(0).getPostDate()); assertEquals("dogukan", twitterList.get(1).getUser()); assertEquals("My message", twitterList.get(1).getMessage()); assertEquals("2012", twitterList.get(1).getPostDate()); } @Test public void getUnFoundMultiGetSourceAsObject() { String response = "{\n" + "\n" + "\"docs\":\n" + "[\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"1\",\"exists\":false},\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"2\",\"exists\":false}\n" + "]\n" + "\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); result.setSucceeded(true); List<Twitter> twitterList = result.getSourceAsObjectList(Twitter.class); assertEquals(0, twitterList.size()); } @Test public void extractEmptySearchSource() { String response = "{\"took\":60,\"timed_out\":false,\"_shards\":{\"total\":1,\"successful\":1," + "\"failed\":0},\"hits\":{\"total\":0,\"max_score\":null,\"hits\":[]}}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); List<JsonElement> actual = result.extractSource(); assertEquals(expected.size(), actual.size()); } @Test public void extractSearchSource() { String response = "{\n" + " \"_shards\":{\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " },\n" + " \"hits\":{\n" + " \"total\" : 1,\n" + " \"hits\" : [\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_version\" : \"2\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); Map<String, Object> expectedResultMap = new LinkedHashMap<String, Object>(); expectedResultMap.put("user", "kimchy"); expectedResultMap.put("postDate", "2009-11-15T14:12:12"); expectedResultMap.put("message", "trying out Elastic Search"); JsonObject actualResultMap = result.extractSource().get(0).getAsJsonObject(); assertEquals(expectedResultMap.size() + 2, actualResultMap.entrySet().size()); for (String key : expectedResultMap.keySet()) { assertEquals(expectedResultMap.get(key).toString(), actualResultMap.get(key).getAsString()); } } @Test public void getSearchSourceAsObject() { String response = "{\n" + " \"_shards\":{\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " },\n" + " \"hits\":{\n" + " \"total\" : 1,\n" + " \"hits\" : [\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + " },\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"dogukan\",\n" + " \"postDate\" : \"2012\",\n" + " \"message\" : \"My Search Result\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); result.setSucceeded(true); List<Twitter> twitterList = result.getSourceAsObjectList(Twitter.class); assertEquals(2, twitterList.size()); assertEquals("kimchy", twitterList.get(0).getUser()); assertEquals("trying out Elastic Search", twitterList.get(0).getMessage()); assertEquals("2009-11-15T14:12:12", twitterList.get(0).getPostDate()); assertEquals("dogukan", twitterList.get(1).getUser()); assertEquals("My Search Result", twitterList.get(1).getMessage()); assertEquals("2012", twitterList.get(1).getPostDate()); } @Test public void getSearchSourceAsObjectWithoutMetadata() { String response = "{\n" + " \"_shards\":{\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " },\n" + " \"hits\":{\n" + " \"total\" : 1,\n" + " \"hits\" : [\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); result.setSucceeded(true); List<Map> twitterList = result.getSourceAsObjectList(Map.class, false); assertEquals(1, twitterList.size()); assertEquals("kimchy", twitterList.get(0).get("user")); assertEquals("trying out Elastic Search", twitterList.get(0).get("message")); assertEquals("2009-11-15T14:12:12", twitterList.get(0).get("postDate")); assertNull(twitterList.get(0).get(JestResult.ES_METADATA_ID)); assertNull(twitterList.get(0).get(JestResult.ES_METADATA_VERSION)); } @Test public void extractIndexSource() { String response = "{\n" + " \"ok\" : true,\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\"\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); Map<String, Object> expectedMap = new LinkedHashMap<String, Object>(); expectedMap.put("ok", true); expectedMap.put("_index", "twitter"); expectedMap.put("_type", "tweet"); expectedMap.put("_id", "1"); expected.add(expectedMap); List<JsonElement> actual = result.extractSource(); for (int i = 0; i < expected.size(); i++) { Map<String, Object> map = expected.get(i); JsonObject actualMap = actual.get(i).getAsJsonObject(); for (String key : map.keySet()) { assertEquals(map.get(key).toString(), actualMap.get(key).getAsString()); } } } @Test public void extractCountResult() { String response = "{\n" + " \"count\" : 1,\n" + " \"_shards\" : {\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("count"); Double actual = result.extractSource().get(0).getAsDouble(); assertEquals(1.0, actual, 0.01); } @Test public void getCountSourceAsObject() { String response = "{\n" + " \"count\" : 1,\n" + " \"_shards\" : {\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("count"); result.setSucceeded(true); Double count = result.getSourceAsObject(Double.class); assertEquals(1.0, count, 0.01); } @Test public void getKeysWithPathToResult() { result.setPathToResult("_source"); String[] expected = {"_source"}; String[] actual = result.getKeys(); assertEquals(1, actual.length); assertEquals(expected[0], actual[0]); } @Test public void getKeysWithoutPathToResult() { assertNull(result.getKeys()); } class Twitter { String user; String postDate; String message; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPostDate() { return postDate; } public void setPostDate(String postDate) { this.postDate = postDate; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } abstract class Base { @JestId Long someIdName; public Long getSomeIdName() { return someIdName; } public void setSomeIdName(Long someIdName) { this.someIdName = someIdName; } } class Comment extends Base { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } class SimpleComment { @JestId Long someIdName; String message; public Long getSomeIdName() { return someIdName; } public void setSomeIdName(Long someIdName) { this.someIdName = someIdName; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
/* * $Header$ * $Revision$ * $Date$ * * ==================================================================== * * Copyright 2005 Elliotte Rusty Harold. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the Jaxen Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * This software consists of voluntary contributions made by many * individuals on behalf of the Jaxen Project and was originally * created by bob mcwhirter <bob@werken.com> and * James Strachan <jstrachan@apache.org>. For more information on the * Jaxen Project, please see <http://www.jaxen.org/>. * * $Id$ */ package org.jaxen.test; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.TestCase; import org.jaxen.FunctionCallException; import org.jaxen.JaxenException; import org.jaxen.XPath; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Document; /** * @author Elliotte Rusty Harold * */ public class SubstringTest extends TestCase { private Document doc; public void setUp() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.newDocument(); doc.appendChild(doc.createElement("root")); } public SubstringTest(String name) { super(name); } public void testSubstringOfNumber() throws JaxenException { XPath xpath = new DOMXPath( "substring(1234, 3)" ); String result = (String) xpath.evaluate( doc ); assertEquals("34", result); } public void testSubstringOfNumber2() throws JaxenException { XPath xpath = new DOMXPath( "substring(1234, 2, 3)" ); String result = (String) xpath.evaluate( doc ); assertEquals("234", result); } // Unusual tests from XPath spec public void testUnusualSubstring1() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 1.5, 2.6)" ); String result = (String) xpath.evaluate( doc ); assertEquals("234", result); } public void testUnusualSubstring2() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 0, 3)" ); String result = (String) xpath.evaluate( doc ); assertEquals("12", result); } public void testUnusualSubstring3() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 0 div 0, 3)" ); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testUnusualSubstring4() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 1, 0 div 0)" ); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testUnusualSubstring5() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', -42, 1 div 0)" ); String result = (String) xpath.evaluate( doc ); assertEquals("12345", result); } public void testUnusualSubstring6() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', -1 div 0, 1 div 0)" ); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testSubstringOfNaN() throws JaxenException { XPath xpath = new DOMXPath( "substring(0 div 0, 2)" ); String result = (String) xpath.evaluate( doc ); assertEquals("aN", result); } public void testSubstringOfEmptyString() throws JaxenException { XPath xpath = new DOMXPath( "substring('', 2)" ); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testSubstringWithNegativeLength() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 2, -3)" ); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testSubstringWithExcessiveLength() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 2, 32)" ); String result = (String) xpath.evaluate( doc ); assertEquals("2345", result); } public void testSubstringWithNegativeLength2() throws JaxenException { XPath xpath = new DOMXPath( "substring('12345', 2, -1)" ); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testSubstringFunctionRequiresAtLeastTwoArguments() throws JaxenException { XPath xpath = new DOMXPath("substring('a')"); try { xpath.selectNodes(doc); fail("Allowed substring function with one argument"); } catch (FunctionCallException ex) { assertNotNull(ex.getMessage()); } } public void testNegativeStartNoLength() throws JaxenException { XPath xpath = new DOMXPath("substring('Hello', -50)"); String result = (String) xpath.evaluate( doc ); assertEquals("Hello", result); } public void testNegativeStartWithLength() throws JaxenException { XPath xpath = new DOMXPath("substring('Hello', -50, 20)"); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testSubstringFunctionRequiresAtMostThreeArguments() throws JaxenException { XPath xpath = new DOMXPath("substring('a', 1, 1, 4)"); try { xpath.selectNodes(doc); fail("Allowed substring function with four arguments"); } catch (FunctionCallException ex) { assertNotNull(ex.getMessage()); } } public void testStringLengthCountsUnicodeCharactersNotJavaChars() throws JaxenException { XPath xpath = new DOMXPath("substring('A\uD834\uDD00', 1, 2)"); String result = (String) xpath.evaluate( doc ); assertEquals("A\uD834\uDD00", result); } public void testStringLengthIndexesUnicodeCharactersNotJavaChars() throws JaxenException { XPath xpath = new DOMXPath("substring('A\uD834\uDD00', 3, 1)"); String result = (String) xpath.evaluate( doc ); assertEquals("", result); } public void testStringLengthIndexesAndCountsUnicodeCharactersNotJavaChars() throws JaxenException { XPath xpath = new DOMXPath("substring('A\uD834\uDD00123', 3, 2)"); String result = (String) xpath.evaluate( doc ); assertEquals("12", result); } }
/* * 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.ignite.internal.processors.cache; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import javax.cache.CacheException; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * */ public class IgniteCachePutAllRestartTest extends GridCommonAbstractTest { /** Cache name. */ private static final String CACHE_NAME = "partitioned"; /** IP finder. */ private static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** */ private static final int NODES = 4; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setPeerClassLoadingEnabled(false); ((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1); ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder); CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setName(CACHE_NAME); cacheCfg.setWriteSynchronizationMode(FULL_SYNC); cacheCfg.setCacheMode(CacheMode.PARTITIONED); cacheCfg.setBackups(1); cacheCfg.setAtomicityMode(TRANSACTIONAL); cacheCfg.setNearConfiguration(null); cfg.setCacheConfiguration(cacheCfg); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { System.setProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL, "true"); super.beforeTestsStarted(); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { System.clearProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); } /** {@inheritDoc} */ @Override protected long getTestTimeout() { return 5 * 60_000; } /** * @throws Exception If failed. */ public void testStopNode() throws Exception { startGrids(NODES); final AtomicBoolean stop = new AtomicBoolean(); IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Object>() { @Override public Object call() throws Exception { Thread.currentThread().setName("put-thread"); IgniteCache<Integer, Integer> cache = ignite(0).cache(CACHE_NAME); Random rnd = new Random(); int iter = 0; while (!stop.get()) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < 10; i++) map.put(rnd.nextInt(1000), i); try { cache.putAll(map); } catch (CacheException e) { log.info("Update failed: " + e); } iter++; if (iter % 1000 == 0) log.info("Iteration: " + iter); } return null; } }); try { ThreadLocalRandom rnd = ThreadLocalRandom.current(); long endTime = System.currentTimeMillis() + 2 * 60_000; while (System.currentTimeMillis() < endTime) { int node = rnd.nextInt(1, NODES); stopGrid(node); startGrid(node); } } finally { stop.set(true); } fut.get(); } /** * @throws Exception If failed. */ public void testStopOriginatingNode() throws Exception { startGrids(NODES); ThreadLocalRandom rnd = ThreadLocalRandom.current(); long endTime = System.currentTimeMillis() + 2 * 60_000; while (System.currentTimeMillis() < endTime) { int node = rnd.nextInt(0, NODES); final Ignite ignite = ignite(node); info("Running iteration on the node [idx=" + node + ", nodeId=" + ignite.cluster().localNode().id() + ']'); final IgniteCache<Integer, Integer> cache = ignite.cache(CACHE_NAME); IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Void>() { @Override public Void call() throws Exception { Thread.currentThread().setName("put-thread"); Random rnd = new Random(); long endTime = System.currentTimeMillis() + 60_000; try { int iter = 0; while (System.currentTimeMillis() < endTime) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < 10; i++) map.put(rnd.nextInt(1000), i); cache.putAll(map); iter++; log.info("Iteration: " + iter); } fail("Should fail."); } catch (CacheException | IllegalStateException e) { log.info("Expected error: " + e); } return null; } }); ignite.close(); fut.get(); startGrid(node); } } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.packaging.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.SuppressForbidden; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Wrapper to run shell commands and collect their outputs in a less verbose way */ public class Shell { public static final Result NO_OP = new Shell.Result(0, "", ""); protected final Logger logger = LogManager.getLogger(getClass()); final Map<String, String> env = new HashMap<>(); String umask; Path workingDirectory; public Shell() { this.workingDirectory = null; } /** * Reset the shell to its newly created state. */ public void reset() { env.clear(); workingDirectory = null; umask = null; } public Map<String, String> getEnv() { return env; } public void setWorkingDirectory(Path workingDirectory) { this.workingDirectory = workingDirectory; } public void setUmask(String umask) { this.umask = umask; } /** * Run the provided string as a shell script. On Linux the {@code bash -c [script]} syntax will be used, and on Windows * the {@code powershell.exe -Command [script]} syntax will be used. Throws an exception if the exit code of the script is nonzero */ public Result run(String script) { return runScript(getScriptCommand(script)); } /** * Same as {@link #run(String)}, but does not throw an exception if the exit code of the script is nonzero */ public Result runIgnoreExitCode(String script) { return runScriptIgnoreExitCode(getScriptCommand(script)); } public void chown(Path path) throws Exception { Platforms.onLinux(() -> run("chown -R elasticsearch:elasticsearch " + path)); Platforms.onWindows( () -> run( String.format( Locale.ROOT, "$account = New-Object System.Security.Principal.NTAccount '%s'; " + "$pathInfo = Get-Item '%s'; " + "$toChown = @(); " + "if ($pathInfo.PSIsContainer) { " + " $toChown += Get-ChildItem '%s' -Recurse; " + "}" + "$toChown += $pathInfo; " + "$toChown | ForEach-Object { " + " $acl = Get-Acl $_.FullName; " + " $acl.SetOwner($account); " + " Set-Acl $_.FullName $acl " + "}", System.getenv("username"), path, path ) ) ); } public void extractZip(Path zipPath, Path destinationDir) throws Exception { Platforms.onLinux(() -> run("unzip \"" + zipPath + "\" -d \"" + destinationDir + "\"")); Platforms.onWindows(() -> run("Expand-Archive -Path \"" + zipPath + "\" -DestinationPath \"" + destinationDir + "\"")); } public Result run(String command, Object... args) { String formattedCommand = String.format(Locale.ROOT, command, args); return run(formattedCommand); } protected String[] getScriptCommand(String script) { if (Platforms.WINDOWS) { return powershellCommand(script); } else { return bashCommand(script); } } private String[] bashCommand(String script) { List<String> command = new ArrayList<>(); command.add("bash"); command.add("-c"); if (umask == null) { command.add(script); } else { command.add(String.format(Locale.ROOT, "umask %s && %s", umask, script)); } return command.toArray(new String[0]); } private static String[] powershellCommand(String script) { return new String[] { "powershell.exe", "-Command", script }; } private Result runScript(String[] command) { logger.warn("Running command with env: " + env); Result result = runScriptIgnoreExitCode(command); if (result.isSuccess() == false) { throw new ShellException("Command was not successful: [" + String.join(" ", command) + "]\n result: " + result.toString()); } return result; } private Result runScriptIgnoreExitCode(String[] command) { ProcessBuilder builder = new ProcessBuilder(); builder.command(command); if (workingDirectory != null) { setWorkingDirectory(builder, workingDirectory); } builder.environment().keySet().remove("JAVA_HOME"); // start with a fresh environment for (Map.Entry<String, String> entry : env.entrySet()) { builder.environment().put(entry.getKey(), entry.getValue()); } final Path stdOut; final Path stdErr; try { Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir")); Files.createDirectories(tmpDir); stdOut = Files.createTempFile(tmpDir, getClass().getName(), ".out"); stdErr = Files.createTempFile(tmpDir, getClass().getName(), ".err"); } catch (IOException e) { throw new UncheckedIOException(e); } redirectOutAndErr(builder, stdOut, stdErr); try { Process process = builder.start(); if (process.waitFor(10, TimeUnit.MINUTES) == false) { if (process.isAlive()) { process.destroyForcibly(); } Result result = new Result(-1, readFileIfExists(stdOut), readFileIfExists(stdErr)); throw new IllegalStateException( "Timed out running shell command: " + Arrays.toString(command) + "\n" + "Result:\n" + result ); } Result result = new Result(process.exitValue(), readFileIfExists(stdOut), readFileIfExists(stdErr)); logger.info("Ran: {} {}", Arrays.toString(command), result); return result; } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } finally { try { FileUtils.deleteIfExists(stdOut); FileUtils.deleteIfExists(stdErr); } catch (UncheckedIOException e) { logger.info("Cleanup of output files failed", e); } } } private String readFileIfExists(Path path) throws IOException { if (Files.exists(path)) { long size = Files.size(path); if (size > 100 * 1024) { return "<<Too large to read: " + size + " bytes>>"; } try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) { return lines.collect(Collectors.joining("\n")); } } else { return ""; } } @SuppressForbidden(reason = "ProcessBuilder expects java.io.File") private void redirectOutAndErr(ProcessBuilder builder, Path stdOut, Path stdErr) { builder.redirectOutput(stdOut.toFile()); builder.redirectError(stdErr.toFile()); } @SuppressForbidden(reason = "ProcessBuilder expects java.io.File") private static void setWorkingDirectory(ProcessBuilder builder, Path path) { builder.directory(path.toFile()); } public String toString() { return String.format(Locale.ROOT, " env = [%s] workingDirectory = [%s]", env, workingDirectory); } public static class Result { public final int exitCode; public final String stdout; public final String stderr; public Result(int exitCode, String stdout, String stderr) { this.exitCode = exitCode; this.stdout = stdout; this.stderr = stderr; } public boolean isSuccess() { return exitCode == 0; } public String toString() { return String.format(Locale.ROOT, "exitCode = [%d] stdout = [%s] stderr = [%s]", exitCode, stdout.trim(), stderr.trim()); } } /** * An exception to model failures to run a shell command. This exists so that calling code can differentiate between * shell / command errors, and other runtime errors. */ public static class ShellException extends RuntimeException { public ShellException(String message) { super(message); } public ShellException(String message, Throwable cause) { super(message, cause); } } }
package info.novatec.testit.webtester.pageobjects; import org.apache.commons.lang.StringUtils; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.novatec.testit.webtester.api.annotations.Mapping; import info.novatec.testit.webtester.api.browser.Browser; import info.novatec.testit.webtester.api.callbacks.PageObjectCallback; import info.novatec.testit.webtester.api.callbacks.PageObjectCallbackWithReturnValue; import info.novatec.testit.webtester.api.events.Event; import info.novatec.testit.webtester.api.exceptions.WrongElementClassException; import info.novatec.testit.webtester.api.pageobjects.Identification; import info.novatec.testit.webtester.api.pageobjects.PageObjectFactory; import info.novatec.testit.webtester.api.pageobjects.PageObjectList; import info.novatec.testit.webtester.eventsystem.EventSystem; import info.novatec.testit.webtester.eventsystem.events.pageobject.ClickedEvent; import info.novatec.testit.webtester.internal.annotations.SetViaInjection; import info.novatec.testit.webtester.internal.pageobjects.ActionTemplate; import info.novatec.testit.webtester.internal.pageobjects.PageObjectModel; import info.novatec.testit.webtester.internal.validation.MappingValidator; import info.novatec.testit.webtester.utils.Identifications; import info.novatec.testit.webtester.utils.Marker; import info.novatec.testit.webtester.utils.PageObjectFinder; import info.novatec.testit.webtester.utils.PageObjectFinder.IdentificationFinder; import info.novatec.testit.webtester.utils.PageObjectFinder.TypedFinder; /** * Base implementation for all page object classes. Any class sub-classing this * class must have a default constructor. Objects of this and any subclass * should not be initialized manually. Instead a {@linkplain PageObjectFactory} * must be used! * * @since 0.9.0 */ public class PageObject { private static final Logger logger = LoggerFactory.getLogger(PageObject.class); @SetViaInjection private PageObjectModel model; private ActionTemplate actionTemplate; private MappingValidator validator; /** * This is the hard coded {@link WebElement} used in case the page object acts as a wrapper instead of a proxy. */ private WebElement webElement; protected PageObject() { this.actionTemplate = new ActionTemplate(this); this.validator = new MappingValidator(getClass()); } /** * Tries to find the {@link WebElement web element} described by this * {@link PageObject page object's} {@link PageObjectModel model}. * <p> * If caching is active the web element will be stored once it was * successfully found and future invocations of this method will return the * cached instance. If caching is not active the web element will be * resolved anew with each invocation. * * @return the web element of this page object. * @throws NoSuchElementException if the web element could not be found. * @since 0.9.9 */ public WebElement getWebElement() { if(webElement != null) { return validate(webElement); } return validate(findWebElement()); } private WebElement findWebElement() { SearchContext searchContext = model.getSearchContext(); return searchContext.findElement(model.getSeleniumBy()); } /** * Executes a validation that checks the {@link WebElement} to make sure the * correct {@link PageObject} class was used to initialize it. If this check * fails an {@link WrongElementClassException} is thrown. * * @param element the element to check * @return the same web element instance in case the validation was successful * @throws WrongElementClassException if check fails * @since 0.9.9 */ protected final WebElement validate(WebElement element) { if (validator.canValidate()) { validator.assertValidity(element); } else { if (!isCorrectClassForWebElement(element)) { throw new WrongElementClassException(getClass()); } } return element; } /** * Check if a given {@linkplain WebElement} is a valid instance of this * specific {@linkplain PageObject} type.<br> * The default implementation always returns true for all * {@linkplain WebElement WebElements}.<br> * <b>Child Classes should override this method!</b> * * @param webElementToBeChecked the element to check * @return true if the {@linkplain WebElement} is a valid instance of this * specific {@linkplain PageObject} type, false otherwise * @since 0.9.0 * @deprecated will be removed with v1.3.0 - the annotation based {@link Mapping} approach should be used instead */ @Deprecated protected boolean isCorrectClassForWebElement(WebElement webElementToBeChecked) { return true; } /** * @return the {@linkplain Browser browser} in which this * {@linkplain PageObject page object} is displayed. * @since 0.9.0 */ public Browser getBrowser() { return model.getBrowser(); } /** * @return this {@linkplain PageObject page object's} parent. Might be null * if this page object has no parent. * @since 0.9.0 */ public PageObject getParent() { return model.getParent(); } /** * @return this {@link PageObject page object's} human readable name. Might * be empty in case no name was given. * @since 0.9.9 */ public String getHumanReadableName() { return model.getName(); } protected PageObjectModel getModel() { return model; } /** * Executes a click on this {@linkplain PageObject page object}. Will throw * an exception if the page object is invisible but not if it is disabled! * * @return the same instance for fluent API * @since 0.9.0 */ public PageObject click() { executeAction(new PageObjectCallback() { @Override public void execute(PageObject pageObject) { getWebElement().click(); logger.debug(logMessage("clicked")); fireEventAndMarkAsUsed(new ClickedEvent(pageObject)); } }); return this; } /** * @return the visible text between the opening and closing tag represented * by this {@linkplain PageObject}. * @since 0.9.0 */ public String getVisibleText() { return executeAction(new PageObjectCallbackWithReturnValue<String>() { @Override public String execute(PageObject pageObject) { pageObject.markAsRead(); return getWebElement().getText(); } }); } /** * @return whether or not the {@linkplain PageObject} exists and is * currently visible * @since 0.9.0 */ public boolean isVisible() { return executeAction(new PageObjectCallbackWithReturnValue<Boolean>() { @Override public Boolean execute(PageObject pageObject) { try { return pageObject.getWebElement().isDisplayed(); } catch (NoSuchElementException e) { return Boolean.FALSE; } } }); } /** * Returns whether or not this {@link PageObject} is part of the current page's DOM. * This can be used to avoid catching the {@link NoSuchElementException} in order to check if an element exists. * * @return true if the object is part of the page's DOM * @see WebElement * @since 1.2.0 */ public boolean isPresent() { try { getWebElement(); return true; } catch (NoSuchElementException e) { return false; } } /** * @return whether or not the {@linkplain PageObject} is currently enabled * @since 0.9.0 */ public boolean isEnabled() { return executeAction(new PageObjectCallbackWithReturnValue<Boolean>() { @Override public Boolean execute(PageObject pageObject) { return getWebElement().isEnabled(); } }); } /** * Returns the underlying elements tag name. * <p> * This method is preferred to something like * <code>pageObject.getWebElement().getTageName();</code> because it uses * the page objects action mechanism to allow for default exception handling * and other features. * * @return the attribute's value as an integer * @since 0.9.7 */ public String getTagName() { return executeAction(new PageObjectCallbackWithReturnValue<String>() { @Override public String execute(PageObject pageObject) { return pageObject.getWebElement().getTagName(); } }); } /** * Sets the value of an attribute of this {@link PageObject} using JavaScript. * <p> * <b>Example:</b> * <pre> * // will change the value of a text field to 'foo' * textField.setAttribute("value", "foo"); * </pre> * * @param attributeName the name of the attribute to set * @param value the value to set the attribute to * @since 1.2.0 */ public void setAttribute(String attributeName, String value) { String escapedValue = StringUtils.replace(value, "\"", "\\\""); String script = "arguments[0]." + attributeName + " = \"" + escapedValue + "\""; getBrowser().executeJavaScript(script, this, value); } /** * @param attributeName the name of the attribute for which the value should * be returned * @return the value of the given attribute, or null if the attribute is not * set * @since 0.9.0 */ public String getAttribute(final String attributeName) { return executeAction(new PageObjectCallbackWithReturnValue<String>() { @Override public String execute(PageObject pageObject) { String attributeValue = getWebElement().getAttribute(attributeName); return log(attributeValue); } private String log(String value) { logger.trace(logMessage("returning '{}' for attribute '{}'"), value, attributeName); return value; } }); } /** * Returns the given attribute's value as an integer. If that attribute * could not be found <code>null</code> is returned! * * @param attributeName name of the attribute * @return the attribute's value as an integer */ protected Integer getAttributeAsInt(String attributeName) { /* handled in two distinct steps in order to guarantee correct exception * recognition */ final String attributeValue = getAttribute(attributeName); return executeAction(new PageObjectCallbackWithReturnValue<Integer>() { @Override public Integer execute(PageObject pageObject) { if (attributeValue == null) { return null; } return Integer.valueOf(attributeValue); } }); } /** * @param propertyName the name of the css property for which the value * should be returned * @return the value of the given css property or null if the property is * not set * @since 0.9.0 */ public String getCssProperty(final String propertyName) { return executeAction(new PageObjectCallbackWithReturnValue<String>() { @Override public String execute(PageObject pageObject) { return getWebElement().getCssValue(propertyName); } }); } /** * Creates a new {@link PageObjectFinder page object finder} for this page * object. This finder can be used to programmatically identify and create * {@link PageObject page objects}. * <p> * This page object will be used as the parent of all created page objects * an in doing so limit the search scope of the operation. Only elements * within this page objects HTML tags will be considered! * * @return the newly create finder * @since 0.9.9 */ public PageObjectFinder finder() { return new PageObjectFinder(this); } /** * Shorthand method for finding a {@link GenericElement generic page * element} via a CSS-Selector expression. * <p> * This page object will be used as the parent of all created page objects * an in doing so limit the search scope of the operation. Only elements * within this page objects HTML tags will be considered! * <p> * <b>Examples:</b> * <ul> * <li><code>pageObject.find("#username").sendKeys("testuser");</code></li> * <li><code>pageObject.find("#button").click();</code></li> * <li><code>pageObject.find("#headline").getVisibleText();</code></li> * </ul> * * @param cssSelector the CSS-Selector expression to use * @return the generic element for the given selector * @since 0.9.9 */ public GenericElement find(String cssSelector) { return finder().findGeneric().by(cssSelector); } /** * Shorthand method for finding a {@link PageObjectList list} of * {@link GenericElement generic page elements} via a CSS-Selector * expression. * <p> * This page object will be used as the parent of all created page objects * an in doing so limit the search scope of the operation. Only elements * within this page objects HTML tags will be considered! * <p> * <b>Examples:</b> * <ul> * <li><code>pageObject.findMany(".button").filter(is(visible()));</code> * </li> * </ul> * * @param cssSelector the CSS-Selector expression to use * @return the list of generic elements for the given selector * @since 0.9.9 */ public PageObjectList<GenericElement> findMany(String cssSelector) { return finder().findGeneric().manyBy(cssSelector); } /** * Shorthand method for creating a new {@link IdentificationFinder * identification based finder}. Matching {@link Identification * identification} instances can be created using the * {@link Identifications} utility class. * <p> * This page object will be used as the parent of all created page objects * an in doing so limit the search scope of the operation. Only elements * within this page objects HTML tags will be considered! * <p> * <b>Examples:</b> * <ul> * <li> * <code>pageObject.findBy(id("username")).as(TextField.class).setText("testuser");</code> * </li> * <li> * <code>pageObject.findBy(css("#button")).as(Button.class).click();</code> * </li> * <li> * <code>pageObject.findBy(xpath(".//h1")).asGeneric().getVisibleText();</code> * </li> * </ul> * * @param identification the identification to use when identifying an * element * @return the new identification finder * @since 0.9.9 */ public IdentificationFinder findBy(Identification identification) { return finder().findBy(identification); } /** * Shorthand method for creating a new {@link TypedFinder type based finder} * . The given page object class is used for all subsequent operations on * the finder. * <p> * This page object will be used as the parent of all created page objects * an in doing so limit the search scope of the operation. Only elements * within this page objects HTML tags will be considered! * <p> * <b>Examples:</b> * <ul> * <li> * <code>pageObject.find(TextField.class).by(id("username")).setText("testuser");</code> * </li> * <li> * <code>pageObject.find(Button.class).by(css("#button")).click();</code> * </li> * <li> * <code>pageObject.find(GenericElement.class).by(xpath(".//h1")).getVisibleText();</code> * </li> * </ul> * * @param <T> the type of the page object to create a finder for * @param pageObjectClass the page object class to use when creating an * element * @return the new type finder * @since 0.9.9 */ public <T extends PageObject> TypedFinder<T> find(Class<T> pageObjectClass) { return finder().find(pageObjectClass); } /** * Invalidates this {@linkplain PageObject} forcing it to reinitialize * itself when it is used again. This can be necessary when the element is * modified by the system under test (e.g. moved). * * @since 0.9.9 * @deprecated caching was removed in v1.2 - this exists in order to NOT break the API till v1.3 */ @Deprecated public void invalidate() { // TODO: remove in v1.3 logger.warn("deprecated method 'invalidate()' used..."); } /** * Fires the given event using the {@linkplain EventSystem#fireEvent(Event)} * method and mark this page object as used using * {@linkplain Marker#markAsUsed(PageObject)}. * * @param event the event to fire. * @since 0.9.0 */ protected final void fireEventAndMarkAsUsed(Event event) { EventSystem.fireEvent(event); Marker.markAsUsed(this); logger.trace(logMessage("fired event: {}"), event); } protected final void markAsRead() { Marker.markAsRead(this); } protected final void markAsUsed() { Marker.markAsUsed(this); } /** * Creates a new instance for the given {@linkplain PageObject page object} * class using the {@linkplain Browser browser's} creation mechanism. This * is a convenience method. * * @param pageClass the class of which an instance should be created. * @param <T> the class of the {@link PageObject} to create * @return the created instance. * @since 0.9.6 */ protected final <T extends PageObject> T create(Class<T> pageClass) { return getBrowser().create(pageClass); } /** * Executes the given {@link PageObjectCallback callback} with this * {@link PageObject page object} as input. This is a convenience method for calling the * {@link ActionTemplate#executeAction(PageObjectCallback)} method. * * @param callback the callback to execute * @since 0.9.7 */ public final void executeAction(PageObjectCallback callback) { actionTemplate.executeAction(callback); } /** * Executes the given {@link PageObjectCallbackWithReturnValue callback} * with this {@link PageObject page object} as input and a return value of * type B as output. This is a convenience method for calling the * {@link ActionTemplate#executeAction(PageObjectCallbackWithReturnValue)} method. * * @param <B> the type of the return value of the action * @param callback the callback to execute * @return the return value of the callback * @since 0.9.7 */ public final <B> B executeAction(PageObjectCallbackWithReturnValue<B> callback) { return actionTemplate.executeAction(callback); } protected String logMessage(String message) { return model.getLogPrefix() + message; } @Override public String toString() { StringBuilder subject = new StringBuilder(getClass().getSimpleName()); String name = model.getName(); if (StringUtils.isNotBlank(name)) { subject.append(" \"").append(name).append('\"'); } Identification identification = model.getIdentification(); if (identification != null) { subject.append(" identified by ").append(identification); } return subject.toString(); } }
/* * 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.trino.execution; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import io.trino.Session; import io.trino.connector.CatalogName; import io.trino.execution.warnings.WarningCollector; import io.trino.metadata.ProcedureRegistry; import io.trino.metadata.QualifiedObjectName; import io.trino.security.AccessControl; import io.trino.security.InjectedConnectorAccessControl; import io.trino.spi.TrinoException; import io.trino.spi.block.BlockBuilder; import io.trino.spi.connector.ConnectorAccessControl; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.eventlistener.RoutineInfo; import io.trino.spi.procedure.Procedure; import io.trino.spi.procedure.Procedure.Argument; import io.trino.spi.type.Type; import io.trino.sql.PlannerContext; import io.trino.sql.planner.ParameterRewriter; import io.trino.sql.tree.Call; import io.trino.sql.tree.CallArgument; import io.trino.sql.tree.Expression; import io.trino.sql.tree.ExpressionTreeRewriter; import io.trino.sql.tree.NodeRef; import io.trino.sql.tree.Parameter; import io.trino.transaction.TransactionManager; import javax.inject.Inject; import java.lang.invoke.MethodType; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Predicate; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.base.Verify.verify; import static com.google.common.util.concurrent.Futures.immediateVoidFuture; import static io.trino.metadata.MetadataUtil.createQualifiedObjectName; import static io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND; import static io.trino.spi.StandardErrorCode.INVALID_ARGUMENTS; import static io.trino.spi.StandardErrorCode.INVALID_PROCEDURE_ARGUMENT; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.StandardErrorCode.PROCEDURE_CALL_FAILED; import static io.trino.spi.type.TypeUtils.writeNativeValue; import static io.trino.sql.ParameterUtils.parameterExtractor; import static io.trino.sql.analyzer.SemanticExceptions.semanticException; import static io.trino.sql.planner.ExpressionInterpreter.evaluateConstantExpression; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; public class CallTask implements DataDefinitionTask<Call> { private final TransactionManager transactionManager; private final PlannerContext plannerContext; private final AccessControl accessControl; private final ProcedureRegistry procedureRegistry; @Inject public CallTask(TransactionManager transactionManager, PlannerContext plannerContext, AccessControl accessControl, ProcedureRegistry procedureRegistry) { this.transactionManager = requireNonNull(transactionManager, "transactionManager is null"); this.plannerContext = requireNonNull(plannerContext, "plannerContext is null"); this.accessControl = requireNonNull(accessControl, "accessControl is null"); this.procedureRegistry = requireNonNull(procedureRegistry, "procedureRegistry is null"); } @Override public String getName() { return "CALL"; } @Override public ListenableFuture<Void> execute( Call call, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) { if (!transactionManager.isAutoCommit(stateMachine.getSession().getRequiredTransactionId())) { throw new TrinoException(NOT_SUPPORTED, "Procedures cannot be called within a transaction (use autocommit mode)"); } Session session = stateMachine.getSession(); QualifiedObjectName procedureName = createQualifiedObjectName(session, call, call.getName()); CatalogName catalogName = plannerContext.getMetadata().getCatalogHandle(stateMachine.getSession(), procedureName.getCatalogName()) .orElseThrow(() -> semanticException(CATALOG_NOT_FOUND, call, "Catalog '%s' does not exist", procedureName.getCatalogName())); Procedure procedure = procedureRegistry.resolve(catalogName, procedureName.asSchemaTableName()); // map declared argument names to positions Map<String, Integer> positions = new HashMap<>(); for (int i = 0; i < procedure.getArguments().size(); i++) { positions.put(procedure.getArguments().get(i).getName(), i); } // per specification, do not allow mixing argument types Predicate<CallArgument> hasName = argument -> argument.getName().isPresent(); boolean anyNamed = call.getArguments().stream().anyMatch(hasName); boolean allNamed = call.getArguments().stream().allMatch(hasName); if (anyNamed && !allNamed) { throw semanticException(INVALID_ARGUMENTS, call, "Named and positional arguments cannot be mixed"); } // get the argument names in call order Map<String, CallArgument> names = new LinkedHashMap<>(); for (int i = 0; i < call.getArguments().size(); i++) { CallArgument argument = call.getArguments().get(i); if (argument.getName().isPresent()) { String name = argument.getName().get(); if (names.put(name, argument) != null) { throw semanticException(INVALID_ARGUMENTS, argument, "Duplicate procedure argument: %s", name); } if (!positions.containsKey(name)) { throw semanticException(INVALID_ARGUMENTS, argument, "Unknown argument name: %s", name); } } else if (i < procedure.getArguments().size()) { names.put(procedure.getArguments().get(i).getName(), argument); } else { throw semanticException(INVALID_ARGUMENTS, call, "Too many arguments for procedure"); } } procedure.getArguments().stream() .filter(Argument::isRequired) .filter(argument -> !names.containsKey(argument.getName())) .map(Argument::getName) .findFirst() .ifPresent(argument -> { throw semanticException(INVALID_ARGUMENTS, call, "Required procedure argument '%s' is missing", argument); }); // get argument values Object[] values = new Object[procedure.getArguments().size()]; Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(call, parameters); for (Entry<String, CallArgument> entry : names.entrySet()) { CallArgument callArgument = entry.getValue(); int index = positions.get(entry.getKey()); Argument argument = procedure.getArguments().get(index); Expression expression = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(parameterLookup), callArgument.getValue()); Type type = argument.getType(); Object value = evaluateConstantExpression(expression, type, plannerContext, session, accessControl, parameterLookup); values[index] = toTypeObjectValue(session, type, value); } // fill values with optional arguments defaults for (int i = 0; i < procedure.getArguments().size(); i++) { Argument argument = procedure.getArguments().get(i); if (!names.containsKey(argument.getName())) { verify(argument.isOptional()); values[i] = toTypeObjectValue(session, argument.getType(), argument.getDefaultValue()); } } // validate arguments MethodType methodType = procedure.getMethodHandle().type(); for (int i = 0; i < procedure.getArguments().size(); i++) { if ((values[i] == null) && methodType.parameterType(i).isPrimitive()) { String name = procedure.getArguments().get(i).getName(); throw new TrinoException(INVALID_PROCEDURE_ARGUMENT, "Procedure argument cannot be null: " + name); } } // insert session argument List<Object> arguments = new ArrayList<>(); Iterator<Object> valuesIterator = asList(values).iterator(); for (Class<?> type : methodType.parameterList()) { if (ConnectorSession.class.equals(type)) { arguments.add(session.toConnectorSession(catalogName)); } else if (ConnectorAccessControl.class.equals(type)) { arguments.add(new InjectedConnectorAccessControl(accessControl, session.toSecurityContext(), catalogName.getCatalogName())); } else { arguments.add(valuesIterator.next()); } } accessControl.checkCanExecuteProcedure(session.toSecurityContext(), procedureName); stateMachine.setRoutines(ImmutableList.of(new RoutineInfo(procedureName.getObjectName(), session.getUser()))); try { procedure.getMethodHandle().invokeWithArguments(arguments); } catch (Throwable t) { if (t instanceof InterruptedException) { Thread.currentThread().interrupt(); } throwIfInstanceOf(t, TrinoException.class); throw new TrinoException(PROCEDURE_CALL_FAILED, t); } return immediateVoidFuture(); } private static Object toTypeObjectValue(Session session, Type type, Object value) { BlockBuilder blockBuilder = type.createBlockBuilder(null, 1); writeNativeValue(type, blockBuilder, value); return type.getObjectValue(session.toConnectorSession(), blockBuilder, 0); } }
/******************************************************************************* * * Copyright (c) 2004-2009 Oracle Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Kohsuke Kawaguchi, CloudBees, Inc. * * *******************************************************************************/ package hudson.model; import hudson.Util; import hudson.model.listeners.ItemListener; import hudson.security.AccessControlled; import hudson.util.CopyOnWriteMap; import hudson.util.Function1; import hudson.util.IOUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.eclipse.hudson.security.team.Team; import org.eclipse.hudson.security.team.TeamManager; import org.eclipse.hudson.security.team.TeamManager.TeamNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Defines a bunch of static methods to be used as a "mix-in" for * {@link ItemGroup} implementations. Not meant for a consumption from outside * {@link ItemGroup}s. * * @author Kohsuke Kawaguchi */ public abstract class ItemGroupMixIn { private transient Logger logger = LoggerFactory.getLogger(ItemGroupMixIn.class); /** * {@link ItemGroup} for which we are working. */ private final ItemGroup parent; private final AccessControlled acl; protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) { this.parent = parent; this.acl = acl; } /* * Callback methods to be implemented by the ItemGroup implementation. */ /** * Adds a newly created item to the parent. */ protected abstract void add(TopLevelItem item); /** * Assigns the root directory for a prospective item. */ protected abstract File getRootDirFor(String name); /* * The rest is the methods that provide meat. */ /** * Loads all the child {@link Item}s. * * @param modulesDir Directory that contains sub-directories for each child * item. */ public static <K, V extends Item> Map<K, V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K, ? super V> key) { modulesDir.mkdirs(); // make sure it exists File[] subdirs = modulesDir.listFiles(new FileFilter() { public boolean accept(File child) { return child.isDirectory(); } }); CopyOnWriteMap.Tree<K, V> configurations = new CopyOnWriteMap.Tree<K, V>(); for (File subdir : subdirs) { try { V item = (V) Items.load(parent, subdir, false); configurations.put(key.call(item), item); } catch (IOException e) { e.printStackTrace(); // TODO: logging } } return configurations; } /** * {@link Item} -> name function. */ public static final Function1<String, Item> KEYED_BY_NAME = new Function1<String, Item>() { public String call(Item item) { return item.getName(); } }; /** * Creates a {@link TopLevelItem} from the submission of the * '/lib/hudson/newFromList/formList' or throws an exception if it fails. */ public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { acl.checkPermission(Job.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if (requestContentType == null) { throw new Failure("No Content-Type header set"); } boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if (name == null) { throw new Failure("Query parameter 'name' is required"); } String team = null; { // check if the name looks good Hudson hudson = Hudson.getInstance(); Hudson.checkGoodName(name); name = name.trim(); if (hudson.isTeamManagementEnabled() && (name.indexOf(TeamManager.TEAM_SEPARATOR) != -1)) { throw new Failure("The job name cannot contain" + TeamManager.TEAM_SEPARATOR + "when team management is enabled. "); } // see if team requested Team requestedTeam = null; if (hudson.isTeamManagementEnabled()) { team = req.getParameter("team"); if (team != null){ String teamName = team.trim(); if (teamName.length() > 0) { try { requestedTeam = hudson.getTeamManager().findTeam(teamName); team = teamName; } catch (TeamManager.TeamNotFoundException ex) { throw new Failure("Requested team " + teamName + " not found"); } } else { team = null; } } } String existingJobName = name; if (hudson.isTeamManagementEnabled()){ existingJobName = requestedTeam == null ? hudson.getTeamManager().getRawTeamQualifiedJobName(name) : hudson.getTeamManager().getRawTeamQualifiedJobName(requestedTeam, name); } if (parent.getItem(existingJobName) != null) { throw new Failure(Messages.Hudson_JobAlreadyExists(existingJobName)); } } String mode = req.getParameter("mode"); if (mode != null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = parent.getItem(from); if (src == null) { src = Hudson.getInstance().getItemByFullName(from); } if (src == null) { if (Util.fixEmpty(from) == null) { throw new Failure("Specify which job to copy"); } else { throw new Failure("No such job: " + from); } } if (!(src instanceof TopLevelItem)) { throw new Failure(from + " cannot be copied"); } result = copy((TopLevelItem) src, name, team); } else { if (isXmlSubmission) { result = createProjectFromXML(name, team, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if (mode == null) { throw new Failure("No mode given"); } // create empty job and redirect to the project config screen result = createProject(Items.getDescriptor(mode), name, team, true); } } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; } /** * Computes the redirection target URL for the newly created * {@link TopLevelItem}. */ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { return req.getContextPath() + '/' + result.getUrl() + "configure"; } /** * Copies an existing {@link TopLevelItem} to a new name. * * The caller is responsible for calling * {@link ItemListener#fireOnCopied(Item, Item)}. This method cannot do that * because it doesn't know how to make the newly added item reachable from * the parent. */ @SuppressWarnings({"unchecked" }) public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException { return copy(src, name, null); } /** * Copies an existing {@link TopLevelItem} to a new name. * * The caller is responsible for calling * {@link ItemListener#fireOnCopied(Item, Item)}. This method cannot do that * because it doesn't know how to make the newly added item reachable from * the parent. */ @SuppressWarnings({"unchecked" }) public synchronized <T extends TopLevelItem> T copy(T src, String name, String teamName) throws IOException { acl.checkPermission(Job.CREATE); String jobName = createInTeam(name, teamName); T result = (T) createProject(src.getDescriptor(), jobName, false); // copy config Util.copyFile(Items.getConfigFile(src).getFile(), Items.getConfigFile(result).getFile()); // reload from the new config result = (T) Items.load(parent, result.getRootDir()); result.onCopiedFrom(src); add(result); ItemListener.fireOnCopied(src, Hudson.getInstance().getItem(result.getName())); return result; } private String createInTeam(String name, String teamName) throws IOException { // To be created in a specific team, a job must first be added // to the team, ensuring that Hudson will find the correct rootDir. TeamManager teamManager = Hudson.getInstance().getTeamManager(); if (!teamManager.isTeamManagementEnabled()) { if (teamName != null) { throw new IOException("Team management is not enabled"); } return name; } Team team; if (teamName == null) { try { team = teamManager.findCurrentUserTeamForNewJob(); } catch (TeamNotFoundException ex) { // Shouldn't happen, as user is already confirmed for Job.CREATE return name; } } else { try { team = teamManager.findTeam(teamName); } catch (TeamNotFoundException e) { throw new IOException("Team "+teamName+" does not exist"); } } // addJob does the necessary name assembly and returns qualified job name return teamManager.addJob(name, team); } public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { return createProjectFromXML(name, null, xml); } public synchronized TopLevelItem createProjectFromXML(String name, String teamName, InputStream xml) throws IOException { acl.checkPermission(Job.CREATE); String jobName = createInTeam(name, teamName); // place it as config.xml File configXml = Items.getConfigFile(getRootDirFor(jobName)).getFile(); configXml.getParentFile().mkdirs(); try { IOUtils.copy(xml, configXml); // load it TopLevelItem result = (TopLevelItem) Items.load(parent, configXml.getParentFile(), false); add(result); assert(result.getName().equals(jobName)); ItemListener.fireOnCreated(Hudson.getInstance().getItem(jobName)); Hudson.getInstance().rebuildDependencyGraph(); return result; } catch (IOException e) { // if anything fails, delete the config file to avoid further confusion Hudson.getInstance().getTeamManager().removeJob(jobName); Util.deleteRecursive(configXml.getParentFile()); throw e; } } public synchronized TopLevelItem createProject(TopLevelItemDescriptor type, String name, boolean notify) throws IOException { return createProject(type, name, null, notify); } public synchronized TopLevelItem createProject(TopLevelItemDescriptor type, String name, String teamName, boolean notify) throws IOException { acl.checkPermission(Job.CREATE); name = createInTeam(name, teamName); Hudson hudson = Hudson.getInstance(); String existingJobName = name; if (hudson.isTeamManagementEnabled() && teamName == null) { existingJobName = hudson.getTeamManager().getTeamQualifiedJobName(name); } if (parent.getItem(existingJobName) != null) { throw new IllegalArgumentException("Job with name " + name + " already exists"); } TopLevelItem item; try { item = type.newInstance(parent, name); } catch (Exception e) { throw new IllegalArgumentException(e); } item.onCreatedFromScratch(); item.save(); add(item); if (notify) { ItemListener.fireOnCreated(item); } return item; } }
/*L * Copyright Washington University in St. Louis * Copyright SemanticBits * Copyright Persistent Systems * Copyright Krishagni * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/catissue-core/LICENSE.txt for details. */ package edu.wustl.catissuecore.domain.client; import edu.wustl.catissuecore.domain.deintegration.ws.*; import edu.wustl.catissuecore.domain.ws.*; import edu.wustl.catissuecore.domain.util.UniqueKeyGenerator; import gov.nih.nci.cagrid.data.faults.QueryProcessingExceptionType; import java.rmi.RemoteException; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.UUID; /** * @author Ion C. Olaru * Date: 7/21/11 - 10:27 AM */ public class Fixtures { public static Set<edu.wustl.catissuecore.domain.CollectionProtocolRegistration> getCollectionProtocolRegistration(edu.wustl.catissuecore.domain.Participant p) { Set<edu.wustl.catissuecore.domain.CollectionProtocolRegistration> cprs = new HashSet(); edu.wustl.catissuecore.domain.CollectionProtocol cp = new edu.wustl.catissuecore.domain.CollectionProtocol(); cp.setType("CP_TYPE"); cp.setId((long)12); for (byte i=0; i<3; i++) { edu.wustl.catissuecore.domain.CollectionProtocolRegistration cpr = new edu.wustl.catissuecore.domain.CollectionProtocolRegistration(); cpr.setBarcode("BARCODE"); cpr.setCollectionProtocol(cp); cprs.add(cpr); } return cprs; } public static ParticipantCollectionProtocolRegistrationCollection getCollectionProtocolRegistrationWS(Participant p, CollectionProtocol cp) { if (cp == null) { cp = new CollectionProtocol(); cp.setIdentifier(new Long(1)); } CollectionProtocolRegistrationCollectionProtocol cprcp = new CollectionProtocolRegistrationCollectionProtocol(); cprcp.setCollectionProtocol(cp); CollectionProtocolRegistrationParticipant cprp = new CollectionProtocolRegistrationParticipant(); cprp.setParticipant(p); CollectionProtocolRegistration[] cprArray = new CollectionProtocolRegistration[1]; cprArray[0] = new CollectionProtocolRegistration(); cprArray[0].setCollectionProtocol(cprcp); cprArray[0].setActivityStatus("Active"); cprArray[0].setProtocolParticipantIdentifier("WS_PPI-01" + UniqueKeyGenerator.getKey()); cprArray[0].setRegistrationDate(Calendar.getInstance()); cprArray[0].setParticipant(null); ParticipantCollectionProtocolRegistrationCollection pcprc = new ParticipantCollectionProtocolRegistrationCollection(); pcprc.setCollectionProtocolRegistration(cprArray); return pcprc; } public static Institution createInstitution() { Institution i = new Institution(); i.setName("Institution name" + UniqueKeyGenerator.getKey()); i.setRemoteId(Long.parseLong(UniqueKeyGenerator.getKey())); return i; } public static Participant createParticipant() { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, 1959); c.set(Calendar.MONTH, 3); c.set(Calendar.DATE, 17); Participant ws = new Participant(); ws.setActivityStatus("Active"); ws.setLastName("Gorbachev"); ws.setFirstName("Mikhail"); ws.setBirthDate(c); ws.setIdentifier(99); return ws; } public static ParticipantRaceCollection createRaceCollectionForWs(Participant p) { // Participant newP = new Participant(); // newP.setIdentifier(p.getIdentifier()); ParticipantRaceCollection prc = new ParticipantRaceCollection(); Race[] races = new Race[3]; races[0] = new Race(); races[0].setRaceName("Asian"); // races[0].setParticipant(new RaceParticipant()); races[0].getParticipant().setParticipant(p); races[1] = new Race(); races[1].setRaceName("Unknown"); // races[1].setParticipant(new RaceParticipant()); races[1].getParticipant().setParticipant(p); races[2] = new Race(); races[2].setRaceName("White"); // races[2].setParticipant(new RaceParticipant()); races[2].getParticipant().setParticipant(p); prc.setRace(races); return prc; } public static ParticipantParticipantRecordEntryCollection createPRECollectionForWs(Participant p) { ParticipantParticipantRecordEntryCollection prec = new ParticipantParticipantRecordEntryCollection(); ParticipantRecordEntry[] preArray = new ParticipantRecordEntry[1]; prec.setParticipantRecordEntry(preArray); ParticipantRecordEntry pre = new ParticipantRecordEntry(); preArray[0] = pre; return prec; } public static ParticipantParticipantMedicalIdentifierCollection createPMICollectionForWs(Participant p) { ParticipantParticipantMedicalIdentifierCollection pmic = new ParticipantParticipantMedicalIdentifierCollection(); ParticipantMedicalIdentifier[] pmcArray = new ParticipantMedicalIdentifier[2]; Site site1 = new Site(); site1.setIdentifier(1); site1.setName("In Transit"); Site site2 = new Site(); site2.setIdentifier(1); site2.setName("In Transit"); pmcArray[0] = new ParticipantMedicalIdentifier(); pmcArray[0].setMedicalRecordNumber("MRN-01-" + UniqueKeyGenerator.getKey()); pmcArray[0].setSite(new ParticipantMedicalIdentifierSite()); pmcArray[0].getSite().setSite(site1); pmcArray[1] = new ParticipantMedicalIdentifier(); pmcArray[1].setMedicalRecordNumber("MRN-02-" + UniqueKeyGenerator.getKey()); pmcArray[1].setSite(new ParticipantMedicalIdentifierSite()); pmcArray[1].getSite().setSite(site2); pmic.setParticipantMedicalIdentifier(pmcArray); return pmic; } private static OrderDetails createOrderDetails() { OrderDetails od = new OrderDetails(); od.setComment("Comments: WS Java client."); od.setName("Order name 55"); od.setStatus("New"); od.setRequestedDate(Calendar.getInstance()); return od; } public static OrderDetails createOrderWithDerivedSpecimenOrderItem(Catissue_cacoreClient client) throws QueryProcessingExceptionType, RemoteException { Specimen s = new Specimen(); s.setIdentifier(1); OrderDetails od = createOrderDetails(); od.setName(UUID.randomUUID().toString()+" Fixture Test."); od.setOrderItemCollection(new OrderDetailsOrderItemCollection()); DerivedSpecimenOrderItem[] items = new DerivedSpecimenOrderItem[1]; od.getOrderItemCollection().setOrderItem(items); od.setDistributionProtocol(new OrderDetailsDistributionProtocol()); od.getDistributionProtocol().setDistributionProtocol(new DistributionProtocol()); od.getDistributionProtocol().getDistributionProtocol().setIdentifier(2); DerivedSpecimenOrderItem item0 = new DerivedSpecimenOrderItem(); item0.setSpecimenClass("Tissue"); item0.setSpecimenType("DNA"); item0.setStatus("New"); item0.setDescription("Desc OrderItem 0"); item0.setRequestedQuantity(0.1); item0.setNewSpecimenArrayOrderItem(new SpecimenOrderItemNewSpecimenArrayOrderItem()); final NewSpecimenArrayOrderItem newSpecimenArrayOrderItem = new NewSpecimenArrayOrderItem(); newSpecimenArrayOrderItem.setName("Specimen Array OI Name "+UUID.randomUUID().toString()); if (client != null) { NewSpecimenArrayOrderItem saoi = (NewSpecimenArrayOrderItem) client.insert(newSpecimenArrayOrderItem); newSpecimenArrayOrderItem.setIdentifier(saoi.getIdentifier()); } item0.getNewSpecimenArrayOrderItem().setNewSpecimenArrayOrderItem(newSpecimenArrayOrderItem); item0.setParentSpecimen(new DerivedSpecimenOrderItemParentSpecimen()); item0.getParentSpecimen().setSpecimen(s); items[0] = item0; return od; } public static OrderDetails createOrderDetailsWithSOI() { OrderDetails od = createOrderDetails(); od.setName(UUID.randomUUID().toString()+" Fixture Test."); od.setOrderItemCollection(new OrderDetailsOrderItemCollection()); OrderItem[] items = new OrderItem[3]; od.getOrderItemCollection().setOrderItem(items); od.setDistributionProtocol(new OrderDetailsDistributionProtocol()); od.getDistributionProtocol().setDistributionProtocol(new DistributionProtocol()); od.getDistributionProtocol().getDistributionProtocol().setIdentifier(2); OrderItem item0 = new OrderItem(); items[0] = item0; //items[0].setIdentifier(1); item0.setStatus("New"); item0.setDescription(UUID.randomUUID().toString()+"Desc OrderItem 0"); item0.setRequestedQuantity(0.1); SpecimenOrderItem item1 = new SpecimenOrderItem(); items[1] = item1; //items[1].setIdentifier(2); item1.setStatus("New"); item1.setDescription(UUID.randomUUID().toString()+"Desc SpecimenOrderItem 1"); item1.setRequestedQuantity(0.2); SpecimenOrderItem item2 = new SpecimenOrderItem(); items[2] = item2; // items[2].setIdentifier(3); item2.setStatus("New"); item2.setDescription(UUID.randomUUID().toString()+"Desc SpecimenOrderItem 2"); item2.setRequestedQuantity(0.5); return od; } public static DistributionProtocol createDistributionProtocol() { DistributionProtocol dp = new DistributionProtocol(); dp.setStartDate(Calendar.getInstance()); dp.setActivityStatus("Active"); SpecimenProtocolPrincipalInvestigator user = new SpecimenProtocolPrincipalInvestigator(); user.setUser(new User()); user.getUser().setIdentifier(1); dp.setPrincipalInvestigator(user); dp.setTitle("Some Title " + UniqueKeyGenerator.getKey()); dp.setShortTitle("Some Title" + UniqueKeyGenerator.getKey()); DistributionSpecimenRequirement requirement = new DistributionSpecimenRequirement(); //requirement.setDistributionProtocol(dp); requirement.setPathologyStatus("Malignant"); requirement.setQuantity(new Double(3.5)); requirement.setSpecimenClass("Cell"); requirement.setSpecimenType("Slide"); requirement.setTissueSite("Appendix"); //DistributionSpecimenRequirementDistributionProtocol dpSpecimenReq = new DistributionSpecimenRequirementDistributionProtocol(dp); // requirement.setDistributionProtocol(dpSpecimenReq); final DistributionSpecimenRequirement[] distributionSpecimenRequirementArray = new DistributionSpecimenRequirement[]{requirement}; dp.setDistributionSpecimenRequirementCollection(new DistributionProtocolDistributionSpecimenRequirementCollection(distributionSpecimenRequirementArray)); return dp; } public static SpecimenCollectionGroup createSpecimenCollectionGroup() { SpecimenCollectionGroup scg = new SpecimenCollectionGroup(); // event scg.setCollectionProtocolEvent(new SpecimenCollectionGroupCollectionProtocolEvent()); scg.getCollectionProtocolEvent().setCollectionProtocolEvent(new CollectionProtocolEvent()); scg.getCollectionProtocolEvent().getCollectionProtocolEvent().setIdentifier(1); // site scg.setSpecimenCollectionSite(new AbstractSpecimenCollectionGroupSpecimenCollectionSite()); scg.getSpecimenCollectionSite().setSite(new Site()); scg.getSpecimenCollectionSite().getSite().setIdentifier(1); // protocol registration scg.setCollectionProtocolRegistration(new SpecimenCollectionGroupCollectionProtocolRegistration()); scg.getCollectionProtocolRegistration().setCollectionProtocolRegistration(new CollectionProtocolRegistration()); scg.getCollectionProtocolRegistration().getCollectionProtocolRegistration().setIdentifier(1); scg.setClinicalDiagnosis("Not Specified"); scg.setClinicalStatus("Not Specified"); scg.setActivityStatus("Active"); scg.setCollectionStatus("Pending"); scg.setComment("comment"); return scg; } public static CollectionProtocol createCollectionProtocolWithOneCollectionProtocolEvent() { String key = UniqueKeyGenerator.getKey(); CollectionProtocol cp = new CollectionProtocol(); cp.setSiteCollection(new CollectionProtocolSiteCollection()); cp.getSiteCollection().setSite(new Site[1]); cp.getSiteCollection().getSite()[0] = new Site(); cp.getSiteCollection().getSite()[0].setIdentifier(1); cp.setActivityStatus("Active"); cp.setTitle("CP Title - " + key); cp.setShortTitle("CP Short Title - " + key); cp.setStartDate(Calendar.getInstance()); cp.setRemoteId(new Date().getTime()); User pi = new User(); pi.setIdentifier(1); User user = new User(); user.setIdentifier(2); cp.setPrincipalInvestigator(new SpecimenProtocolPrincipalInvestigator()); cp.getPrincipalInvestigator().setUser(pi); cp.setCoordinatorCollection(new CollectionProtocolCoordinatorCollection()); cp.getCoordinatorCollection().setUser(new User[1]); cp.getCoordinatorCollection().getUser()[0] = user; // CPE CollectionProtocolEvent cpe = new CollectionProtocolEvent(); // site cpe.setSpecimenCollectionSite(new AbstractSpecimenCollectionGroupSpecimenCollectionSite()); cpe.getSpecimenCollectionSite().setSite(new Site()); cpe.getSpecimenCollectionSite().getSite().setIdentifier(1); cpe.setClinicalDiagnosis("Not Specified"); cpe.setClinicalStatus("Not Specified"); cpe.setActivityStatus("Active"); cpe.setStudyCalendarEventPoint(5.0); cpe.setCollectionPointLabel("CP LBL2 "+UUID.randomUUID().toString()); cpe.setLabelFormat("%CP_DEFAULT%"); cp.setCollectionProtocolEventCollection(new CollectionProtocolCollectionProtocolEventCollection()); cp.getCollectionProtocolEventCollection().setCollectionProtocolEvent(new CollectionProtocolEvent[1]); cp.getCollectionProtocolEventCollection().getCollectionProtocolEvent()[0] = cpe; return cp; } public static OrderDetails createOrderWithExistingSpecimenOrderItem(long specimenId, long dpId) { OrderDetails od = createOrderDetails(); od.setOrderItemCollection(new OrderDetailsOrderItemCollection()); ExistingSpecimenOrderItem[] items = new ExistingSpecimenOrderItem[1]; od.getOrderItemCollection().setOrderItem(items); od.setDistributionProtocol(new OrderDetailsDistributionProtocol()); od.getDistributionProtocol().setDistributionProtocol(new DistributionProtocol()); od.getDistributionProtocol().getDistributionProtocol().setIdentifier(dpId); ExistingSpecimenOrderItem esoi0 = new ExistingSpecimenOrderItem(); esoi0.setSpecimen(new ExistingSpecimenOrderItemSpecimen()); esoi0.getSpecimen().setSpecimen(new FluidSpecimen()); esoi0.getSpecimen().getSpecimen().setIdentifier(specimenId); // esoi0.getSpecimen().getSpecimen().setSpecimenClass("Fixed Tissue"); esoi0.setStatus("New"); esoi0.setRequestedQuantity(0.2); /* SpecimenSpecimenCollectionGroup sscg = new SpecimenSpecimenCollectionGroup(); sscg.setSpecimenCollectionGroup(new SpecimenCollectionGroup()); sscg.getSpecimenCollectionGroup().setIdentifier(1064); esoi0.getSpecimen().getSpecimen().setSpecimenCollectionGroup(sscg); */ items[0] = esoi0; return od; } public static Distribution createDistribution(long odId, long dpId, long spcId) { Distribution d = new Distribution(); d.setDistributionProtocol(new DistributionDistributionProtocol()); d.getDistributionProtocol().setDistributionProtocol(new DistributionProtocol()); d.getDistributionProtocol().getDistributionProtocol().setIdentifier(dpId); d.setToSite(new DistributionToSite()); d.getToSite().setSite(new Site()); d.getToSite().getSite().setIdentifier(1); d.setActivityStatus("Active"); d.setOrderDetails(new DistributionOrderDetails()); d.getOrderDetails().setOrderDetails(new OrderDetails()); d.getOrderDetails().getOrderDetails().setIdentifier(odId); d.setComment("COMM"); d.setDistributedBy(new DistributionDistributedBy()); d.getDistributedBy().setUser(new User()); d.getDistributedBy().getUser().setIdentifier(1); d.setDistributedItemCollection(new DistributionDistributedItemCollection()); d.getDistributedItemCollection().setDistributedItem(new DistributedItem[1]); d.getDistributedItemCollection().getDistributedItem()[0] = new DistributedItem(); d.getDistributedItemCollection().getDistributedItem()[0].setQuantity(0.2); DistributedItem di = d.getDistributedItemCollection().getDistributedItem()[0]; di.setSpecimen(new DistributedItemSpecimen()); di.getSpecimen().setSpecimen(new FluidSpecimen()); di.getSpecimen().getSpecimen().setIdentifier(spcId); return d; } }
package au.com.dius.pact.consumer; import au.com.dius.pact.consumer.dsl.DslPart; import au.com.dius.pact.consumer.dsl.PactDslJsonBody; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; public class PactDslJsonBodyTest { private static final String NUMBERS = "numbers"; private static final String K_DEPRECIATION_BIPS = "10k-depreciation-bips"; private static final String FIRST = "first"; private static final String LEVEL_1 = "level1"; private static final String L_1_EXAMPLE = "l1example"; private static final String SECOND = "second"; private static final String LEVEL_2 = "level2"; private static final String L_2_EXAMPLE = "l2example"; private static final String THIRD = "@third"; @Test public void guardAgainstObjectNamesThatDontConformToGatlingFields() { DslPart body = new PactDslJsonBody() .id() .object("2") .id() .stringValue("test", "A Test String") .closeObject() .array(NUMBERS) .id() .number(100) .numberValue(101) .hexValue() .object() .id() .stringValue("name", "Rogger the Dogger") .timestamp() .date("dob", "MM/dd/yyyy") .object(K_DEPRECIATION_BIPS) .id() .closeObject() .closeObject() .closeArray(); Set<String> expectedMatchers = new HashSet<String>(Arrays.asList( ".id", "['2'].id", ".numbers[3]", ".numbers[0]", ".numbers[4].timestamp", ".numbers[4].dob", ".numbers[4].id", ".numbers[4]['10k-depreciation-bips'].id" )); assertThat(body.getMatchers().getMatchingRules().keySet(), is(equalTo(expectedMatchers))); assertThat(((JSONObject) body.getBody()).keySet(), is(equalTo((Set) new HashSet(Arrays.asList("2", NUMBERS, "id"))))); } @Test public void guardAgainstFieldNamesThatDontConformToGatlingFields() { DslPart body = new PactDslJsonBody() .id("1") .stringType("@field") .hexValue("200", "abc") .integerType(K_DEPRECIATION_BIPS); Set<String> expectedMatchers = new HashSet<String>(Arrays.asList( "['200']", "['1']", "['@field']", "['10k-depreciation-bips']" )); assertThat(body.getMatchers().getMatchingRules().keySet(), is(equalTo(expectedMatchers))); assertThat(((JSONObject) body.getBody()).keySet(), is(equalTo((Set) new HashSet(Arrays.asList("200", K_DEPRECIATION_BIPS, "1", "@field"))))); } @Test public void eachLikeMatcherTest() { DslPart body = new PactDslJsonBody() .eachLike("ids") .id() .closeObject() .closeArray(); Set<String> expectedMatchers = new HashSet<String>(Arrays.asList( ".ids", ".ids[*].id" )); assertThat(body.getMatchers().getMatchingRules().keySet(), is(equalTo(expectedMatchers))); assertThat(((JSONObject) body.getBody()).keySet(), is(equalTo((Set) new HashSet(Arrays.asList("ids"))))); } @Test public void nestedObjectMatcherTest() { DslPart body = new PactDslJsonBody() .object(FIRST) .stringType(LEVEL_1, L_1_EXAMPLE) .stringType("@level1") .object(SECOND) .stringType(LEVEL_2, L_2_EXAMPLE) .object(THIRD) .stringType("level3", "l3example") .object("fourth") .stringType("level4", "l4example") .closeObject() .closeObject() .closeObject() .closeObject(); Set<String> expectedMatchers = new HashSet<>(Arrays.asList( ".first.second['@third'].fourth.level4", ".first.second['@third'].level3", ".first.second.level2", ".first.level1", ".first['@level1']" )); assertThat(body.getMatchers().getMatchingRules().keySet(), is(equalTo(expectedMatchers))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getString(LEVEL_1), is(equalTo(L_1_EXAMPLE))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getJSONObject(SECOND) .getString(LEVEL_2), is(equalTo(L_2_EXAMPLE))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getJSONObject(SECOND) .getJSONObject(THIRD) .getString("level3"), is(equalTo("l3example"))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getJSONObject(SECOND) .getJSONObject(THIRD) .getJSONObject("fourth") .getString("level4"), is(equalTo("l4example"))); } @Test public void nestedArrayMatcherTest() { DslPart body = new PactDslJsonBody() .array(FIRST) .stringType(L_1_EXAMPLE) .array() .stringType(L_2_EXAMPLE) .closeArray() .closeArray(); Set<String> expectedMatchers = new HashSet<String>(Arrays.asList( ".first[0]", ".first[1][0]" )); assertThat(body.getMatchers().getMatchingRules().keySet(), is(equalTo(expectedMatchers))); assertThat(((JSONObject)body.getBody()) .getJSONArray(FIRST) .getString(0), is(equalTo(L_1_EXAMPLE))); assertThat(((JSONObject)body.getBody()) .getJSONArray(FIRST) .getJSONArray(1) .getString(0), is(equalTo(L_2_EXAMPLE))); } @Test public void nestedArrayAndObjectMatcherTest() { DslPart body = new PactDslJsonBody() .object(FIRST) .stringType(LEVEL_1, L_1_EXAMPLE) .array(SECOND) .stringType("al2example") .object() .stringType(LEVEL_2, L_2_EXAMPLE) .array("third") .stringType("al3example") .closeArray() .closeObject() .closeArray() .closeObject(); Set<String> expectedMatchers = new HashSet<String>(Arrays.asList( ".first.level1", ".first.second[1].level2", ".first.second[0]", ".first.second[1].third[0]" )); assertThat(body.getMatchers().getMatchingRules().keySet(), is(equalTo(expectedMatchers))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getString(LEVEL_1), is(equalTo(L_1_EXAMPLE))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getJSONArray(SECOND) .getString(0), is(equalTo("al2example"))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getJSONArray(SECOND) .getJSONObject(1) .getString(LEVEL_2), is(equalTo(L_2_EXAMPLE))); assertThat(((JSONObject)body.getBody()) .getJSONObject(FIRST) .getJSONArray(SECOND) .getJSONObject(1) .getJSONArray("third") .getString(0), is(equalTo("al3example"))); } @Test public void allowSettingFieldsToNull() { DslPart body = new PactDslJsonBody() .id() .object("2") .id() .stringValue("test", null) .nullValue("nullValue") .closeObject() .array(NUMBERS) .id() .nullValue() .stringValue(null) .closeArray(); JSONObject jsonObject = (JSONObject) body.getBody(); assertThat(jsonObject.keySet(), is(equalTo((Set) new HashSet(Arrays.asList("2", NUMBERS, "id"))))); assertThat(jsonObject.getJSONObject("2").get("test"), is(JSONObject.NULL)); JSONArray numbers = jsonObject.getJSONArray(NUMBERS); assertThat(numbers.length(), is(3)); assertThat(numbers.get(0), is(notNullValue())); assertThat(numbers.get(1), is(JSONObject.NULL)); assertThat(numbers.get(2), is(JSONObject.NULL)); } }
package org.seasar.doma.internal.jdbc.mock; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.Arrays; @SuppressWarnings("RedundantThrows") public class MockStatement extends MockWrapper implements Statement { public boolean closed; public int addBatchCount; public int updatedRows = 1; @Override public void addBatch(String sql) throws SQLException { throw new AssertionError(); } @Override public void cancel() throws SQLException { throw new AssertionError(); } @Override public void clearBatch() throws SQLException { throw new AssertionError(); } @Override public void clearWarnings() throws SQLException { throw new AssertionError(); } @Override public void close() throws SQLException { closed = true; } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { throw new AssertionError(); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { throw new AssertionError(); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { throw new AssertionError(); } @Override public boolean execute(String sql) throws SQLException { return false; } @Override public int[] executeBatch() throws SQLException { int[] results = new int[addBatchCount]; Arrays.fill(results, updatedRows); addBatchCount = 0; return results; } @Override public ResultSet executeQuery(String sql) throws SQLException { throw new AssertionError(); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { throw new AssertionError(); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { throw new AssertionError(); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { throw new AssertionError(); } @Override public int executeUpdate(String sql) throws SQLException { throw new AssertionError(); } @Override public Connection getConnection() throws SQLException { throw new AssertionError(); } @Override public int getFetchDirection() throws SQLException { throw new AssertionError(); } @Override public int getFetchSize() throws SQLException { throw new AssertionError(); } @Override public ResultSet getGeneratedKeys() throws SQLException { throw new AssertionError(); } @Override public int getMaxFieldSize() throws SQLException { throw new AssertionError(); } @Override public int getMaxRows() throws SQLException { throw new AssertionError(); } @Override public boolean getMoreResults() throws SQLException { throw new AssertionError(); } @Override public boolean getMoreResults(int current) throws SQLException { throw new AssertionError(); } @Override public int getQueryTimeout() throws SQLException { throw new AssertionError(); } @Override public ResultSet getResultSet() throws SQLException { throw new AssertionError(); } @Override public int getResultSetConcurrency() throws SQLException { throw new AssertionError(); } @Override public int getResultSetHoldability() throws SQLException { throw new AssertionError(); } @Override public int getResultSetType() throws SQLException { throw new AssertionError(); } @Override public int getUpdateCount() throws SQLException { throw new AssertionError(); } @Override public SQLWarning getWarnings() throws SQLException { throw new AssertionError(); } @Override public boolean isClosed() throws SQLException { return closed; } @Override public boolean isPoolable() throws SQLException { throw new AssertionError(); } @Override public void setCursorName(String name) throws SQLException { throw new AssertionError(); } @Override public void setEscapeProcessing(boolean enable) throws SQLException { throw new AssertionError(); } @Override public void setFetchDirection(int direction) throws SQLException { throw new AssertionError(); } @Override public void setFetchSize(int rows) throws SQLException { throw new AssertionError(); } @Override public void setMaxFieldSize(int max) throws SQLException { throw new AssertionError(); } @Override public void setMaxRows(int max) throws SQLException { throw new AssertionError(); } @Override public void setPoolable(boolean poolable) throws SQLException { throw new AssertionError(); } @Override public void setQueryTimeout(int seconds) throws SQLException {} @SuppressWarnings("all") public void closeOnCompletion() throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public boolean isCloseOnCompletion() throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long getLargeUpdateCount() throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public void setLargeMaxRows(long max) throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long getLargeMaxRows() throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long[] executeLargeBatch() throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long executeLargeUpdate(String sql) throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException { throw new AssertionError(); } @SuppressWarnings("all") public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException { throw new AssertionError(); } }
/* * 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.catalina.startup; import java.io.File; import java.lang.management.ManagementFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import org.apache.catalina.Globals; import org.apache.catalina.security.SecurityClassLoad; import org.apache.catalina.startup.ClassLoaderFactory.Repository; import org.apache.catalina.startup.ClassLoaderFactory.RepositoryType; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * Bootstrap loader for Catalina. This application constructs a class loader * for use in loading the Catalina internal classes (by accumulating all of the * JAR files found in the "server" directory under "catalina.home"), and * starts the regular execution of the container. The purpose of this * roundabout approach is to keep the Catalina internal classes (and any * other classes they depend on, such as an XML parser) out of the system * class path and therefore not visible to application level classes. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id: Bootstrap.java 1142323 2011-07-02 21:57:12Z markt $ */ public final class Bootstrap { private static final Log log = LogFactory.getLog(Bootstrap.class); // ------------------------------------------------------- Static Variables /** * Daemon object used by main. */ private static Bootstrap daemon = null; // -------------------------------------------------------------- Variables /** * Daemon reference. */ private Object catalinaDaemon = null; protected ClassLoader commonLoader = null; protected ClassLoader catalinaLoader = null; protected ClassLoader sharedLoader = null; // -------------------------------------------------------- Private Methods private void initClassLoaders() { try { commonLoader = createClassLoader("common", null); if( commonLoader == null ) { // no config file, default to this loader - we might be in a 'single' env. commonLoader=this.getClass().getClassLoader(); } catalinaLoader = createClassLoader("server", commonLoader); sharedLoader = createClassLoader("shared", commonLoader); } catch (Throwable t) { handleThrowable(t); log.error("Class loader creation threw exception", t); System.exit(1); } } private ClassLoader createClassLoader(String name, ClassLoader parent) throws Exception { String value = CatalinaProperties.getProperty(name + ".loader"); if ((value == null) || (value.equals(""))) return parent; value = replace(value); List<Repository> repositories = new ArrayList<Repository>(); StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { String repository = tokenizer.nextToken().trim(); if (repository.length() == 0) { continue; } // Check for a JAR URL repository try { @SuppressWarnings("unused") URL url = new URL(repository); repositories.add( new Repository(repository, RepositoryType.URL)); continue; } catch (MalformedURLException e) { // Ignore } // Local repository if (repository.endsWith("*.jar")) { repository = repository.substring (0, repository.length() - "*.jar".length()); repositories.add( new Repository(repository, RepositoryType.GLOB)); } else if (repository.endsWith(".jar")) { repositories.add( new Repository(repository, RepositoryType.JAR)); } else { repositories.add( new Repository(repository, RepositoryType.DIR)); } } ClassLoader classLoader = ClassLoaderFactory.createClassLoader (repositories, parent); // Retrieving MBean server MBeanServer mBeanServer = null; if (MBeanServerFactory.findMBeanServer(null).size() > 0) { mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0); } else { mBeanServer = ManagementFactory.getPlatformMBeanServer(); } // Register the server classloader ObjectName objectName = new ObjectName("Catalina:type=ServerClassLoader,name=" + name); mBeanServer.registerMBean(classLoader, objectName); return classLoader; } /** * System property replacement in the given string. * * @param str The original string * @return the modified string */ protected String replace(String str) { // Implementation is copied from ClassLoaderLogManager.replace(), // but added special processing for catalina.home and catalina.base. String result = str; int pos_start = str.indexOf("${"); if (pos_start >= 0) { StringBuilder builder = new StringBuilder(); int pos_end = -1; while (pos_start >= 0) { builder.append(str, pos_end + 1, pos_start); pos_end = str.indexOf('}', pos_start + 2); if (pos_end < 0) { pos_end = pos_start - 1; break; } String propName = str.substring(pos_start + 2, pos_end); String replacement; if (propName.length() == 0) { replacement = null; } else if (Globals.CATALINA_HOME_PROP.equals(propName)) { replacement = getCatalinaHome(); } else if (Globals.CATALINA_BASE_PROP.equals(propName)) { replacement = getCatalinaBase(); } else { replacement = System.getProperty(propName); } if (replacement != null) { builder.append(replacement); } else { builder.append(str, pos_start, pos_end + 1); } pos_start = str.indexOf("${", pos_end + 1); } builder.append(str, pos_end + 1, str.length()); result = builder.toString(); } return result; } /** * Initialize daemon. */ public void init() throws Exception { // Set Catalina path setCatalinaHome(); setCatalinaBase(); initClassLoaders(); Thread.currentThread().setContextClassLoader(catalinaLoader); SecurityClassLoad.securityClassLoad(catalinaLoader); // Load our startup class and call its process() method if (log.isDebugEnabled()) log.debug("Loading startup class"); Class<?> startupClass = catalinaLoader.loadClass ("org.apache.catalina.startup.Catalina"); Object startupInstance = startupClass.newInstance(); // Set the shared extensions class loader if (log.isDebugEnabled()) log.debug("Setting startup class properties"); String methodName = "setParentClassLoader"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Class.forName("java.lang.ClassLoader"); Object paramValues[] = new Object[1]; paramValues[0] = sharedLoader; Method method = startupInstance.getClass().getMethod(methodName, paramTypes); method.invoke(startupInstance, paramValues); catalinaDaemon = startupInstance; } /** * Load daemon. */ private void load(String[] arguments) throws Exception { // Call the load() method String methodName = "load"; Object param[]; Class<?> paramTypes[]; if (arguments==null || arguments.length==0) { paramTypes = null; param = null; } else { paramTypes = new Class[1]; paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } Method method = catalinaDaemon.getClass().getMethod(methodName, paramTypes); if (log.isDebugEnabled()) log.debug("Calling startup class " + method); method.invoke(catalinaDaemon, param); } /** * getServer() for configtest */ private Object getServer() throws Exception { String methodName = "getServer"; Method method = catalinaDaemon.getClass().getMethod(methodName); return method.invoke(catalinaDaemon); } // ----------------------------------------------------------- Main Program /** * Load the Catalina daemon. */ public void init(String[] arguments) throws Exception { init(); load(arguments); } /** * Start the Catalina daemon. */ public void start() throws Exception { if( catalinaDaemon==null ) init(); Method method = catalinaDaemon.getClass().getMethod("start", (Class [] )null); method.invoke(catalinaDaemon, (Object [])null); } /** * Stop the Catalina Daemon. */ public void stop() throws Exception { Method method = catalinaDaemon.getClass().getMethod("stop", (Class [] ) null); method.invoke(catalinaDaemon, (Object [] ) null); } /** * Stop the standalone server. */ public void stopServer() throws Exception { Method method = catalinaDaemon.getClass().getMethod("stopServer", (Class []) null); method.invoke(catalinaDaemon, (Object []) null); } /** * Stop the standalone server. */ public void stopServer(String[] arguments) throws Exception { Object param[]; Class<?> paramTypes[]; if (arguments==null || arguments.length==0) { paramTypes = null; param = null; } else { paramTypes = new Class[1]; paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } Method method = catalinaDaemon.getClass().getMethod("stopServer", paramTypes); method.invoke(catalinaDaemon, param); } /** * Set flag. */ public void setAwait(boolean await) throws Exception { Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Boolean.TYPE; Object paramValues[] = new Object[1]; paramValues[0] = Boolean.valueOf(await); Method method = catalinaDaemon.getClass().getMethod("setAwait", paramTypes); method.invoke(catalinaDaemon, paramValues); } public boolean getAwait() throws Exception { Class<?> paramTypes[] = new Class[0]; Object paramValues[] = new Object[0]; Method method = catalinaDaemon.getClass().getMethod("getAwait", paramTypes); Boolean b=(Boolean)method.invoke(catalinaDaemon, paramValues); return b.booleanValue(); } /** * Destroy the Catalina Daemon. */ public void destroy() { // FIXME } /** * Main method, used for testing only. * * @param args Command line arguments to be processed */ public static void main(String args[]) { if (daemon == null) { // Don't set daemon until init() has completed Bootstrap bootstrap = new Bootstrap(); try { bootstrap.init(); } catch (Throwable t) { handleThrowable(t); t.printStackTrace(); return; } daemon = bootstrap; } try { String command = "start"; if (args.length > 0) { command = args[args.length - 1]; } if (command.equals("startd")) { args[args.length - 1] = "start"; daemon.load(args); daemon.start(); } else if (command.equals("stopd")) { args[args.length - 1] = "stop"; daemon.stop(); } else if (command.equals("start")) { daemon.setAwait(true); daemon.load(args); daemon.start(); } else if (command.equals("stop")) { daemon.stopServer(args); } else if (command.equals("configtest")) { daemon.load(args); if (null==daemon.getServer()) { System.exit(1); } System.exit(0); } else { log.warn("Bootstrap: command \"" + command + "\" does not exist."); } } catch (Throwable t) { handleThrowable(t); // Unwrap the Exception for clearer error reporting if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } t.printStackTrace(); System.exit(1); } } public void setCatalinaHome(String s) { System.setProperty(Globals.CATALINA_HOME_PROP, s); } public void setCatalinaBase(String s) { System.setProperty(Globals.CATALINA_BASE_PROP, s); } /** * Set the <code>catalina.base</code> System property to the current * working directory if it has not been set. */ private void setCatalinaBase() { if (System.getProperty(Globals.CATALINA_BASE_PROP) != null) return; if (System.getProperty(Globals.CATALINA_HOME_PROP) != null) System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty(Globals.CATALINA_HOME_PROP)); else System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty("user.dir")); } /** * Set the <code>catalina.home</code> System property to the current * working directory if it has not been set. */ private void setCatalinaHome() { if (System.getProperty(Globals.CATALINA_HOME_PROP) != null) return; File bootstrapJar = new File(System.getProperty("user.dir"), "bootstrap.jar"); if (bootstrapJar.exists()) { try { System.setProperty (Globals.CATALINA_HOME_PROP, (new File(System.getProperty("user.dir"), "..")) .getCanonicalPath()); } catch (Exception e) { // Ignore System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("user.dir")); } } else { System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("user.dir")); } } /** * Get the value of the catalina.home environment variable. */ public static String getCatalinaHome() { return System.getProperty(Globals.CATALINA_HOME_PROP, System.getProperty("user.dir")); } /** * Get the value of the catalina.base environment variable. */ public static String getCatalinaBase() { return System.getProperty(Globals.CATALINA_BASE_PROP, getCatalinaHome()); } // Copied from ExceptionUtils since that class is not visible during start private static void handleThrowable(Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } // All other instances of Throwable will be silently swallowed } }
/* * Copyright 2014 Andrej Petras. * * 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.lorislab.transformer.api; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.lorislab.transformer.api.factory.ServiceFactory; /** * The model utility class. * * @author Andrej Petras */ public final class Transformer { /** * The logger for this class. */ private static final Logger LOGGER = Logger.getLogger(Transformer.class.getName()); /** * The default constructor. */ private Transformer() { // empty cosntructor } /** * Transform the object to map of string. * * @param data the input object. * @return the corresponding map of field names and string values. */ public static Map<String, String> transform(Object data) { Map<String, String> result = new HashMap<>(); if (data != null) { Class clazz = data.getClass(); Map<String, Field> fields = getFields(clazz); if (fields != null) { for (Field field : fields.values()) { // get the value Object value = null; try { boolean accessible = field.isAccessible(); try { field.setAccessible(true); value = field.get(data); } finally { field.setAccessible(accessible); } } catch (IllegalAccessException | IllegalArgumentException | SecurityException ex) { LOGGER.log(Level.SEVERE, "Error read the value for the field {0}", field.getName()); } // transform the value String tmp = ServiceFactory.getAdapterService().writeValue(value, field.getType()); result.put(field.getName(), tmp); } } } return result; } /** * Transforms the map of strings to the instance of the class. * * @param <T> the instance type. * @param data the map of strings. * @param clazz the class. * @return the corresponding instance. */ public static <T> T transform(Map<String, String> data, Class<T> clazz) { T result = null; if (data != null && clazz != null) { // create instance try { result = clazz.newInstance(); } catch (IllegalAccessException | InstantiationException ex) { LOGGER.log(Level.SEVERE, "Error create the instance for the " + clazz.getName(), ex); } if (result != null) { Map<String, Field> fields = getFields(clazz); for (Entry<String, String> entry : data.entrySet()) { Field field = fields.get(entry.getKey()); if (field != null) { // transform the value Object tmp = ServiceFactory.getAdapterService().readValue(entry.getValue(), field.getType()); // set the value boolean accessible = field.isAccessible(); try { field.setAccessible(true); field.set(result, tmp); } catch (IllegalAccessException | IllegalArgumentException | SecurityException ex) { LOGGER.log(Level.SEVERE, "Error set the value to the instance. Class {0} field {1}", new Object[]{clazz.getName(), field.getName()}); } finally { field.setAccessible(accessible); } } else { LOGGER.log(Level.FINE, "The field {0} is missing in the class {1}", new Object[]{entry.getKey(), clazz.getName()}); } } } } return result; } /** * Transforms the map of strings to the instance of the class. * * @param <T> the instance type. * @param data the map of strings. * @param name the name of the class. * @return the corresponding instance. */ public static <T> T transform(Map<String, String> data, String name) { T result = null; if (name != null && data != null) { // load the class by name. Class<T> clazz = null; try { clazz = (Class<T>) Class.forName(name); } catch (ClassNotFoundException ex) { LOGGER.log(Level.SEVERE, "Error load the class " + name, ex); } if (clazz != null) { result = transform(data, clazz); } } return result; } /** * Gets the list of fields for the class. * * @param clazz the class. * @return the corresponding list of fields. */ private static Map<String, Field> getFields(Class clazz) { Map<String, Field> result = new HashMap<>(); if (clazz != null) { Field[] fields = clazz.getDeclaredFields(); if (fields != null) { for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { result.put(field.getName(), field); } } } } return result; } /** * Gets the list of fields for the class. * * @param clazz the class. * @return the corresponding list of fields. */ public static Set<String> getFieldNames(Class clazz) { Set<String> result = new HashSet<>(); if (clazz != null) { Field[] fields = clazz.getDeclaredFields(); if (fields != null) { for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { result.add(field.getName()); } } } } return result; } /** * Creates object instance by class name. * * @param name the class name. * @return the corresponding object instance. */ public static Object createInstance(String name) { Object result = null; try { Class clazz = Class.forName(name); result = clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { LOGGER.log(Level.SEVERE, null, ex); } return result; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive.functions; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.RealType; import com.facebook.presto.common.type.Type; import com.facebook.presto.testing.MaterializedResult; import com.google.common.collect.ImmutableMap; import org.intellij.lang.annotations.Language; import org.testng.annotations.Test; import java.io.File; import java.math.BigDecimal; import java.util.Optional; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.common.type.DecimalType.createDecimalType; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.google.common.math.DoubleMath.fuzzyEquals; import static java.util.Arrays.asList; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @SuppressWarnings("UnknownLanguage") public class TestHiveScalarFunctions extends AbstractTestHiveFunctions { private static final String FUNCTION_PREFIX = "hive.default."; private static final String TABLE_NAME = "memory.default.function_testing"; private static final Type INTEGER_ARRAY = new ArrayType(INTEGER); private static final Type VARCHAR_ARRAY = new ArrayType(VARCHAR); @Override protected Optional<File> getInitScript() { return Optional.of(new File("src/test/sql/function-testing.sql")); } @Test public void genericFunction() { check(select("isnull", "null"), BOOLEAN, true); check(select("isnull", "1"), BOOLEAN, false); check(selectF("isnull", "c_varchar_null"), BOOLEAN, true); check(select("isnotnull", "1"), BOOLEAN, true); check(select("isnotnull", "null"), BOOLEAN, false); check(selectF("isnotnull", "c_varchar_null"), BOOLEAN, false); check(select("nvl", "null", "'2'"), VARCHAR, "2"); check(selectF("nvl", "c_varchar_null", "'2'"), VARCHAR, "2"); // Primitive numbers check(selectF("abs", "c_bigint"), BIGINT, 1L); check(selectF("abs", "c_integer"), INTEGER, 1); check(selectF("abs", "c_smallint"), INTEGER, 1); check(selectF("abs", "c_tinyint"), INTEGER, 1); check(selectF("abs", "c_decimal_52"), createDecimalType(5, 2), BigDecimal.valueOf(12345, 2)); check(selectF("abs", "c_real"), DOUBLE, 123.45f); check(selectF("abs", "c_double"), DOUBLE, 123.45); // Primitive string check(selectF("upper", "c_varchar"), VARCHAR, "VARCHAR"); check(selectF("upper", "c_varchar_10"), VARCHAR, "VARCHAR10"); check(selectF("upper", "c_char_10"), VARCHAR, "CHAR10"); } @Test public void genericArrayFunction() { check(selectF("coalesce", "c_varchar_null", "c_varchar_a", "c_varchar_10"), VARCHAR, "a"); check(select("coalesce", "null", "10"), INTEGER, 10); check(select("size", "null"), INTEGER, -1); check(select("size", "array []"), INTEGER, 0); check(select("size", "array [1, 2]"), INTEGER, 2); check(select("size", "array [array [1, 2], null][1]"), INTEGER, 2); check(select("size", "array [array [1, 2], null][2]"), INTEGER, -1); check(select("array", "1", "2"), INTEGER_ARRAY, asList(1, 2)); check(select("array", "'1'", "'2'"), VARCHAR_ARRAY, asList("1", "2")); check(selectF("array", "c_varchar", "c_varchar_10"), VARCHAR_ARRAY, asList("varchar", "varchar10")); check(selectF("array_contains", "c_array_integer", "2"), BOOLEAN, true); check(selectF("array_contains", "c_array_integer", "4"), BOOLEAN, false); check(selectF("array_contains", "c_array_varchar", "cast('a' as VARCHAR)"), BOOLEAN, true); check(selectF("array_contains", "c_array_varchar", "c_varchar_a"), BOOLEAN, true); check(selectF("array_contains", "c_array_varchar", "c_varchar_z"), BOOLEAN, false); check(selectF("sort_array", "ARRAY ['b', 'd', 'c', 'a']"), VARCHAR_ARRAY, asList("a", "b", "c", "d")); check(selectF("sort_array", "ARRAY [2, 4, 3, 1]"), INTEGER_ARRAY, asList(1, 2, 3, 4)); check(select("split", "'oneAtwoBthree'", "'[ABC]'"), VARCHAR_ARRAY, asList("one", "two", "three")); check(select("concat", "'aa'", "'bb'"), VARCHAR, "aabb"); check(select("concat_ws", "'.'", "'www'", "ARRAY ['facebook', 'com']"), VARCHAR, "www.facebook.com"); check(select("elt", "1", "'face'", "'book'"), VARCHAR, "face"); check(select("index", "ARRAY ['face', 'book']", "1"), VARCHAR, "book"); check(selectF("index", "c_array_varchar", "1"), VARCHAR, "b"); } @Test public void genericDateTimeFunction() { check(selectF("add_months", "c_date", "1"), VARCHAR, "2020-05-28"); check(selectF("add_months", "c_timestamp", "1"), VARCHAR, "2020-05-28"); check(select("add_months", "'2009-08-31'", "1"), VARCHAR, "2009-09-30"); check(select("add_months", "'2009-08-31 12:01:05'", "1"), VARCHAR, "2009-09-30"); check(select("datediff", "'2009-07-30'", "'2009-07-31'"), INTEGER, -1); check(select("datediff", "'2009-07-30 12:01:05'", "'2009-07-31 12:01:05'"), INTEGER, -1); } @Test public void genericMapFunction() { check(selectF("map_values", "c_map_varchar_integer"), INTEGER_ARRAY, asList(1, 2, 3)); check(selectF("map_values", "c_map_varchar_varchar"), VARCHAR_ARRAY, asList("1", "2", "3")); check(selectF("index", "c_map_string_string", "cast('a' as varchar)"), VARCHAR, "1"); check(selectF("index", "c_map_varchar_integer", "'a'"), INTEGER, 1); check(selectF("index", "c_map_varchar_varchar", "'a'"), VARCHAR, "1"); check(select("str_to_map", "'a:1,b:2'"), typeOf("map(varchar,varchar)"), ImmutableMap.of("a", "1", "b", "2")); check(select("str_to_map", "'a=1;b=2'", "';'", "'='"), typeOf("map(varchar,varchar)"), ImmutableMap.of("a", "1", "b", "2")); check(select("struct", "'a'", "1"), typeOf("row(col1 varchar,col2 integer)"), asList("a", 1)); } public void check(@Language("SQL") String query, Type expectedType, Object expectedValue) { MaterializedResult result = client.execute(query).getResult(); assertEquals(result.getRowCount(), 1); assertEquals(result.getTypes().get(0), expectedType); Object actual = result.getMaterializedRows().get(0).getField(0); if (expectedType.equals(DOUBLE) || expectedType.equals(RealType.REAL)) { if (expectedValue == null) { assertNaN(actual); } else { assertTrue(fuzzyEquals(((Number) actual).doubleValue(), ((Number) expectedValue).doubleValue(), 0.000001)); } } else { assertEquals(actual, expectedValue); } } private Type typeOf(String signature) { return typeManager.getType(parseTypeSignature(signature)); } private static void assertNaN(Object o) { if (o instanceof Double) { assertEquals((Double) o, Double.NaN); } else if (o instanceof Float) { assertEquals((Float) o, Float.NaN); } else { fail("Unexpected " + o); } } private static String select(String function, String... args) { StringBuilder builder = new StringBuilder(); builder.append("SELECT ").append(FUNCTION_PREFIX).append(function); builder.append("("); if (args != null) { builder.append(String.join(", ", args)); } builder.append(")"); return builder.toString(); } private static String selectF(String function, String... args) { StringBuilder builder = new StringBuilder(); builder.append("SELECT ").append(FUNCTION_PREFIX).append(function); builder.append("("); if (args != null) { builder.append(String.join(", ", args)); } builder.append(")").append(" FROM ").append(TABLE_NAME); return builder.toString(); } }
package de.jpaw.bonaparte.core; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.function.LongFunction; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.jpaw.bonaparte.pojos.meta.AlphanumericElementaryDataItem; import de.jpaw.bonaparte.pojos.meta.AlphanumericEnumSetDataItem; import de.jpaw.bonaparte.pojos.meta.BasicNumericElementaryDataItem; import de.jpaw.bonaparte.pojos.meta.BinaryElementaryDataItem; import de.jpaw.bonaparte.pojos.meta.ClassDefinition; import de.jpaw.bonaparte.pojos.meta.EnumDataItem; import de.jpaw.bonaparte.pojos.meta.EnumDefinition; import de.jpaw.bonaparte.pojos.meta.FieldDefinition; import de.jpaw.bonaparte.pojos.meta.MiscElementaryDataItem; import de.jpaw.bonaparte.pojos.meta.NumericElementaryDataItem; import de.jpaw.bonaparte.pojos.meta.NumericEnumSetDataItem; import de.jpaw.bonaparte.pojos.meta.ObjectReference; import de.jpaw.bonaparte.pojos.meta.TemporalElementaryDataItem; import de.jpaw.bonaparte.pojos.meta.XEnumDataItem; import de.jpaw.bonaparte.pojos.meta.XEnumSetDataItem; import de.jpaw.bonaparte.util.BigDecimalTools; import de.jpaw.enums.AbstractXEnumBase; import de.jpaw.enums.XEnumFactory; import de.jpaw.fixedpoint.FixedPointBase; import de.jpaw.util.ByteArray; import de.jpaw.util.MapIterator; // this parser will accept a subset of all possible convertable input types // the following types can be assumed to be accepted: // - the desired type itself // - a string // - the possible types created by the JsonParser for input originating from the corresponding type public class MapParser extends AbstractMessageParser<MessageParserException> implements MessageParser<MessageParserException> { private static final Logger LOGGER = LoggerFactory.getLogger(MapParser.class); private final Map<String, Object> map; private final boolean readEnumOrdinals; // false: use name, true: return ordinal for non tokenizable enums private final boolean readEnumTokens; // false: use name, true: return token for tokenizable enums / xenums private Iterator<Object> iter = null; private String currentClass = "N/A"; protected final boolean instantInMillis; protected final StringParserUtil spu; protected MessageParserException err(int errno, FieldDefinition di) { return new MessageParserException(errno, di.getName(), -1, currentClass); } public MapParser(Map<String, Object> map, boolean instantInMillis) { this(map, instantInMillis, true, true); } public MapParser(Map<String, Object> map, boolean instantInMillis, boolean readEnumOrdinals, boolean readEnumTokens) { this.map = map; // currentClass = map.get(MimeTypes.JSON_FIELD_PQON); this.instantInMillis = instantInMillis; this.readEnumOrdinals = readEnumOrdinals; this.readEnumTokens = readEnumTokens; this.spu = new StringParserUtil(new ParsePositionProvider() { @Override public int getParsePosition() { return -1; } @Override public String getCurrentClassName() { return currentClass; } }, instantInMillis); } // populate an existing object from a provided map public static void populateFrom(BonaPortable obj, Map<String, Object> map) throws MessageParserException { obj.deserialize(new MapParser(map, false)); } public static BonaPortable allocObject(Map<String, Object> map, ObjectReference di) throws MessageParserException { final ClassDefinition lowerBound = di.getLowerBound(); // create the object. Determine the type by the object reference, if that defines no subclassing // otherwise, check for special fields like $PQON (partially qualified name), and @type (fully qualified name) if (di.getAllowSubclasses() == false) { // no parameter required. determine by reference if (lowerBound == null) throw new MessageParserException(MessageParserException.JSON_BAD_OBJECTREF); return BonaPortableFactory.createObject(di.getLowerBound().getName()); // OK } // variable contents. see if we got a partially qualified name Object pqon1 = map.get(MimeTypes.JSON_FIELD_PQON); if (pqon1 != null && pqon1 instanceof String) { // lucky day, we got the partially qualified name return BonaPortableFactory.createObject((String)pqon1); } Object pqon2 = map.get(MimeTypes.JSON_FIELD_FQON); if (pqon2 != null && pqon2 instanceof String) { // also lucky, we got a fully qualified name return BonaPortableFactory.createObjectByFqon((String)pqon2); } // fallback: use the lower bound of di, if provided if (lowerBound == null) { // also no lower bound? Cannot work around that! throw new MessageParserException(MessageParserException.JSON_NO_PQON, di.getName(), -1, null); } if (LOGGER.isTraceEnabled()) { // output the map we got LOGGER.trace("Cannot convert Map to BonaPortable, Map dump is"); for (Map.Entry<String, Object> me : map.entrySet()) LOGGER.trace(" \"{}\": {}", me.getKey(), me.getValue() == null ? "null" : me.getValue().toString()); } // severe issue if the base class is abstract if (lowerBound.getIsAbstract()) { LOGGER.warn("Parsed object cannot be determined, no type information provided and base object is abstract. {}: ({}...)", di.getName(), lowerBound.getName()); throw new MessageParserException(MessageParserException.JSON_NO_PQON, di.getName(), -1, null); } // issue a warning, at least, and use the base class LOGGER.warn("Parsed object cannot be determined uniquely, no type information provided and subclasses allowed for {}: ({}...)", di.getName(), lowerBound.getName()); return BonaPortableFactory.createObject(lowerBound.getName()); } // convert a map to BonaPortable, read class info from the Map ($PQON entries) public static BonaPortable asBonaPortable(Map<String, Object> map, ObjectReference di) throws MessageParserException { BonaPortable obj = allocObject(map, di); populateFrom(obj, map); return obj; } private Object getNext(FieldDefinition di) { return (iter != null) ? iter.next() : map.get(di.getName()); } private Object get(FieldDefinition di) throws MessageParserException { Object z = getNext(di); if (z == null && di.getIsRequired()) throw err(MessageParserException.ILLEGAL_EXPLICIT_NULL, di); return z; } @Override public MessageParserException enumExceptionConverter(IllegalArgumentException e) throws MessageParserException { return new MessageParserException(MessageParserException.INVALID_ENUM_TOKEN, e.getMessage(), -1, currentClass); } @Override public MessageParserException customExceptionConverter(String msg, Exception e) throws MessageParserException { return new MessageParserException(MessageParserException.CUSTOM_OBJECT_EXCEPTION, e != null ? msg + e.toString() : msg, -1, currentClass); } @Override public void setClassName(String newClassName) { currentClass = newClassName; } @Override public Character readCharacter(MiscElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Character) return (Character)z; // must be string of length 1 otherwise if (z instanceof String) { return spu.readCharacter(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public UUID readUUID(MiscElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof UUID) return (UUID)z; if (z instanceof String) { return spu.readUUID(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Boolean readBoolean(MiscElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Boolean) return (Boolean)z; if (z instanceof String) { return spu.readBoolean(di, (String)z); } if (z instanceof Number) { return ((Number)z).doubleValue() == 0.0 ? Boolean.TRUE : Boolean.FALSE; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Double readDouble(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { return Double.valueOf(((Number)z).doubleValue()); } if (z instanceof String) { return Double.valueOf(spu.readPrimitiveDouble(di, (String)z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Float readFloat(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { return Float.valueOf(((Number)z).floatValue()); } if (z instanceof String) { return Float.valueOf(spu.readPrimitiveFloat(di, (String)z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Long readLong(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { return Long.valueOf(((Number)z).longValue()); } if (z instanceof String) { return Long.valueOf(spu.readPrimitiveLong(di, (String)z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Integer readInteger(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { return Integer.valueOf(((Number)z).intValue()); } if (z instanceof String) { return Integer.valueOf(spu.readPrimitiveInteger(di, (String)z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Short readShort(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { return Short.valueOf(((Number)z).shortValue()); } if (z instanceof String) { return Short.valueOf(spu.readPrimitiveShort(di, (String)z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Byte readByte(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { return Byte.valueOf(((Number)z).byteValue()); } if (z instanceof String) { return Byte.valueOf(spu.readPrimitiveByte(di, (String)z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public BigInteger readBigInteger(BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { if (z instanceof BigInteger) // todo: check scale? return (BigInteger)z; if (z instanceof Integer) return BigInteger.valueOf(((Integer)z).intValue()); if (z instanceof Long) return BigInteger.valueOf(((Long)z).longValue()); throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } if (z instanceof String) { return spu.readBigInteger(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public BigDecimal readBigDecimal(NumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { if (z instanceof BigDecimal) // todo: check scale? return (BigDecimal)z; if (z instanceof FixedPointBase) return ((FixedPointBase)z).toBigDecimal(); if (z instanceof Integer) return BigDecimal.valueOf(((Integer)z).intValue()); if (z instanceof Long) return BigDecimal.valueOf(((Long)z).longValue()); if (z instanceof Double) return BigDecimal.valueOf(((Double)z).doubleValue()); throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } if (z instanceof String) { return spu.readBigDecimal(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public <F extends FixedPointBase<F>> F readFixedPoint(BasicNumericElementaryDataItem di, LongFunction<F> factory) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Number) { long mantissa; if (z instanceof FixedPointBase) { FixedPointBase x = (FixedPointBase)z; if (x.scale() == di.getDecimalDigits() && x.isFixedScale()) { // this must be the same class - return as is return (F)x; } else { // is fixed point already, but with wrong scale mantissa = FixedPointBase.mantissaFor(x.getMantissa(), x.scale(), di.getDecimalDigits(), di.getRounding()); } } if (z instanceof BigDecimal) { final BigDecimal bd = (BigDecimal)z; mantissa = FixedPointBase.mantissaFor(bd.unscaledValue().longValue(), bd.scale(), di.getDecimalDigits(), di.getRounding()); } else if (z instanceof Integer) { mantissa = FixedPointBase.mantissaFor(((Integer)z).longValue(), 0, di.getDecimalDigits(), false); } else if (z instanceof Long) { mantissa = FixedPointBase.mantissaFor(((Long)z).longValue(), 0, di.getDecimalDigits(), false); } else { // anything else convert via double mantissa = FixedPointBase.mantissaFor(((Number)z).doubleValue(), di.getDecimalDigits()); } return BigDecimalTools.check(factory.apply(mantissa), di, -1, currentClass); } if (z instanceof String) { return BigDecimalTools.check(factory.apply(FixedPointBase.mantissaFor((String)z, di.getDecimalDigits())), di, -1, currentClass); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public String readAscii(AlphanumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof String) { return spu.readAscii(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public String readString(AlphanumericElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof String) { return spu.readString(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public ByteArray readByteArray(BinaryElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof ByteArray) { final ByteArray zz = (ByteArray)z; if (zz.length() > di.getLength()) throw err(MessageParserException.BINARY_TOO_LONG, di); return zz; } if (z instanceof byte []) { final byte [] zz = (byte [])z; if (zz.length > di.getLength()) throw err(MessageParserException.BINARY_TOO_LONG, di); return zz.length == 0 ? ByteArray.ZERO_BYTE_ARRAY : new ByteArray(zz); } if (z instanceof String) { return spu.readByteArray(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public byte[] readRaw(BinaryElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof ByteArray) { final ByteArray zz = (ByteArray)z; if (zz.length() > di.getLength()) throw err(MessageParserException.BINARY_TOO_LONG, di); return zz.getBytes(); } if (z instanceof byte []) { final byte [] zz = (byte [])z; if (zz.length > di.getLength()) throw err(MessageParserException.BINARY_TOO_LONG, di); return zz; } if (z instanceof String) { return spu.readRaw(di, (String)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Instant readInstant(TemporalElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Instant) { return (Instant)z; } if (z instanceof String) { return spu.readInstant(di, (String)z); // assumes precision = 1 second, with fractionals if ms } if (z instanceof Number) { // convert number of seconds to Instant return Instant.ofEpochMilli((long)(((Number)z).doubleValue() * 1000.0)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public LocalDate readDay(TemporalElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof String) { // cannot use spu, use JSON instead of Bonaparte formatting try { return LocalDate.parse((String)z); } catch (IllegalArgumentException e) { throw err(MessageParserException.ILLEGAL_TIME, di); } } if (z instanceof LocalDate) { return (LocalDate)z; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public LocalTime readTime(TemporalElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof String) { // cannot use spu, use JSON instead of Bonaparte formatting try { //return LocalTime.parse((String)z, di.getFractionalSeconds() > 0 ? ISODateTimeFormat.time() : ISODateTimeFormat.timeNoMillis()); return LocalTime.parse((String)z); // a more flexible parser } catch (IllegalArgumentException e) { throw err(MessageParserException.ILLEGAL_TIME, di); } } if (z instanceof LocalTime) { return (LocalTime)z; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public LocalDateTime readDayTime(TemporalElementaryDataItem di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof String) { // cannot use spu, use JSON instead of Bonaparte formatting try { // return LocalDateTime.parse((String)z, di.getFractionalSeconds() > 0 ? ISODateTimeFormat.dateTime() : ISODateTimeFormat.dateTimeNoMillis()); return LocalDateTime.parse((String)z); // a more flexible parser } catch (IllegalArgumentException e) { throw err(MessageParserException.ILLEGAL_TIME, di); } } if (z instanceof LocalDateTime) { return (LocalDateTime)z; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public <R extends BonaPortable> R readObject(ObjectReference di, Class<R> type) throws MessageParserException { // read of a nested object => uses a separate map! Object z = get(di); if (z == null) return null; BonaCustom obj; if (z instanceof Map<?,?>) { // recursive invocation. This creates a new instance of MapParser, with same settings // an alternative implementation could remove the "final" qualifier from map, push it, and continue with the same parser instance Map subMap = (Map<String, Object>)z; BonaPortable subObj = allocObject(subMap, di); subObj.deserialize(new MapParser(subMap, instantInMillis, readEnumOrdinals, readEnumTokens)); obj = subObj; } else if (z instanceof BonaCustom) { obj = (BonaCustom)z; } else { throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } if (obj.getClass().equals(type)) return (R)obj; if (!di.getAllowSubclasses() && !type.isAssignableFrom(obj.getClass())) throw new MessageParserException(MessageParserException.BAD_CLASS, String.format("(got %s, expected %s or subclass for %s)", obj.getClass().getSimpleName(), type.getSimpleName(), di.getName()), -1, currentClass); return (R)obj; } @Override public Map<String, Object> readJson(ObjectReference di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof Map<?,?>) { return (Map<String, Object>)z; // no check possible due to Java type erasure } // reverse mapping: BonaPortable => Map<>. It would be weird to encounter here, but hey.... if (z instanceof BonaCustom) { return MapComposer.marshal((BonaCustom)z); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public List<Object> readArray(ObjectReference di) throws MessageParserException { Object z = get(di); if (z == null) return null; if (z instanceof List<?>) { return (List<Object>)z; // no check possible due to Java type erasure } if (z instanceof Object []) { return new ArrayList<Object>(Arrays.asList((Object [])z)); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public Object readElement(ObjectReference di) throws MessageParserException { return get(di); } @Override public int parseMapStart(FieldDefinition di) throws MessageParserException { if (iter != null) throw new RuntimeException("Nested collection should not happen, but occurred for Map " + currentClass + "." + di.getName()); Object z = getNext(di); if (z == null) { if (di.getIsAggregateRequired()) throw err(MessageParserException.NULL_COLLECTION_NOT_ALLOWED, di); return -1; } if (z instanceof Map<?,?>) { Map<Object,Object> m = (Map<Object,Object>)z; iter = new MapIterator<Object>(m); return m.size(); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public int parseArrayStart(FieldDefinition di, int sizeOfElement) throws MessageParserException { if (iter != null) throw new RuntimeException("Nested collection should not happen, but occurred for Collection " + currentClass + "." + di.getName()); Object z = getNext(di); if (z == null) { if (di.getIsAggregateRequired()) throw err(MessageParserException.NULL_COLLECTION_NOT_ALLOWED, di); return -1; } if (z instanceof List<?>) { List<Object> l = (List<Object>)z; iter = l.iterator(); return l.size(); } if (z instanceof Set<?>) { Set<Object> s = (Set<Object>)z; iter = s.iterator(); return s.size(); } if (z instanceof Object []) { Object [] a = (Object [])z; iter = Arrays.asList(a).iterator(); return a.length; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } @Override public void parseArrayEnd() throws MessageParserException { if (iter == null) throw new RuntimeException("Cannot end collection when none has been started."); if (iter.hasNext()) throw new RuntimeException("Should not end collection when iterator has not been exhausted."); iter = null; } @Override public BonaPortable readRecord() throws MessageParserException { BonaPortable obj = allocObject(map, StaticMeta.OUTER_BONAPORTABLE); obj.deserialize(this); return obj; } @Override public List<BonaPortable> readTransmission() throws MessageParserException { throw new UnsupportedOperationException(); } @Override public void eatParentSeparator() throws MessageParserException { } @Override public <T extends AbstractXEnumBase<T>> T readXEnum(XEnumDataItem di, XEnumFactory<T> factory) throws MessageParserException { Object z = getNext(di); if (z == null) { T result = factory.getNullToken(); if (result == null && di.getIsRequired()) throw err(MessageParserException.EMPTY_BUT_REQUIRED_FIELD, di); return result; } if (z instanceof String) { final T value = readEnumTokens ? factory.getByToken((String)z) : factory.getByName((String)z); if (value == null) throw err(MessageParserException.INVALID_ENUM_TOKEN, di); return value; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } // special handling of enums: access the original name, not the one with $token suffix: take care when di and when edi is used! @Override public Integer readEnum(EnumDataItem edi, BasicNumericElementaryDataItem di) throws MessageParserException { Object z = get(edi); if (z == null) return null; if (z instanceof Number) { return Integer.valueOf(((Number)z).intValue()); } if (z instanceof String) { if (readEnumOrdinals) { return Integer.valueOf(spu.readPrimitiveInteger(di, (String)z)); } // expect a name, and map that to the ordinal int ordinal = edi.getBaseEnum().getIds().indexOf(z); if (ordinal < 0) { throw err(MessageParserException.INVALID_ENUM_NAME, di); } return ordinal; } throw err(MessageParserException.UNSUPPORTED_CONVERSION, edi); } // special handling of enums: access the original name, not the one with $token suffix @Override public String readEnum(EnumDataItem edi, AlphanumericElementaryDataItem di) throws MessageParserException { Object z = get(edi); if (z == null) return null; if (z instanceof String) { if (readEnumTokens) { return spu.readString(di, (String)z); } // expect a name, and map it to the token int ordinal = edi.getBaseEnum().getIds().indexOf(z); if (ordinal < 0) { throw err(MessageParserException.INVALID_ENUM_NAME, di); } // convert the name into a token return edi.getBaseEnum().getTokens().get(ordinal); } throw err(MessageParserException.UNSUPPORTED_CONVERSION, edi); } // enumset conversions protected String mapEnumTokens(FieldDefinition di, EnumDefinition edi) { final Collection<?> values = getCollection(di); if (values == null) return null; final ArrayList<String> tokens = new ArrayList<>(values.size()); List<String> instances = edi.getIds(); for (Object v: values) { int ordinal = instances.indexOf(v); if (ordinal < 0) { throw err(MessageParserException.INVALID_ENUM_NAME, di); } tokens.add(edi.getTokens().get(ordinal)); } Collections.sort(tokens); StringBuilder buff = new StringBuilder(tokens.size()); for (String s: tokens) { buff.append(s); } return buff.toString(); } @Override public String readString4Xenumset(XEnumSetDataItem di) throws MessageParserException { if (readEnumTokens) { return readString(di); } else { // compose the set // read instance names and map to tokens // FIXME: currently maps values of the base enum only, must obtain dynamically collected enums EnumDefinition edi = di.getBaseXEnumset().getBaseXEnum().getBaseEnum(); return mapEnumTokens(di, edi); } } @Override public String readString4EnumSet(AlphanumericEnumSetDataItem di) throws MessageParserException { if (readEnumTokens) { return readString(di); } else { // compose the set // read instance names and map to tokens EnumDefinition edi = di.getBaseEnumset().getBaseEnum(); return mapEnumTokens(di, edi); } } protected Collection<?> getCollection(FieldDefinition di) { Object enumset = get(di); if (enumset == null) return null; if (!(enumset instanceof Collection)) { throw err(MessageParserException.UNSUPPORTED_CONVERSION, di); } return (Collection<?>)enumset; } protected long mapToBitmap(NumericEnumSetDataItem di, Collection<?> values) { long bitmap = 0L; List<String> instances = di.getBaseEnumset().getBaseEnum().getIds(); for (Object v: values) { int ordinal = instances.indexOf(v); if (ordinal < 0) { throw err(MessageParserException.INVALID_ENUM_NAME, di); } bitmap |= (1L << ordinal); } return bitmap; } @Override public Long readLong4EnumSet(NumericEnumSetDataItem di) throws MessageParserException { if (readEnumOrdinals) { return readLong(di); } else { // read instance names and map to ordinals final Collection<?> values = getCollection(di); if (values == null) return null; return Long.valueOf(mapToBitmap(di, values)); } } @Override public Integer readInteger4EnumSet(NumericEnumSetDataItem di) throws MessageParserException { if (readEnumOrdinals) { return readInteger(di); } else { // read instance names and map to ordinals final Collection<?> values = getCollection(di); if (values == null) return null; return Integer.valueOf((int) mapToBitmap(di, values)); } } @Override public Short readShort4EnumSet(NumericEnumSetDataItem di) throws MessageParserException { if (readEnumOrdinals) { return readShort(di); } else { // read instance names and map to ordinals final Collection<?> values = getCollection(di); if (values == null) return null; return Short.valueOf((short) mapToBitmap(di, values)); } } @Override public Byte readByte4EnumSet(NumericEnumSetDataItem di) throws MessageParserException { if (readEnumOrdinals) { return readByte(di); } else { // read instance names and map to ordinals final Collection<?> values = getCollection(di); if (values == null) return null; return Byte.valueOf((byte) mapToBitmap(di, values)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.server.core.schema; import static org.apache.directory.server.core.integ.IntegrationUtils.getRootContext; import static org.apache.directory.server.core.integ.IntegrationUtils.getSchemaContext; import static org.apache.directory.server.core.integ.IntegrationUtils.getSystemContext; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SchemaViolationException; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.exception.LdapOtherException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.api.ldap.model.schema.parsers.AttributeTypeDescriptionSchemaParser; import org.apache.directory.api.ldap.util.JndiUtils; import org.apache.directory.server.core.annotations.ApplyLdifs; import org.apache.directory.server.core.annotations.CreateDS; import org.apache.directory.server.core.integ.AbstractLdapTestUnit; import org.apache.directory.server.core.integ.FrameworkRunner; import org.junit.Test; import org.junit.runner.RunWith; /** * Test cases for the schema getService(). This is for * <a href="http://issues.apache.org/jira/browse/DIREVE-276">DIREVE-276</a>. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ @ApplyLdifs( { // Entry # 1 "dn: cn=person0,ou=system", "objectClass: person", "cn: person0", "sn: sn_person0\n", // Entry # 2 "dn: cn=person1,ou=system", "objectClass: organizationalPerson", "cn: person1", "sn: sn_person1", "seealso: cn=Good One,ou=people,o=sevenSeas", //"seealso:: Y249QmFkIEXDqWvDoCxvdT1wZW9wbGUsbz1zZXZlblNlYXM=\n", // Entry # 3 "dn: cn=person2,ou=system", "objectClass: inetOrgPerson", "cn: person2", "sn: sn_person2" }) @RunWith(FrameworkRunner.class) @CreateDS(name = "SchemaServiceIT") public class SchemaServiceIT extends AbstractLdapTestUnit { /** * For <a href="https://issues.apache.org/jira/browse/DIRSERVER-925">DIRSERVER-925</a>. * * @throws NamingException on error */ @Test public void testNoStructuralObjectClass() throws Exception { Attributes attrs = new BasicAttributes( "objectClass", "top", true ); attrs.get( "objectClass" ).add( "uidObject" ); attrs.put( "uid", "invalid" ); try { getSystemContext( getService() ).createSubcontext( "uid=invalid", attrs ); } catch ( SchemaViolationException e ) { } } /** * For <a href="https://issues.apache.org/jira/browse/DIRSERVER-925">DIRSERVER-925</a>. * * @throws NamingException on error */ @Test public void testMultipleStructuralObjectClasses() throws Exception { Attributes attrs = new BasicAttributes( "objectClass", "top", true ); attrs.get( "objectClass" ).add( "organizationalUnit" ); attrs.get( "objectClass" ).add( "person" ); attrs.put( "ou", "comedy" ); attrs.put( "cn", "Jack Black" ); attrs.put( "sn", "Black" ); try { getSystemContext( getService() ).createSubcontext( "cn=Jack Black", attrs ); } catch ( SchemaViolationException e ) { } } /** * For <a href="https://issues.apache.org/jira/browse/DIRSERVER-904">DIRSERVER-904</a>. * * @throws NamingException on error */ @Test public void testAddingTwoDifferentEntitiesWithSameOid() throws Exception { String numberOfGunsAttrLdif = "dn: m-oid=1.3.6.1.4.1.18060.0.4.1.2.999,ou=attributeTypes,cn=other,ou=schema\n" + "m-usage: USER_APPLICATIONS\n" + "m-equality: integerOrderingMatch\n" + "objectClass: metaAttributeType\n" + "objectClass: metaTop\n" + "objectClass: top\n" + "m-name: numberOfGuns\n" + "m-oid: 1.3.6.1.4.1.18060.0.4.1.2.999\n" + "m-singleValue: TRUE\n" + "m-description: Number of guns of a ship\n" + "m-collective: FALSE\n" + "m-obsolete: FALSE\n" + "m-noUserModification: FALSE\n" + "m-syntax: 1.3.6.1.4.1.1466.115.121.1.27\n"; String shipOCLdif = "dn: m-oid=1.3.6.1.4.1.18060.0.4.1.2.999,ou=objectClasses,cn=other,ou=schema\n" + "objectClass: top\n" + "objectClass: metaTop\n" + "objectClass: metaObjectclass\n" + "m-supObjectClass: top\n" + "m-oid: 1.3.6.1.4.1.18060.0.4.1.2.999\n" + "m-name: ship\n" + "m-must: cn\n" + "m-may: numberOfGuns\n" + "m-may: description\n" + "m-typeObjectClass: STRUCTURAL\n" + "m-obsolete: FALSE\n" + "m-description: A ship\n"; StringReader in = new StringReader( numberOfGunsAttrLdif + "\n\n" + shipOCLdif ); LdifReader ldifReader = new LdifReader( in ); LdifEntry numberOfGunsAttrEntry = ldifReader.next(); LdifEntry shipOCEntry = ldifReader.next(); assertFalse( ldifReader.hasNext() ); ldifReader.close(); // should be fine with unique OID getService().getAdminSession().add( new DefaultEntry( getService().getSchemaManager(), numberOfGunsAttrEntry.getEntry() ) ); // should blow chuncks using same OID try { getService().getAdminSession().add( new DefaultEntry( getService().getSchemaManager(), shipOCEntry.getEntry() ) ); fail( "Should not be possible to create two schema entities with the same OID." ); } catch ( LdapOtherException e ) { assertTrue( true ); } } /** * Test that we have all the needed ObjectClasses * * @throws NamingException on error */ @Test public void testFillInObjectClasses() throws Exception { LdapContext sysRoot = getSystemContext( getService() ); Attribute ocs = sysRoot.getAttributes( "cn=person0" ).get( "objectClass" ); assertEquals( 2, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); ocs = sysRoot.getAttributes( "cn=person1" ).get( "objectClass" ); assertEquals( 3, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); ocs = sysRoot.getAttributes( "cn=person2" ).get( "objectClass" ); assertEquals( 4, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); assertTrue( ocs.contains( "inetOrgPerson" ) ); } /** * Search all the entries with a 'person' ObjectClass, or an ObjectClass * inheriting from 'person' * * @throws NamingException on error */ @Test public void testSearchForPerson() throws Exception { LdapContext sysRoot = getSystemContext( getService() ); SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> persons = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = sysRoot.search( "", "(objectClass=*person)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); persons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 4, persons.size() ); Attributes person = persons.get( "cn=person0,ou=system" ); assertNotNull( person ); Attribute ocs = person.get( "objectClass" ); assertEquals( 2, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); person = persons.get( "cn=person1,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertEquals( 3, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); person = persons.get( "cn=person2,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertEquals( 4, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); assertTrue( ocs.contains( "inetOrgPerson" ) ); } @Test public void testSearchForOrgPerson() throws Exception { LdapContext sysRoot = getSystemContext( getService() ); SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> orgPersons = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = sysRoot.search( "", "(objectClass=organizationalPerson)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); orgPersons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 3, orgPersons.size() ); Attributes orgPerson = orgPersons.get( "cn=person1,ou=system" ); assertNotNull( orgPerson ); Attribute ocs = orgPerson.get( "objectClass" ); assertEquals( 3, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); orgPerson = orgPersons.get( "cn=person2,ou=system" ); assertNotNull( orgPerson ); ocs = orgPerson.get( "objectClass" ); assertEquals( 4, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); assertTrue( ocs.contains( "inetOrgPerson" ) ); } @Test public void testSearchForInetOrgPerson() throws Exception { LdapContext sysRoot = getSystemContext( getService() ); SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> inetOrgPersons = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = sysRoot.search( "", "(objectClass=inetOrgPerson)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); inetOrgPersons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 2, inetOrgPersons.size() ); Attributes inetOrgPerson = inetOrgPersons.get( "cn=person2,ou=system" ); assertNotNull( inetOrgPerson ); Attribute ocs = inetOrgPerson.get( "objectClass" ); assertEquals( 4, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); assertTrue( ocs.contains( "inetOrgPerson" ) ); } @Test public void testSearchForSubSchemaSubEntryUserAttrsOnly() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ).search( "cn=schema", "(objectClass=*)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have only one entry in the result assertEquals( 1, subSchemaEntry.size() ); // It should be the normalized form of cn=schema Attributes attrs = subSchemaEntry.get( "cn=schema" ); assertNotNull( attrs ); // We should have 2 attributes in the result : // - attributeTypes // - cn // - objectClass assertEquals( 2, attrs.size() ); assertNotNull( attrs.get( "cn" ) ); assertNotNull( attrs.get( "objectClass" ) ); } @Test public void testSearchForSubSchemaSubEntryAllAttrs() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "*", "+" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ).search( "cn=schema", "(objectClass=*)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have only one entry in the result assertEquals( 1, subSchemaEntry.size() ); // It should be the normalized form of cn=schema Attributes attrs = subSchemaEntry.get( "cn=schema" ); assertNotNull( attrs ); // We should not have any NameForms assertNull( attrs.get( "nameForms" ) ); } @Test public void testSearchForSubSchemaSubEntrySingleAttributeSelected() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "objectClasses" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(objectClass=*)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have only one entry in the result assertEquals( 1, subSchemaEntry.size() ); // It should be the normalized form of cn=schema Attributes attrs = subSchemaEntry.get( "cn=schema" ); assertNotNull( attrs ); // We should have 1 attribute in the result : // - nameForms assertEquals( 1, attrs.size() ); assertNull( attrs.get( "attributeTypes" ) ); assertNull( attrs.get( "cn" ) ); assertNull( attrs.get( "creatorsName" ) ); assertNull( attrs.get( "createTimestamp" ) ); assertNull( attrs.get( "dITContentRules" ) ); assertNull( attrs.get( "dITStructureRules" ) ); assertNull( attrs.get( "ldapSyntaxes" ) ); assertNull( attrs.get( "matchingRules" ) ); assertNull( attrs.get( "matchingRuleUse" ) ); assertNull( attrs.get( "modifiersName" ) ); assertNull( attrs.get( "modifyTimestamp" ) ); assertNotNull( attrs.get( "objectClasses" ) ); assertNull( attrs.get( "objectClass" ) ); assertNull( attrs.get( "nameForms" ) ); } /** * Test for DIRSERVER-1055. * Check if modifyTimestamp and createTimestamp are present in the search result, * if they are requested. */ @Test public void testSearchForSubSchemaSubEntryOperationalAttributesSelected() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "creatorsName", "createTimestamp", "modifiersName", "modifyTimestamp" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(objectClass=subschema)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have only one entry in the result assertEquals( 1, subSchemaEntry.size() ); // It should be the normalized form of cn=schema Attributes attrs = subSchemaEntry.get( "cn=schema" ); assertNotNull( attrs ); // We should have 4 attribute in the result : assertEquals( 4, attrs.size() ); assertNull( attrs.get( "attributeTypes" ) ); assertNull( attrs.get( "cn" ) ); assertNotNull( attrs.get( "creatorsName" ) ); assertNotNull( attrs.get( "createTimestamp" ) ); assertNull( attrs.get( "dITContentRules" ) ); assertNull( attrs.get( "dITStructureRules" ) ); assertNull( attrs.get( "ldapSyntaxes" ) ); assertNull( attrs.get( "matchingRules" ) ); assertNull( attrs.get( "matchingRuleUse" ) ); assertNotNull( attrs.get( "modifiersName" ) ); assertNotNull( attrs.get( "modifyTimestamp" ) ); assertNull( attrs.get( "nameForms" ) ); assertNull( attrs.get( "objectClass" ) ); assertNull( attrs.get( "objectClasses" ) ); } @Test public void testSearchForSubSchemaSubEntryBadFilter() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "+" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(objectClass=nothing)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have no entry in the result assertEquals( 0, subSchemaEntry.size() ); } @Test public void testSearchForSubSchemaSubEntryFilterEqualTop() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "*", "+" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(objectClass=top)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have only one entry in the result assertEquals( 1, subSchemaEntry.size() ); // It should be the normalized form of cn=schema Attributes attrs = subSchemaEntry.get( "cn=schema" ); assertNotNull( attrs ); // We should have 14 attributes in the result : assertEquals( 14, attrs.size() ); assertNotNull( attrs.get( "attributeTypes" ) ); assertNotNull( attrs.get( "cn" ) ); assertNotNull( attrs.get( "comparators" ) ); assertNotNull( attrs.get( "creatorsName" ) ); assertNotNull( attrs.get( "createTimestamp" ) ); assertNull( attrs.get( "dITContentRules" ) ); assertNull( attrs.get( "dITStructureRules" ) ); assertNotNull( attrs.get( "ldapSyntaxes" ) ); assertNotNull( attrs.get( "matchingRules" ) ); assertNull( attrs.get( "matchingRuleUse" ) ); assertNotNull( attrs.get( "modifiersName" ) ); assertNotNull( attrs.get( "modifyTimestamp" ) ); assertNull( attrs.get( "nameForms" ) ); assertNotNull( attrs.get( "normalizers" ) ); assertNotNull( attrs.get( "objectClass" ) ); assertNotNull( attrs.get( "objectClasses" ) ); assertNotNull( attrs.get( "subtreeSpecification" ) ); assertNotNull( attrs.get( "syntaxCheckers" ) ); } @Test public void testSearchForSubSchemaSubEntryFilterEqualSubSchema() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "*", "+" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(objectClass=subSchema)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have only one entry in the result assertEquals( 1, subSchemaEntry.size() ); // It should be the normalized form of cn=schema Attributes attrs = subSchemaEntry.get( "cn=schema" ); assertNotNull( attrs ); // We should have 14 attributes in the result : assertEquals( 14, attrs.size() ); assertNotNull( attrs.get( "attributeTypes" ) ); assertNotNull( attrs.get( "cn" ) ); assertNotNull( attrs.get( "subtreeSpecification" ) ); assertNotNull( attrs.get( "creatorsName" ) ); assertNotNull( attrs.get( "createTimestamp" ) ); assertNull( attrs.get( "dITContentRules" ) ); assertNull( attrs.get( "dITStructureRules" ) ); assertNotNull( attrs.get( "ldapSyntaxes" ) ); assertNotNull( attrs.get( "matchingRules" ) ); assertNull( attrs.get( "matchingRuleUse" ) ); assertNotNull( attrs.get( "modifiersName" ) ); assertNotNull( attrs.get( "modifyTimestamp" ) ); assertNull( attrs.get( "nameForms" ) ); assertNotNull( attrs.get( "objectClass" ) ); assertNotNull( attrs.get( "objectClasses" ) ); } @Test public void testSearchForSubSchemaSubEntryNotObjectScope() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); controls.setReturningAttributes( new String[] { "+" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(objectClass=nothing)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have no entry in the result assertEquals( 0, subSchemaEntry.size() ); } @Test public void testSearchForSubSchemaSubEntryComposedFilters() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); controls.setReturningAttributes( new String[] { "+" } ); Map<String, Attributes> subSchemaEntry = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getRootContext( getService() ) .search( "cn=schema", "(&(objectClass=*)(objectClass=top))", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); subSchemaEntry.put( result.getName(), result.getAttributes() ); } results.close(); // We should have no entry in the result assertEquals( 0, subSchemaEntry.size() ); } /** * Test for DIRSERVER-844: storing of base 64 encoded values into H-R attributes * * @throws NamingException on error */ @Test public void testSearchSeeAlso() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> persons = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = getSystemContext( getService() ) .search( "", "(seeAlso=cn=Good One,ou=people,o=sevenSeas)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); persons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 1, persons.size() ); Attributes person; Attribute ocs; person = persons.get( "cn=person1,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertEquals( 3, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); Attribute seeAlso = person.get( "seeAlso" ); assertTrue( seeAlso.contains( "cn=Good One,ou=people,o=sevenSeas" ) ); //assertTrue( seeAlso.contains( "cn=Bad E\u00e9k\u00e0,ou=people,o=sevenSeas" ) ); } /** * Doing a search with filtering attributes should work even if the attribute * is not valid * * @throws NamingException on error */ @Test public void testSearchForUnknownAttributes() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> persons = new HashMap<String, Attributes>(); controls.setReturningAttributes( new String[] { "9.9.9" } ); NamingEnumeration<SearchResult> results = getSystemContext( getService() ) .search( "", "(objectClass=person)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); persons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 4, persons.size() ); Attributes person; Attribute ocs; person = persons.get( "cn=person0,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); ocs = person.get( "9.9.9" ); assertNull( ocs ); person = persons.get( "cn=person1,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); person = persons.get( "cn=person2,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); } /** * Check that if we request a Attribute which is not an AttributeType, * we still get a result * * @throws NamingException on error */ @Test public void testSearchAttributesOIDObjectClass() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> persons = new HashMap<String, Attributes>(); controls.setReturningAttributes( new String[] { "2.5.6.6" } ); NamingEnumeration<SearchResult> results = getSystemContext( getService() ) .search( "", "(objectClass=person)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); persons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 4, persons.size() ); Attributes person; Attribute ocs; person = persons.get( "cn=person0,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); // We should not get this attribute (it's an ObjectClass) ocs = person.get( "2.5.6.6" ); assertNull( ocs ); person = persons.get( "cn=person1,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); person = persons.get( "cn=person2,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); } /** * Check that if we request a Attribute which is an ObjectClass. * * @throws NamingException on error */ @Test public void testSearchAttributesOIDObjectClassName() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> persons = new HashMap<String, Attributes>(); controls.setReturningAttributes( new String[] { "person" } ); NamingEnumeration<SearchResult> results = getSystemContext( getService() ) .search( "", "(objectClass=person)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); persons.put( result.getName(), result.getAttributes() ); } results.close(); // admin is extra assertEquals( 4, persons.size() ); Attributes person; Attribute ocs; person = persons.get( "cn=person0,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); // We should not get this attrinute (it's an ObjectClass) ocs = person.get( "2.5.4.46" ); assertNull( ocs ); person = persons.get( "cn=person1,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); person = persons.get( "cn=person2,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertNull( ocs ); } /** * Check that if we search for an attribute using its inherited * AttributeType (ie, looking for name instead of givenName, surname, * commonName), we find all the entries. * * @throws NamingException */ @Test public void testSearchForName() throws Exception { LdapContext sysRoot = getSystemContext( getService() ); SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); Map<String, Attributes> persons = new HashMap<String, Attributes>(); NamingEnumeration<SearchResult> results = sysRoot.search( "", "(name=person*)", controls ); while ( results.hasMore() ) { SearchResult result = results.next(); persons.put( result.getName(), result.getAttributes() ); } results.close(); assertEquals( 3, persons.size() ); Attributes person = persons.get( "cn=person0,ou=system" ); assertNotNull( person ); Attribute ocs = person.get( "objectClass" ); assertEquals( 2, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); person = persons.get( "cn=person1,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertEquals( 3, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); person = persons.get( "cn=person2,ou=system" ); assertNotNull( person ); ocs = person.get( "objectClass" ); assertEquals( 4, ocs.size() ); assertTrue( ocs.contains( "top" ) ); assertTrue( ocs.contains( "person" ) ); assertTrue( ocs.contains( "organizationalPerson" ) ); assertTrue( ocs.contains( "inetOrgPerson" ) ); } /** * Search all the entries with a 'metaTop' ObjectClass, or an ObjectClass * inheriting from 'metaTop' * * @throws NamingException on error */ @Test public void testSearchForMetaTop() throws Exception { LdapContext schemaRoot = getSchemaContext( getService() ); SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); NamingEnumeration<SearchResult> results = schemaRoot.search( "", "(objectClass=top)", controls ); assertTrue( "Expected some results", results.hasMore() ); results.close(); controls = new SearchControls(); controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); results = schemaRoot.search( "", "(objectClass=metaAttributeType)", controls ); assertTrue( "Expected some results", results.hasMore() ); results.close(); controls = new SearchControls(); controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); results = schemaRoot.search( "", "(objectClass=metaTop)", controls ); assertTrue( "Expected some results", results.hasMore() ); results.close(); } // ----------------------------------------------------------------------- // Private Utility Methods // ----------------------------------------------------------------------- private static final String SUBSCHEMA_SUBENTRY = "subschemaSubentry"; private static final AttributeTypeDescriptionSchemaParser ATTRIBUTE_TYPE_DESCRIPTION_SCHEMA_PARSER = new AttributeTypeDescriptionSchemaParser(); private void modify( int op, List<String> descriptions, String opAttr ) throws Exception { Dn dn = new Dn( getSubschemaSubentryDN() ); Attribute attr = new BasicAttribute( opAttr ); for ( String description : descriptions ) { attr.add( description ); } Attributes mods = new BasicAttributes( true ); mods.put( attr ); getRootContext( getService() ).modifyAttributes( JndiUtils.toName( dn ), op, mods ); } /** * Gets the subschemaSubentry attributes for the global schema. * * @return all operational attributes of the subschemaSubentry * @throws NamingException if there are problems accessing this entry */ private Attributes getSubschemaSubentryAttributes() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { "+", "*" } ); NamingEnumeration<SearchResult> results = getRootContext( getService() ).search( getSubschemaSubentryDN(), "(objectClass=*)", controls ); SearchResult result = results.next(); results.close(); return result.getAttributes(); } /** * Get's the subschemaSubentry attribute value from the rootDSE. * * @return the subschemaSubentry distinguished name * @throws NamingException if there are problems accessing the RootDSE */ private String getSubschemaSubentryDN() throws Exception { SearchControls controls = new SearchControls(); controls.setSearchScope( SearchControls.OBJECT_SCOPE ); controls.setReturningAttributes( new String[] { SUBSCHEMA_SUBENTRY } ); NamingEnumeration<SearchResult> results = getRootContext( getService() ).search( "", "(objectClass=*)", controls ); SearchResult result = results.next(); results.close(); Attribute subschemaSubentry = result.getAttributes().get( SUBSCHEMA_SUBENTRY ); return ( String ) subschemaSubentry.get(); } private void enableSchema( String schemaName ) throws Exception { // now enable the test schema ModificationItem[] mods = new ModificationItem[1]; Attribute attr = new BasicAttribute( "m-disabled", "FALSE" ); mods[0] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr ); getSchemaContext( getService() ).modifyAttributes( "cn=" + schemaName, mods ); } private void checkAttributeTypePresent( String oid, String schemaName, boolean isPresent ) throws Exception { // ------------------------------------------------------------------- // check first to see if it is present in the subschemaSubentry // ------------------------------------------------------------------- Attributes attrs = getSubschemaSubentryAttributes(); Attribute attrTypes = attrs.get( "attributeTypes" ); AttributeType attributeType = null; for ( int ii = 0; ii < attrTypes.size(); ii++ ) { String desc = ( String ) attrTypes.get( ii ); if ( desc.indexOf( oid ) != -1 ) { attributeType = ATTRIBUTE_TYPE_DESCRIPTION_SCHEMA_PARSER .parseAttributeTypeDescription( desc ); break; } } if ( isPresent ) { assertNotNull( attributeType ); assertEquals( oid, attributeType.getOid() ); } else { assertNull( attributeType ); } // ------------------------------------------------------------------- // check next to see if it is present in the schema partition // ------------------------------------------------------------------- attrs = null; if ( isPresent ) { attrs = getSchemaContext( getService() ).getAttributes( "m-oid=" + oid + ",ou=attributeTypes,cn=" + schemaName ); assertNotNull( attrs ); } else { //noinspection EmptyCatchBlock try { attrs = getSchemaContext( getService() ).getAttributes( "m-oid=" + oid + ",ou=attributeTypes,cn=" + schemaName ); fail( "should never get here" ); } catch ( NamingException e ) { } assertNull( attrs ); } // ------------------------------------------------------------------- // check to see if it is present in the attributeTypeRegistry // ------------------------------------------------------------------- if ( isPresent ) { assertTrue( getService().getSchemaManager().getAttributeTypeRegistry().contains( oid ) ); } else { assertFalse( getService().getSchemaManager().getAttributeTypeRegistry().contains( oid ) ); } } /** * Tests to see if an attributeType is persisted when added, then server * is shutdown, then restarted again. * * @throws Exception on error */ @Test public void testAddAttributeTypePersistence() throws Exception { try { enableSchema( "nis" ); List<String> descriptions = new ArrayList<String>(); // ------------------------------------------------------------------- // test successful add with everything // ------------------------------------------------------------------- descriptions.add( "( 1.3.6.1.4.1.18060.0.9.3.1.9" + " NAME 'ibm-imm' " + " DESC 'the actual block data being stored' " + " EQUALITY octetStringMatch " + " SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{32700} " + " SINGLE-VALUE " + " USAGE userApplications " + " X-SCHEMA 'nis' )" ); modify( DirContext.ADD_ATTRIBUTE, descriptions, "attributeTypes" ); checkAttributeTypePresent( "1.3.6.1.4.1.18060.0.9.3.1.9", "nis", true ); // sync operation happens anyway on shutdowns but just to make sure we can do it again getService().sync(); getService().shutdown(); getService().startup(); Attributes attrs = new BasicAttributes( true ); Attribute attr = new BasicAttribute( "objectClass" ); attr.add( "top" ); attr.add( "person" ); attr.add( "extensibleObject" ); attrs.put( attr ); attrs.put( "cn", "blah" ); attrs.put( "sn", "Blah" ); attrs.put( "ibm-imm", "test" ); getSystemContext( getService() ).createSubcontext( "cn=blah", attrs ); checkAttributeTypePresent( "1.3.6.1.4.1.18060.0.9.3.1.9", "nis", true ); } catch ( Exception e ) { throw e; } } }
package org.myrobotlab.framework.repo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.meta.abstracts.MetaData; // FIXME - 2 layer abstraction - because to generate build files and // other critical methods - they do not require actual "ivy" components // so these methods should be un-hindered by actual maven, gradle or ivy imports ! public class MavenWrapper extends Repo implements Serializable { private static final long serialVersionUID = 1L; String installDir = "install"; static String pomXmlTemplate = null; static MavenWrapper localInstance = null; static public Repo getTypeInstance() { if (localInstance == null) { init(); } return localInstance; } static private synchronized void init() { if (localInstance == null) { /* * ClassWorld classWorld = new ClassWorld(); ClassRealm classRealm = * (ClassRealm) Thread.currentThread().getContextClassLoader(); mavenCli = * new MavenCli(classRealm.getWorld()); */ // mavenCli = new MavenCli(); localInstance = new MavenWrapper(); pomXmlTemplate = FileIO.resourceToString("framework/pom.xml.template"); } } // FIXME - fix do createBuildFiles // FIXME - call external mvn since Embedded Maven is not documented and buggy @Override synchronized public void install(String location, String[] serviceTypes) { createBuildFiles(location, serviceTypes); log.error("TODO - implement dependency copy with ProcessBuilder & external mvn install"); boolean done = true; if (done) { return; } info("===== starting installation of %d services =====", serviceTypes.length); for (String serviceType : serviceTypes) { try { Set<ServiceDependency> unfulfilled = getUnfulfilledDependencies(serviceType); // FIXME - callback logging // directory to run localInstance over a default pom File f = new File(installDir); f.mkdirs(); for (ServiceDependency library : unfulfilled) { // mavenGenerateServiceInstallPom(); log.info("===== installing dependency {} =====", library); String installPom = null;// getArtifactInstallPom(library.getOrgId(), // library.getArtifactId(),library.getVersion()); installPom = installPom.replace("{{location}}", location); // search and replace - add File installPomDir = new File(location); installPomDir.mkdirs(); FileOutputStream fos = new FileOutputStream(installDir + File.separator + "pom.xml"); fos.write(installPom.getBytes()); fos.close(); // mavenCli.doMain(new String[] { "install" }, "install", System.out, // System.out); } } catch (Exception e) { // FIXME - add to errors !!! info("===== ERROR in installation of %s =====", serviceType); log.error("installServiceDir threw", e); // FIXME - callback error } info("===== finished installation of %s =====", serviceType); // save updated repo/library state save(); } } public String getRepositories() { StringBuilder ret = new StringBuilder(" <repositories>\n"); for (RemoteRepo repo : remotes) { StringBuilder sb = new StringBuilder(); sb.append(" <!-- " + repo.comment + " -->\n"); sb.append(" <repository>\n"); sb.append(" <id>" + repo.id + "</id>\n"); sb.append(" <name>" + repo.id + "</name>\n"); sb.append(" <url>" + repo.url + "</url>\n"); sb.append(" </repository>\n"); ret.append(sb); } ret.append(" </repositories>\n"); return ret.toString(); } public void createPom(String location, String[] serviceTypes) throws IOException { Map<String, String> snr = new HashMap<String, String>(); StringBuilder deps = new StringBuilder(); ServiceData sd = ServiceData.getLocalInstance(); snr.put("{{repositories}}", getRepositories()); deps.append("<dependencies>\n\n"); Set<String> listedDeps = new HashSet<String>(); for (String serviceType : serviceTypes) { MetaData service = ServiceData.getMetaData(serviceType); // FIXME - getUnFufilledDependencies ??? List<ServiceDependency> dependencies = service.getDependencies(); if (dependencies.size() == 0) { continue; } StringBuilder dep = new StringBuilder(); dep.append(String.format("<!-- %s begin -->\n", service.getSimpleName())); for (ServiceDependency dependency : dependencies) { String depKey = dependency.getOrgId() + "-" + dependency.getArtifactId() + "-" + dependency.getVersion(); if (listedDeps.contains(depKey)) { dep.append("<!-- Duplicate entry for " + depKey + " skipping -->\n"); continue; } if (dependency.getVersion() == null) { dep.append("<!-- skipping " + dependency.getOrgId() + " " + dependency.getArtifactId() + " " + depKey + " null version/latest -->\n"); continue; } listedDeps.add(depKey); dep.append(" <dependency>\n"); dep.append(String.format(" <groupId>%s</groupId>\n", dependency.getOrgId())); dep.append(String.format(" <artifactId>%s</artifactId>\n", dependency.getArtifactId())); // optional - means latest ??? dep.append(String.format(" <version>%s</version>\n", dependency.getVersion())); if (!service.includeServiceInOneJar()) { dep.append(" <scope>provided</scope>\n"); } if (dependency.getExt() != null) { dep.append(String.format(" <type>%s</type>\n", dependency.getExt())); } List<ServiceExclude> excludes = dependency.getExcludes(); // exclusions begin --- if (excludes != null & excludes.size() > 0) { StringBuilder ex = new StringBuilder(); ex.append(" <exclusions>\n"); for (ServiceExclude exclude : excludes) { ex.append(" <exclusion>\n"); ex.append(String.format(" <groupId>%s</groupId>\n", exclude.getOrgId())); ex.append(String.format(" <artifactId>%s</artifactId>\n", exclude.getArtifactId())); if (exclude.getVersion() != null) { ex.append(String.format(" <version>%s</version>\n", exclude.getVersion())); } if (exclude.getExt() != null) { ex.append(String.format(" <type>%s</type>\n", exclude.getExt())); } ex.append(" </exclusion>\n"); } ex.append(" </exclusions>\n"); dep.append(ex); } dep.append(" </dependency>\n"); // exclusions end --- } // for each dependency dep.append(String.format("<!-- %s end -->\n\n", service.getSimpleName())); if (dependencies.size() > 0) { deps.append(dep); } } // for each service deps.append(" </dependencies>\n"); snr.put("{{dependencies}}", deps.toString()); createFilteredFile(snr, location, "pom", "xml"); } /** * (non-Javadoc) * * @see org.myrobotlab.framework.repo.Repo#createBuildFiles(java.lang.String, * java.lang.String[]) */ public void createBuildFiles(String location, String[] serviceTypes) { try { location = createWorkDirectory(location); createPom(location, serviceTypes); } catch (Exception e) { log.error("could not generate build files", e); } } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); File cache = new File("./data/.myrobotlab/serviceData.json"); if (cache.exists()) { log.info("removing servicData.json cache"); cache.delete(); } Repo repo = Repo.getInstance("MavenWrapper"); String serviceType = "_TemplateService"; serviceType = null; long ts = System.currentTimeMillis(); // String dir = String.format("install.maven.%s.%d", serviceType, ts); String dir = "install.maven.update"; repo.createBuildFiles(dir, serviceType); // repo.install("install.dl4j.maven", "Deeplearning4j"); // repo.install("install.opencv.maven","OpenCV"); // repo.createBuildFiles(dir, "Arm"); // repo.createBuildFilesTo(dir); // repo.installTo(dir); // repo.install(); // repo.installEach(); <-- TODO - test log.info("done"); } catch (Exception e) { log.error(e.getMessage(), e); } } @Override public void installDependency(String location, ServiceDependency serviceTypes) { // TODO Auto-generated method stub } }
/* * Copyright 2012 Benjamin Fagin * * 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. * * * Read the included LICENSE.TXT for more information. */ package unquietcode.tools.closures; import unquietcode.tools.closures.view.ClosureView; import java.util.Iterator; import java.util.LinkedList; /** * @author Benjamin Fagin * @version 12-31-2010 * * * Chains are a series of linked ClosureView objects. Execution starts at the first and proceeds to the end. * Each closure is left in charge of how to handle the inputs and outputs. Because each closure outputs a single * object, arrays of objects can be returned, which will be fed to the next closure as varargs. Only the last closure * need return the 'correct' return type, as specified in the type parameter (optional, of course). * * All of the normal concerns apply: No concurrency out of the box, mutable objects passed as arguments could produce * unexpected results, etc. * * It should be pointed out that by default no validation occurs here whatsoever. Null closures will throw a Java NPE * when they are executed. The "expectedArguments" value is ignored. * * However, enabling validation will wrap these errors in an unchecked @see{ClosureException}. * */ public class Chain<Z> implements Iterable<ClosureView<Z>> { private LinkedList<ClosureView<Z>> chain = new LinkedList<ClosureView<Z>>(); private boolean validate = false; //final Class expectedReturn; public Chain() { // nothing for now } /** * Takes a series of ClosureView elements and combines them into a "chain". * * @param closures */ public Chain(ClosureView<Z>...closures) { for (ClosureView<Z> c : closures) { chain.add(c); } } /** * Takes a series of Chain elements and combines them into a new Chain. * * @param chains */ public Chain(Chain<Z>...chains) { for (Chain<Z> c : chains) for (ClosureView<Z> cv : c.chain) chain.addLast(cv); } public void setValidation(boolean validate) { this.validate = validate; } public boolean isValidated() { return validate; } /** * Prepends a series of closures to the chain. * * @param closures ClosureView objects to prepend. * @return this Chain, with the newly added closures */ public Chain<Z> prepend(ClosureView<Z>...closures) { for (int i=closures.length-1; i >= 0; --i) { chain.addFirst(closures[i]); } return this; } /** * Appends a series of closures to the chain. * * @param closures ClosureView objects to append. * @return this Chain, with the newly added closures */ public Chain<Z> append(ClosureView<Z>...closures) { for (ClosureView<Z> closure : closures) { chain.addLast(closure); } return this; } /* * Inserts a ClosureView into the desired location. * */ public Chain<Z> insert(int i, ClosureView<Z> closure) { chain.add(i, closure); return this; } /* * Inserts an existing chain into the desired location. * */ public Chain<Z> insert(int i, Chain<Z> chain) { for (int j=chain.chain.size()-1; j >= 0; --j) { this.chain.add(i, chain.chain.get(j)); } return this; } /* * Removes a closure from the desired location, shifting everything after it to the left. * */ public Chain<Z> remove(int i) { chain.remove(i); return this; } /* * Gets a closure at the index. * */ public ClosureView<Z> get(int i) { return chain.get(i); } /** * Prepends a series of closures to the chain. * * @param chains ClosureView objects to prepend. * @return this Chain, with the newly added closures */ public Chain<Z> prepend(Chain<Z>...chains) { for (int i = chains.length-1; i >= 0; --i) { Chain<Z> c = chains[i]; for (int j = c.chain.size()-1; j >= 0; --j) { chain.addFirst(c.chain.get(j)); } } return this; } /** * Appends a series of closures to the chain. * * @param chains ClosureView objects to append. * @return this Chain, with the newly added closures */ public Chain<Z> append(Chain<Z>...chains) { for (Chain<Z> c : chains) for (ClosureView<Z> cv : c.chain) chain.addLast(cv); return this; } /** * Execute the chain, starting from the first to the last (index 0 to size-1). * * @param args * @return */ @SuppressWarnings("unchecked") public Z run(Object...args) { Object result = null; if (validate) { int lcv = -1; for (ClosureView<Z> closure : chain) { ++lcv; if (closure == null) throw new ClosureChainException("Closure is null and will not execute! Index: " + lcv); try { int expected = closure.getExpectedArgs(); if (args == null && expected != 1) { throw new ClosureChainException("Wrong number of arguments. Expected: 0, Found: 1"); } else if (expected != args.length) { throw new ClosureChainException("Wrong number of arguments. Expected: " + expected + ", Found: " + args.length); } result = closure.run(args); if (result == null) { args = new Object[]{null}; } else if (result.getClass().isArray()) { args = (Object[]) result; } else { args = new Object[]{result}; } } catch (ClosureChainException ex) { throw ex; } catch (Exception ex) { throw new ClosureChainException("Error while executing closure.", ex); } } } else { for (ClosureView<Z> closure : chain) { result = closure.run(args); if (result == null) { args = new Object[]{null}; } else if (result.getClass().isArray()) { args = (Object[]) result; } else { args = new Object[]{result}; } } } if (validate) { try { return (Z) result; } catch (Exception ex) { throw new ClosureChainException("Could not return result.", ex); } } else { return (Z) result; } } public int size() { return chain.size(); } public Iterator<ClosureView<Z>> iterator() { return chain.iterator(); } }
package ash.vm; import ash.lang.*; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.stream.Collectors; public final class JavaMethod implements Serializable { private static final Class<?>[] EMPTY_CLASSES = new Class<?>[]{}; private static final long serialVersionUID = -933603269059202413L; private static final Map<String, JavaMethod> CACHE = new WeakHashMap<>(); private String methodFullName; private Class<?> clazz; transient private List<Method> candidateMethods; public static JavaMethod create(Symbol symbol) { String methodName = symbol.name; JavaMethod javaMethod = CACHE.get(methodName); if (javaMethod == null) { javaMethod = new JavaMethod(symbol); CACHE.put(methodName, javaMethod); } return javaMethod; } private JavaMethod(Symbol symbol) { methodFullName = symbol.name; if (methodFullName.charAt(0) == '.') return; try { clazz = loadClassBySymbol(symbol); loadCandidateMethod(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Class<?> loadClassBySymbol(Symbol symbolName) throws ClassNotFoundException { return Class.forName(getFullClassPath(symbolName.name)); } private static String getFullClassPath(String classpath) { int sepPos = classpath.indexOf('/'); String path = sepPos != -1 ? classpath.substring(0, sepPos) : classpath; if (Character.isUpperCase(path.charAt(0)) && path.indexOf('.') == -1) { return "java.lang." + path; } return path; } @Override public String toString() { return methodFullName; } private List<Method> loadCandidateMethod() { if (clazz != null && candidateMethods == null) { candidateMethods = filterMethod(clazz.getMethods(), getStaticMemberName()); } return candidateMethods; } private static List<Method> filterMethod(Method[] methods, final String methodName) { return Arrays.asList(methods).stream().filter(m -> m.getName().equals(methodName)).collect(Collectors.toList()); } private String getStaticMemberName() { return methodFullName.substring(methodFullName.indexOf('/') + 1); } public Object call(Object[] args) { List<Method> candidateMethods = loadCandidateMethod(); Object rst = candidateMethods != null && 0 < candidateMethods.size() ? callReflectMethod(args, candidateMethods) : callCustomMethod(args); if (rst == null) return BasicType.NIL; else if (rst instanceof Boolean) return ListUtils.transformBoolean(((Boolean) rst).booleanValue()); return rst; } private Object callCustomMethod(Object[] args) { switch (methodFullName) { case ".new": return reflectCreateObject(args); default: if (methodFullName.startsWith(".$")) { return readField(methodFullName.substring(2), args); } else if (methodFullName.charAt(0) == '.') { return callInstanceMethod(methodFullName.substring(1), args); } throw new UnsupportedOperationException("Unsupport Custom Method Call:" + methodFullName); } } private static Object callReflectMethod(Object[] args, List<Method> candidateMethods) { try { if (candidateMethods.size() == 1) { return candidateMethods.get(0).invoke(null, args); } else { return matchMethod(candidateMethods, getParameterTypes(args)).invoke(null, args); } } catch (Exception e) { throw new RuntimeException(e); } } private static Object callInstanceMethod(String methodName, Object[] args) { try { Object[] argsArray = subArray(args, 1); Method[] methods = args[0].getClass().getMethods(); Method matchMethod = matchMethod(filterMethod(methods, methodName), getParameterTypes(argsArray)); matchMethod.setAccessible(true); return matchMethod.invoke(args[0], argsArray); } catch (Exception e) { throw new RuntimeException(e); } } private static Object readField(String fieldName, Object[] args) { try { if (args[0] instanceof Symbol) { return loadClassBySymbol((Symbol) args[0]).getField(fieldName).get(null); } else { return args[0].getClass().getField(fieldName).get(args[0]); } } catch (Exception e) { throw new RuntimeException(e); } } public static boolean instanceOf(Class<?> valClass, Class<?> clazz) { return clazz == valClass || clazz.isAssignableFrom(valClass); } private static Object reflectCreateObject(Object[] args) { try { Class<?> clazz = loadClassBySymbol((Symbol) args[0]); Object[] newArgs = subArray(args, 1); Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length == 1) { return constructors[0].newInstance(newArgs); } else { return matchConstructor(Arrays.asList(constructors), getParameterTypes(newArgs)).newInstance(newArgs); } } catch (Exception e) { throw new RuntimeException(e); } } private static Object[] subArray(Object[] args, int startIndex) { Object[] newArgs = new Object[args.length - startIndex]; System.arraycopy(args, startIndex, newArgs, 0, newArgs.length); return newArgs; } private static Method matchMethod(List<Method> candidateMethods, final Class<?>[] targetParameterTypes) { return candidateMethods.stream() .filter(m -> strictMatch(m.getParameterTypes(), targetParameterTypes)).findFirst() .orElseGet(() -> candidateMethods.stream() .filter(m -> fuzzyMatch(m.getParameterTypes(), targetParameterTypes)) .findFirst().orElse(null)); } private static Constructor<?> matchConstructor(List<Constructor<?>> candidateConstructors, final Class<?>[] targetParameterTypes) { return candidateConstructors.stream() .filter(c -> strictMatch(c.getParameterTypes(), targetParameterTypes)) .findFirst().orElseGet(() -> candidateConstructors.stream() .filter(c -> fuzzyMatch(c.getParameterTypes(), targetParameterTypes)) .findFirst().orElse(null)); } private static Class<?>[] getParameterTypes(Object[] args) { return Arrays.asList(args).stream().map(Object::getClass).toArray(Class[]::new); } // int match to Integer ignore Float private static boolean strictMatch(Class<?>[] methodParameterTypes, Class<?>[] targetParameterTypes) { if (methodParameterTypes.length != targetParameterTypes.length) return false; for (int i = 0; i < targetParameterTypes.length; i++) { if (methodParameterTypes[i].isPrimitive() && STRICT_PRIMITIVE_CLASS_MAP.get(methodParameterTypes[i]) == targetParameterTypes[i]) { } else if (instanceOf(targetParameterTypes[i], methodParameterTypes[i])) { } else { return false; } } return true; } private static boolean fuzzyMatch(Class<?>[] methodParameterTypes, Class<?>[] targetParameterTypes) { if (methodParameterTypes.length != targetParameterTypes.length) return false; for (int i = 0; i < targetParameterTypes.length; i++) { if (methodParameterTypes[i].isPrimitive() && PRIMITIVE_CLASS_MAP.get(methodParameterTypes[i]).contains(targetParameterTypes[i])) { } else if (instanceOf(targetParameterTypes[i], methodParameterTypes[i])) { } else { return false; } } return true; } private static final PersistentMap<Class<?>, Class<?>> STRICT_PRIMITIVE_CLASS_MAP = new PersistentMap<>( boolean.class, Boolean.class, byte.class, Byte.class, char.class, Character.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, float.class, Float.class, double.class, Double.class ); private static final PersistentMap<Class<?>, PersistentSet<Class<?>>> PRIMITIVE_CLASS_MAP = new PersistentMap<>( boolean.class, new PersistentSet<>(Boolean.class), byte.class, new PersistentSet<>(Byte.class, Character.class), char.class, new PersistentSet<>(Byte.class, Character.class), short.class, new PersistentSet<>(Byte.class, Character.class, Short.class), int.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class), long.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class, Long.class), float.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class, Float.class), double.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class, Float.class, Double.class) ); }
package com.planet_ink.coffee_mud.Behaviors; 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 2000-2014 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. */ @SuppressWarnings({"unchecked","rawtypes"}) public class Nanny extends StdBehavior { @Override public String ID(){return "Nanny";} @Override protected int canImproveCode(){return Behavior.CAN_MOBS;} protected boolean watchesBabies=true; protected boolean watchesChildren=true; protected boolean watchesMounts=false; protected boolean watchesWagons=false; protected boolean watchesCars=false; protected boolean watchesBoats=false; protected boolean watchesAirCars=false; protected boolean watchesMOBFollowers=false; protected boolean changedSinceLastSave=false; protected String place="Nursery"; protected double hourlyRate=1.0; protected List<DropOff> dropOffs=null; protected List<Payment> payments=new SVector<Payment>(); protected DVector sayLaters=new DVector(2); // dynamic list of who belongs to what, before they leave // and get added to official drop-offs. protected List<DropOff> associations=new SVector<DropOff>(); @Override public String accountForYourself() { return "caretaking and babysitting for a fee"; } private static class DropOff { public MOB mommyM; public PhysicalAgent baby; public long dropOffTime; public DropOff(MOB momM, PhysicalAgent baby, long dropOff){mommyM=momM;this.baby=baby; dropOffTime=dropOff;} } private static class Payment { public MOB mommyM; public double paid; public Payment(MOB M, double d){mommyM=M; paid=d;} } public double getPaidBy(MOB mob) { if(mob==null) return 0.0; double amt=0.0; for(final Payment P : payments) if(P.mommyM==mob) amt+=P.paid; return amt; } public boolean isDroppedOff(PhysicalAgent P) { if(P==null) return false; for(final DropOff D : dropOffs) if(D.baby==P) return true; return false; } public boolean isAssociated(PhysicalAgent P) { if(P==null) return false; for(final DropOff D : associations) if((D.mommyM==P)||(D.baby==P)) return true; return false; } public void addPayment(MOB mob,double amt) { if(mob==null) return; for(final Payment P : payments) if(P.mommyM==mob) { P.paid += amt; return; } payments.add(new Payment(mob,amt)); } public void clearTheSlate(MOB mob) { if(mob==null) return; for(final Payment P : payments) if(P.mommyM==mob) payments.remove(P); if(dropOffs != null) for(final DropOff D : dropOffs) if(D.mommyM==mob) { boolean found=false; for(final DropOff A : associations) found = found || (A.mommyM==D.mommyM); if(!found) associations.add(D); dropOffs.remove(D); changedSinceLastSave=true; } } public double getAllOwedBy(MOB mob) { if(mob==null) return 0.0; final Room R=mob.location(); if(R==null) return 0.0; final Area A=R.getArea(); if(A==null) return 0.0; double amt=0.0; for(final DropOff D : dropOffs) if(D.mommyM==mob) { long t=System.currentTimeMillis()-D.dropOffTime; t=Math.round(Math.ceil(CMath.div(t,CMProps.getMillisPerMudHour()))); if(t>0) amt+=(t*hourlyRate); } return amt; } public List<PhysicalAgent> getAllOwedFor(MOB mob) { final List<PhysicalAgent> V=new Vector<PhysicalAgent>(); if(mob!=null) for(final DropOff D : dropOffs) if(D.mommyM==mob) V.add(D.baby); return V; } public String getPronoun(List<PhysicalAgent> V) { if(V.size()==0) return "your stuff"; int babies=0; int friends=0; int objects=0; int mounts=0; for(int v=0;v<V.size();v++) { final PhysicalAgent E=V.get(v); if(CMLib.flags().isBaby(E)||CMLib.flags().isChild(E)) babies++; else if(isMount(E)) mounts++; else if(E instanceof Item) objects++; else friends++; } final Vector pros=new Vector(); if(babies>0) pros.addElement("little one"+((babies>1)?"s":"")); if(mounts>0) pros.addElement("mount"+((babies>1)?"s":"")); if(friends>0) pros.addElement("friend"+((babies>1)?"s":"")); if(objects>0) pros.addElement("thing"+((babies>1)?"s":"")); final StringBuffer list=new StringBuffer(""); for(int p=0;p<pros.size();p++) { list.append((String)pros.elementAt(p)); if((pros.size()>1)&&(p==pros.size()-2)) list.append(", and "); else if(pros.size()>1) list.append(", "); } return list.toString().trim(); } public String getOwedFor(String currency, PhysicalAgent P) { for(final DropOff D : dropOffs) if(D.baby==P) { long t=System.currentTimeMillis()-D.dropOffTime; t=Math.round(Math.floor(CMath.div(t,CMProps.getMillisPerMudHour()))); if(t>0) return CMLib.beanCounter().abbreviatedPrice(currency, (t+hourlyRate))+" for watching "+P.name(); } return ""; } public String getAllOwedBy(String currency, MOB mob) { if(mob==null) return ""; final Room R=mob.location(); if(R==null) return ""; final Area A=R.getArea(); if(A==null) return ""; final StringBuffer owed=new StringBuffer(""); for(final DropOff D : dropOffs) if(D.mommyM==mob) { long t=System.currentTimeMillis()-D.dropOffTime; t=Math.round(Math.ceil(CMath.div(t,CMProps.getMillisPerMudHour()))); if(t>0) owed.append(CMLib.beanCounter().abbreviatedPrice(currency, (t*hourlyRate))+" for "+D.baby.name()+", "); } String s=owed.toString(); if(s.endsWith(", "))s=s.substring(0,s.length()-2); return s; } public PhysicalAgent getDroppedOffObjIfAny(PhysicalAgent P) { if(P==null) return null; if(isDroppedOff(P)) return P; if(P instanceof Container) { final List<Item> V=((Container)P).getContents(); Item I=null; for(int v=0;v<V.size();v++) { I=V.get(v); P=getDroppedOffObjIfAny(I); if(P!=null) return P; } } return null; } @Override public boolean okMessage(Environmental host, CMMsg msg) { if(!super.okMessage(host,msg)) return false; if(dropOffs==null) return true; final int targMinor=msg.targetMinor(); if((msg.target()==host) &&(targMinor==CMMsg.TYP_GIVE)) { if(isDropOffable(msg.tool())) { final String pronoun=this.getPronoun(new XVector(msg.tool())); msg.source().tell(msg.source(),host,msg.tool(),_("<T-NAME> won't accept <O-NAME>. You should probably leave your @x1 here.",pronoun)); return false; } if(msg.tool() instanceof Coins) { final Coins C=(Coins)msg.tool(); final String myCurrency=CMLib.beanCounter().getCurrency(host); if(!C.getCurrency().equalsIgnoreCase(myCurrency)) { if(host instanceof MOB) CMLib.commands().postSay((MOB)host,msg.source(),_("I'm don't accept @x1. I can only accept @x2.",CMLib.beanCounter().getDenominationName(C.getCurrency(),C.getDenomination()),CMLib.beanCounter().getDenominationName(myCurrency))); else msg.source().tell(_("The @x1 doesn't accept @x2. It only accepts @x3.",place,CMLib.beanCounter().getDenominationName(C.getCurrency(),C.getDenomination()),CMLib.beanCounter().getDenominationName(myCurrency))); return false; } } } else if(((targMinor==CMMsg.TYP_GET) ||(targMinor==CMMsg.TYP_PULL) ||(targMinor==CMMsg.TYP_PUSH) ||(targMinor==CMMsg.TYP_CAST_SPELL)) &&(msg.target() instanceof Item) &&(!msg.targetMajor(CMMsg.MASK_INTERMSG)) &&(getDroppedOffObjIfAny((Item)msg.target()))!=null) { final PhysicalAgent obj=getDroppedOffObjIfAny((Item)msg.target()); final String amt=getOwedFor(CMLib.beanCounter().getCurrency(host),obj); if((msg.source().location()==CMLib.map().roomLocation(host)) &&(host instanceof MOB)) { if(amt.length()>0) CMLib.commands().postSay((MOB)host,msg.source(),_("I'm afraid that @x1 fees of @x2 are still owed.",place,amt)); else CMLib.commands().postSay((MOB)host,msg.source(),_("I'm afraid that @x1 fees are still owed on @x2.",place,obj.name())); } else if(amt.length()>0) msg.source().tell(_("You'll need to pay @x1 fees of @x2 first.",place,amt)); else msg.source().tell(_("You'll need to pay your @x1 fees for @x2 first.",place,obj.name())); return false; } else if((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MALICIOUS) ||CMath.bset(msg.targetMajor(),CMMsg.MASK_MALICIOUS)) &&(msg.target() instanceof PhysicalAgent) &&((getDroppedOffObjIfAny((PhysicalAgent)msg.target())!=null) ||(msg.target()==host) ||(msg.target()==CMLib.map().roomLocation(host)))) { if(msg.source()!=host) { if((host instanceof MOB)&&(msg.source().location()==CMLib.map().roomLocation(host))) { CMLib.commands().postSay((MOB)host,msg.source(),_("Not in my @x1 you dont!",place)); final MOB victim=msg.source().getVictim(); if(victim!=null) victim.makePeace(); msg.source().makePeace(); } else msg.source().tell(_("You can't do that here.")); } return false; } else if((msg.sourceMinor()==CMMsg.TYP_LEAVE) &&(msg.target()==CMLib.map().roomLocation(host))) { final PhysicalAgent obj=getDroppedOffObjIfAny(msg.source()); if(obj!=null) { if((msg.tool() instanceof Ability) &&(msg.source().location()!=null)) { final Room R=CMLib.map().roomLocation(host); final boolean summon=CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_SUMMONING); final boolean teleport=CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_TRANSPORTING); final boolean shere=(msg.source().location()==R); if((!shere)&&((summon)||(teleport))) { if((msg.source().location()!=null)&&(msg.source().location()!=R)) msg.source().location().showHappens(CMMsg.MSG_OK_VISUAL,_("Magical energy fizzles and is absorbed into the air!")); R.showHappens(CMMsg.MSG_OK_VISUAL,_("Magic energy fizzles and is absorbed into the air.")); return false; } } else { final String amt=getOwedFor(CMLib.beanCounter().getCurrency(host),obj); if((msg.source().location()==CMLib.map().roomLocation(host)) &&(host instanceof MOB)) { if(amt.length()>0) CMLib.commands().postSay((MOB)host,msg.source(),_("I'm afraid that @x1 fees of @x2 are still owed on @x3.",place,amt,obj.name())); else CMLib.commands().postSay((MOB)host,msg.source(),_("I'm afraid that @x1 fees are still owed on @x2.",place,obj.name())); } else if(amt.length()>0) msg.source().tell(_("You'll need to pay @x1 fees of @x2 for @x3 first.",place,amt,obj.name())); else msg.source().tell(_("You'll need to pay your @x1 fees for @x2 first.",place,obj.name())); } return false; } } return true; } public boolean isMount(Environmental E) { if((E instanceof MOB) &&(E instanceof Rideable) &&((((Rideable)E).rideBasis()==Rideable.RIDEABLE_LAND) ||(((Rideable)E).rideBasis()==Rideable.RIDEABLE_AIR) ||(((Rideable)E).rideBasis()==Rideable.RIDEABLE_WATER))) return true; return false; } public boolean isDropOffable(Environmental E) { if(E==null) return false; if((E instanceof MOB)&&(!((MOB)E).isMonster())) return false; if((watchesBabies)&&(CMLib.flags().isBaby(E))) return true; if((watchesChildren)&&(CMLib.flags().isChild(E))&&(!CMLib.flags().isBaby(E))) return true; if((watchesMounts)&&(isMount(E))) return true; if((watchesMOBFollowers)&&(E instanceof MOB)&&(!isMount(E))&&(!CMLib.flags().isChild(E))&&(!CMLib.flags().isBaby(E))) return true; if((this.watchesWagons) &&(E instanceof Rideable) &&(((Rideable)E).rideBasis()==Rideable.RIDEABLE_WAGON)) return true; if((this.watchesCars) &&(E instanceof Item) &&(E instanceof Rideable) &&(((Rideable)E).rideBasis()==Rideable.RIDEABLE_LAND)) return true; if((this.watchesBoats) &&(E instanceof Item) &&(E instanceof Rideable) &&(((Rideable)E).rideBasis()==Rideable.RIDEABLE_WATER)) return true; if((this.watchesAirCars) &&(E instanceof Item) &&(E instanceof Rideable) &&(((Rideable)E).rideBasis()==Rideable.RIDEABLE_AIR)) return true; return false; } public MOB ultimateFollowing(Environmental E) { MOB ultimateFollowing=null; if(E instanceof MOB) ultimateFollowing=((MOB)E).amUltimatelyFollowing(); return ultimateFollowing; } public MOB getMommyOf(Physical P) { if((P instanceof Item) &&(((Item)P).owner() instanceof MOB) &&(!((MOB)((Item)P).owner()).isMonster())) return (MOB)((Item)P).owner(); if((P instanceof MOB) &&(((MOB)P).amFollowing()!=null) &&(!((MOB)P).amFollowing().isMonster())) return ((MOB)P).amFollowing(); if((P instanceof MOB) &&(ultimateFollowing(P)!=null) &&(!ultimateFollowing(P).isMonster())) return ultimateFollowing(P); if(P instanceof Rideable) { final Rideable R=(Rideable)P; Environmental E2=null; for(int r=0;r<R.numRiders();r++) { E2=R.fetchRider(r); if((E2 instanceof MOB) &&(!((MOB)E2).isMonster())) return (MOB)E2; } } if((P instanceof Rider) &&(((Rider)P).riding()!=null)) return getMommyOf(((Rider)P).riding()); return null; } public void addAssociationsIfNecessary(Set<PhysicalAgent> H) { PhysicalAgent P=null; for(final Object o : H) if(o instanceof PhysicalAgent) { P=(PhysicalAgent)o; if((P instanceof Rider)&&(((Rider)P).riding()!=null)&&(!H.contains(((Rider)P).riding()))) H.add(P); } for(final Object o : H) if(o instanceof PhysicalAgent) { P=(PhysicalAgent)o; if((isDropOffable(P))&&(!isAssociated(P))) { final MOB source=getMommyOf(P); if(source!=null) associations.add(new DropOff(source,P,System.currentTimeMillis())); } if(P instanceof MOB) { final MOB mob=(MOB)P; for(int t=0;t<mob.numItems();t++) { final Item I=mob.getItem(t); if(isDropOffable(I)&&(!isAssociated(I))) { final MOB source=getMommyOf(I); if(source!=null) associations.add(new DropOff(source,I,System.currentTimeMillis())); } } } } } public List<PhysicalAgent> myCurrentAssocs(MOB mob) { final Vector<PhysicalAgent> V=new Vector<PhysicalAgent>(); if(mob!=null) for(final DropOff A : associations) if(A.mommyM==mob) V.add(A.baby); return V; } @Override public void executeMsg(Environmental host, CMMsg msg) { super.executeMsg(host,msg); if(dropOffs==null) return; if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.target()==CMLib.map().roomLocation(host))) { final String currency=CMLib.beanCounter().getCurrency(host); final Set H=msg.source().getGroupMembers(new HashSet<MOB>()); msg.source().getRideBuddies(H); if(!H.contains(msg.source())) H.add(msg.source()); HashSet<Environmental> H2 = null; do { H2 = new HashSet<Environmental>(); H2.addAll(H); for (final Object element : H2) { final Environmental E = (Environmental)element; if(E instanceof Rideable) { final Rideable R = (Rideable)E; for(int r = 0; r<R.numRiders(); r++) if(!H.contains(R.fetchRider(r))) H.add(R.fetchRider(r)); } } } while(H.size() > H2.size()); addAssociationsIfNecessary(H); final List<PhysicalAgent> myAssocs=myCurrentAssocs(msg.source()); final StringBuffer list=new StringBuffer(""); for(int m=0;m<myAssocs.size();m++) { list.append(myAssocs.get(m).name()); if((myAssocs.size()>1)&&(m==myAssocs.size()-2)) list.append(", and "); else if(myAssocs.size()>1) list.append(", "); } if(list.length()>0) sayLaters.addElement(msg.source(),"Welcome to my "+place+", "+msg.source().name()+"! You are welcome to leave " + list.toString()+" here under my care and protection. Be aware that I charge " +CMLib.beanCounter().abbreviatedPrice(currency,hourlyRate)+" per hour, each. " + "No payment is due until you return to fetch your "+getPronoun(myAssocs)+"."); final double owed=getAllOwedBy(msg.source()); final double paid=getPaidBy(msg.source()); if(owed>0) { final List<PhysicalAgent> myStuff=getAllOwedFor(msg.source()); final String pronoun=getPronoun(myStuff); sayLaters.addElement(msg.source(),"Welcome back, "+msg.source().name()+"! If are here for your "+pronoun +", the total bill is: "+getAllOwedBy(currency, msg.source()) +" ("+CMLib.beanCounter().abbreviatedPrice(currency,owed-paid)+"). " +"You can just give me the money to settle the bill."); } } else if((msg.target()==host) &&(msg.targetMinor()==CMMsg.TYP_GIVE) &&(msg.tool() instanceof Coins)) { addPayment(msg.source(),((Coins)msg.tool()).getTotalValue()); final double owed=getAllOwedBy(msg.source()); final double paid=getPaidBy(msg.source()); final String currency=CMLib.beanCounter().getCurrency(host); if((paid>owed)&&(host instanceof MOB)) { final double change=paid-owed; final Coins C=CMLib.beanCounter().makeBestCurrency(currency,change); final MOB source=msg.source(); if((change>0.0)&&(C!=null)) { // this message will actually end up triggering the hand-over. final CMMsg newMsg=CMClass.getMsg((MOB)host,source,C,CMMsg.MSG_SPEAK,_("^T<S-NAME> say(s) 'Heres your change.' to <T-NAMESELF>.^?")); C.setOwner((MOB)host); final long num=C.getNumberOfCoins(); final String curr=C.getCurrency(); final double denom=C.getDenomination(); C.destroy(); C.setNumberOfCoins(num); C.setCurrency(curr); C.setDenomination(denom); msg.addTrailerMsg(newMsg); } else CMLib.commands().postSay((MOB)host,source,_("Gee, thanks. :)"),true,false); } ((Coins)msg.tool()).destroy(); if(paid>=owed) { final List<PhysicalAgent> V=getAllOwedFor(msg.source()); PhysicalAgent P=null; for(int v=0;v<V.size();v++) { P=V.get(v); if(P instanceof MOB) { CMLib.commands().postFollow((MOB)P,msg.source(),false); if(CMath.bset(((MOB)P).getBitmap(), MOB.ATT_AUTOGUARD)) ((MOB)P).setBitmap(CMath.unsetb(((MOB)P).getBitmap(), MOB.ATT_AUTOGUARD)); if(((MOB)P).amFollowing()!=msg.source()) { CMLib.commands().postSay((MOB)host,msg.source(),_("Hmm, '@x1' doesn't seem ready to leave. Now get along!",P.name()),true,false); msg.source().location().send((MOB)P,CMClass.getMsg((MOB)P,msg.source(),null,CMMsg.MSG_FOLLOW|CMMsg.MASK_ALWAYS,_("<S-NAME> follow(s) <T-NAMESELF>."))); if(((MOB)P).amFollowing()!=msg.source()) ((MOB)P).setFollowing(msg.source()); } } } clearTheSlate(msg.source()); sayLaters.addElement(msg.source(),"Thanks, come again!"); } else sayLaters.addElement(msg.source(),"Thanks, but you still owe "+CMLib.beanCounter().abbreviatedPrice(currency,owed-paid)+"."); } else if((msg.source()==host) &&(msg.targetMinor()==CMMsg.TYP_SPEAK) &&(msg.target() instanceof MOB) &&(msg.tool() instanceof Coins) &&(((Coins)msg.tool()).amDestroyed()) &&(!msg.source().isMine(msg.tool())) &&(!((MOB)msg.target()).isMine(msg.tool()))) CMLib.beanCounter().giveSomeoneMoney(msg.source(),(MOB)msg.target(),((Coins)msg.tool()).getTotalValue()); } public int getNameIndex(Vector V, String name) { int index=0; for(int v=0;v<V.size();v++) { if(((String)V.elementAt(v)).equals(name)) index++; } return index; } @Override public String getParms() { final StringBuffer parms=new StringBuffer(""); parms.append("RATE="+hourlyRate+" "); parms.append("NAME=\""+place+"\" "); parms.append("WATCHES=\""); if(watchesBabies) parms.append("Babies,"); if(watchesChildren) parms.append("Children,"); if(watchesMounts) parms.append("Mounts,"); if(watchesWagons) parms.append("Wagons,"); if(watchesCars) parms.append("Cars,"); if(watchesBoats) parms.append("Boats,"); if(watchesAirCars) parms.append("AirCars,"); if(watchesMOBFollowers) parms.append("Followers,"); parms.append("\""); if(dropOffs!=null) { parms.append(" |~| "); final Vector<String> oldNames=new Vector<String>(); String eName=null; String oName=null; for(final DropOff D : dropOffs) { parms.append("<DROP>"); eName=D.baby.Name(); oName=D.mommyM.Name(); if(oldNames.contains(eName)) eName=getNameIndex(oldNames,eName)+"."+eName; parms.append(CMLib.xml().convertXMLtoTag("ENAM",CMLib.xml().parseOutAngleBrackets(eName))); parms.append(CMLib.xml().convertXMLtoTag("ONAM",CMLib.xml().parseOutAngleBrackets(oName))); parms.append(CMLib.xml().convertXMLtoTag("TIME",D.dropOffTime)); parms.append("</DROP>"); } } return parms.toString().trim(); } @Override public void setParms(String parms) { super.setParms(parms); final int x=super.parms.indexOf("|~|"); if(x>0) dropOffs=null; hourlyRate=CMParms.getParmDouble(parms,"RATE",2.0); place=CMParms.getParmStr(parms,"NAME","nursery"); final List<String> watches=CMParms.parseCommas(CMParms.getParmStr(parms,"WATCHES","Babies,Children").toUpperCase(),true); String watch=null; watchesBabies=false; watchesChildren=false; watchesMounts=false; watchesWagons=false; watchesCars=false; watchesBoats=false; watchesAirCars=false; watchesMOBFollowers=false; for(int w=0;w<watches.size();w++) { watch=watches.get(w); if(watch.startsWith("BAB")) watchesBabies=true; if(watch.startsWith("CHI")) watchesChildren=true; if(watch.startsWith("MOU")) watchesMounts=true; if(watch.startsWith("WAG")) watchesWagons=true; if(watch.startsWith("CAR")) watchesCars=true; if(watch.startsWith("BOA")) watchesBoats=true; if(watch.startsWith("AIR")) watchesAirCars=true; if(watch.startsWith("FOL")) watchesMOBFollowers=true; } } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) ||((!(ticking instanceof Environmental)))) return true; if(dropOffs==null) { final int x=super.parms.indexOf("|~|"); dropOffs=new SVector<DropOff>(); if(x>0) { final String codes=super.parms.substring(x+3); parms=parms.substring(0,3); if(codes.trim().length()>0) { final List<XMLLibrary.XMLpiece> V=CMLib.xml().parseAllXML(codes); XMLLibrary.XMLpiece P=null; final Hashtable parsedPlayers=new Hashtable(); long time=0; String eName=null; PhysicalAgent PA=null; String oName=null; final Room R=CMLib.map().roomLocation((Environmental)ticking); MOB M=null; if((V!=null)&&(R!=null)) for(int v=0;v<V.size();v++) { P=(V.get(v)); if((P!=null)&&(P.contents!=null)&&(P.contents.size()==3)&&(P.tag.equalsIgnoreCase("DROP"))) { eName=CMLib.xml().restoreAngleBrackets(CMLib.xml().getValFromPieces(P.contents,"ENAM")); oName=CMLib.xml().restoreAngleBrackets(CMLib.xml().getValFromPieces(P.contents,"ONAM")); time=CMLib.xml().getLongFromPieces(P.contents,"TIME"); if(parsedPlayers.get(oName) instanceof MOB) M=(MOB)parsedPlayers.get(oName); else if(parsedPlayers.get(oName) instanceof String) continue; else { M=CMLib.players().getLoadPlayer(oName); if(M==null) parsedPlayers.put(oName,""); else parsedPlayers.put(oName,M); } PA=R.fetchInhabitant(eName); if(PA==null) PA=R.findItem(eName); if(PA==null) Log.errOut("Nanny","Unable to find "+eName+" for "+oName+"!!"); else if(!isDroppedOff(PA)) dropOffs.add(new DropOff(M,PA,time)); } else if(P!=null) Log.errOut("Nanny","Unable to parse: "+codes+", specifically: "+P.value); } } } changedSinceLastSave=false; } for(int s=sayLaters.size()-1;s>=0;s--) { if(ticking instanceof MOB) CMLib.commands().postSay((MOB)ticking,(MOB)sayLaters.elementAt(s,1),(String)sayLaters.elementAt(s,2)); else ((MOB)sayLaters.elementAt(s,1)).tell((String)sayLaters.elementAt(s,2)); sayLaters.removeElementAt(s); } final Room R=CMLib.map().roomLocation((Environmental)ticking); if(R!=null) for(final DropOff D : associations) { if(R.isHere(D.baby)) { if((CMLib.map().roomLocation(D.mommyM)!=R) ||(!CMLib.flags().isInTheGame(D.mommyM,true))) { if(!isDroppedOff(D.baby)) { if((D.baby instanceof MOB)&&(((MOB)D.baby).amFollowing()!=null)) ((MOB)D.baby).setFollowing(null); D.dropOffTime=System.currentTimeMillis(); dropOffs.add(D); associations.remove(D); changedSinceLastSave=true; } } } else associations.remove(D); } if(!changedSinceLastSave) for(final DropOff D : dropOffs) if((D.baby instanceof MOB) &&(R!=null) &&(!R.isInhabitant((MOB)D.baby))) { dropOffs.remove(D); changedSinceLastSave=true; } for(final DropOff D : dropOffs) if((D.baby instanceof Item) &&(R!=null) &&(!R.isContent((Item)D.baby))) { dropOffs.remove(D); changedSinceLastSave=true; } if(changedSinceLastSave) { if(R!=null) { final Vector<MOB> mobsToSave=new Vector<MOB>(); if(ticking instanceof MOB) mobsToSave.addElement((MOB)ticking); MOB M=null; for(int i=0;i<R.numInhabitants();i++) { M=R.fetchInhabitant(i); if((M!=null) &&(M.isSavable()) &&(CMLib.flags().isMobile(M)) &&(M.getStartRoom()==R) &&(!mobsToSave.contains(M))) mobsToSave.addElement(M); } for(final DropOff D : dropOffs) { if((D.baby instanceof MOB) &&(R.isInhabitant((MOB)D.baby)) &&(!mobsToSave.contains(D.baby))) mobsToSave.addElement((MOB)D.baby); } CMLib.database().DBUpdateTheseMOBs(R,mobsToSave); } final Vector<Item> itemsToSave=new Vector<Item>(); if(ticking instanceof Item) itemsToSave.addElement((Item)ticking); Item I=null; if(R!=null) { for(int i=0;i<R.numItems();i++) { I=R.getItem(i); if((I!=null) &&(I.isSavable()) &&((!CMLib.flags().isGettable(I))||(I.displayText().length()==0)) &&(!itemsToSave.contains(I))) itemsToSave.addElement(I); } for(final DropOff D : dropOffs) { if((D.baby instanceof Item) &&(R.isContent((Item)D.baby)) &&(!itemsToSave.contains(D.baby))) itemsToSave.addElement((Item)D.baby); } CMLib.database().DBUpdateTheseItems(R,itemsToSave); } if(ticking instanceof Room) CMLib.database().DBUpdateRoom((Room)ticking); changedSinceLastSave=false; } if((dropOffs.size()>0)&&(ticking instanceof MOB)&&(CMLib.dice().rollPercentage()<10)&&(R!=null)) { final MOB mob=(MOB)ticking; final PhysicalAgent PA=dropOffs.get(CMLib.dice().roll(1,dropOffs.size(),-1)).baby; if(CMLib.flags().isBaby(PA)) { if(PA.fetchEffect("Soiled")!=null) { R.show(mob, PA, CMMsg.MSG_NOISYMOVEMENT,_("<S-NAME> change(s) <T-YOUPOSS> diaper.")); PA.delEffect(PA.fetchEffect("Soiled")); } else if(CMLib.dice().rollPercentage()>50) R.show(mob, PA, CMMsg.MSG_NOISYMOVEMENT,_("<S-NAME> play(s) with <T-NAME>.")); else R.show(mob, PA, CMMsg.MSG_NOISYMOVEMENT,_("<S-NAME> go(es) 'coochie-coochie coo' to <T-NAME>.")); } else if(CMLib.flags().isChild(PA)) { if(CMLib.dice().rollPercentage()>20) R.show(mob, PA, CMMsg.MSG_NOISYMOVEMENT,_("<S-NAME> play(s) with <T-NAME>.")); else { R.show(mob, PA, CMMsg.MSG_NOISYMOVEMENT,_("<S-NAME> groom(s) <T-NAME>.")); if(PA.fetchEffect("Soiled")!=null) PA.delEffect(PA.fetchEffect("Soiled")); } } else if(isMount(PA)) { if(PA instanceof MOB) { if((!CMLib.flags().isAnimalIntelligence((MOB)PA)) &&(CMLib.flags().canSpeak(mob))) R.show(mob, PA, CMMsg.MSG_NOISE,_("<S-NAME> speak(s) quietly with <T-NAME>.")); else { final List<RawMaterial> V=((MOB)PA).charStats().getMyRace().myResources(); boolean comb=false; if(V!=null) for(int v=0;v<V.size();v++) if(((Item)V.get(v)).material()==RawMaterial.RESOURCE_FUR) comb=true; if(comb) R.show(mob, PA, CMMsg.MSG_QUIETMOVEMENT,_("<S-NAME> groom(s) <T-NAME>.")); else R.show(mob, PA, CMMsg.MSG_QUIETMOVEMENT,_("<S-NAME> pet(s) <T-NAME>.")); } } else R.show(mob, PA, CMMsg.MSG_LOCK,_("<S-NAME> admire(s) <T-NAME>.")); } else if(PA instanceof MOB) { if(CMLib.flags().isAnimalIntelligence((MOB)PA)) R.show(mob, PA, CMMsg.MSG_QUIETMOVEMENT,_("<S-NAME> smile(s) and pet(s) <T-NAME>.")); else if(CMLib.flags().canSpeak(mob)) R.show(mob, PA, CMMsg.MSG_NOISE,_("<S-NAME> speak(s) quietly with <T-NAME>.")); } } return true; } }
/* * Copyright 2016. * This code is part of IBM Mobile UI Builder */ package ibmmobileappbuilder.charts.ui; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.Chart; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import java.util.ArrayList; import java.util.List; import ibmmobileappbuilder.charts.R; import ibmmobileappbuilder.ds.Datasource; import ibmmobileappbuilder.ds.Pagination; import ibmmobileappbuilder.ds.filter.Filter; import ibmmobileappbuilder.ui.BaseFragment; import ibmmobileappbuilder.ui.Filterable; import ibmmobileappbuilder.ui.Refreshable; import ibmmobileappbuilder.util.ColorUtils; public abstract class PieChartFragment<T> extends BaseFragment implements ChartFragment, Filterable, Refreshable { private static String BUNDLE_SERIES = "series"; private static String BUNDLE_LABELS = "labels"; private static String BUNDLE_RANDOM_COLORS = "random_colors"; private static String BUNDLE_PIE_TITLE = "pie_title"; private PieChart pieChart; private Datasource<T> datasource; private TextView pieTitle; protected View pieChartContainer; protected View progressContainer; protected List<Number> series = new ArrayList<Number>(); protected List<String> labels = new ArrayList<String>(); protected ArrayList<Integer> randomColors = new ArrayList<Integer>(); private int textColor, backgroundColor; @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(savedInstanceState == null) { datasource = getDatasource(); } View view = inflater.inflate(R.layout.fragment_pie_chart, container, false); pieChart = (PieChart) view.findViewById(R.id.pie_chart); pieChartContainer = view.findViewById(R.id.pie_chart_container); progressContainer = view.findViewById(R.id.progressContainer); pieTitle = (TextView) view.findViewById(R.id.pie_title); textColor = getResources().getColor(R.color.textColor); backgroundColor = getResources().getColor(R.color.window_background); // initialize chart pieChartSetup(); return view; } private void pieChartSetup() { pieChart.setUsePercentValues(false); pieChart.setDescription(""); pieChart.setNoDataText(getString(R.string.chart_no_info)); Paint p = pieChart.getPaint(Chart.PAINT_INFO); p.setColor(textColor); pieChart.setExtraOffsets(15, 0, 15, 0); pieChart.setDragDecelerationFrictionCoef(0.95f); pieChart.setCenterText(""); pieChart.setCenterTextColor(textColor); pieChart.setDrawHoleEnabled(true); pieChart.setHoleColor(Color.WHITE); pieChart.setTransparentCircleColor(Color.WHITE); pieChart.setTransparentCircleAlpha(110); pieChart.setHoleRadius(48f); pieChart.setTransparentCircleRadius(51f); pieChart.setDrawCenterText(true); pieChart.setDrawSliceText(false); pieChart.setHoleColor(backgroundColor); pieChart.setRotationAngle(0); pieChart.setRotationEnabled(true); pieChart.setHighlightPerTapEnabled(true); pieChart.animateY(getResources().getInteger(R.integer.animation_duration), Easing.EasingOption.EaseInOutCirc); Legend legend = pieChart.getLegend(); legend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER); legend.setXEntrySpace(4f); legend.setWordWrapEnabled(true); legend.setTextSize(getResources().getDimension(R.dimen.legend_text_font_size)); legend.setTextColor(textColor); legend.setForm(Legend.LegendForm.SQUARE); legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM); legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER); legend.setFormSize(getResources().getDimension(R.dimen.legend_form_size)); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if(savedInstanceState == null) { loadData(); } else { float[] serieValues = savedInstanceState.getFloatArray(BUNDLE_SERIES); labels = savedInstanceState.getStringArrayList(BUNDLE_LABELS); randomColors = savedInstanceState.getIntegerArrayList(BUNDLE_RANDOM_COLORS); pieTitle.setText(savedInstanceState.getString(BUNDLE_PIE_TITLE)); if (serieValues != null && labels != null && randomColors != null && pieTitle != null) { series = new ArrayList<Number>(); for (int i = 0; i < serieValues.length; i++) { series.add(serieValues[i]); } drawChart(); } else { loadData(); } } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); if(series != null) { float serieValues[] = new float[series.size()]; for(int i=0;i<series.size();i++) { serieValues[i] = (Float) series.get(i); } savedInstanceState.putFloatArray(BUNDLE_SERIES, serieValues); savedInstanceState.putStringArrayList(BUNDLE_LABELS, (ArrayList<String>) labels); savedInstanceState.putIntegerArrayList(BUNDLE_RANDOM_COLORS, randomColors); if(pieTitle != null && pieTitle.getText() != null) { savedInstanceState.putString(BUNDLE_PIE_TITLE, pieTitle.getText().toString()); } } } private void loadData() { //set up the listener for charts Datasource.Listener dsListener = new Datasource.Listener<List<T>>() { @Override public void onSuccess(List<T> ts) { if (pieChart != null && ts.size() != 0) { loadChart(ts); drawChart(); } setListShown(true); } @Override public void onFailure(Exception e) { setListShown(true); } }; if (datasource != null) { setListShown(false); if (datasource instanceof Pagination) { ((Pagination) datasource).getItems(0, dsListener); } else { datasource.getItems(dsListener); } } } @Override public void onDestroyView() { super.onDestroyView(); pieChart = null; } @Override public void setChartTitle(String title) { pieTitle.setText(title); } @Override public void addSeries(List<Number> series, int seriesColor, String label) { if(series != null && !series.isEmpty()) { this.series.add(series.get(0)); this.labels.add(label); this.randomColors.add(seriesColor); } } @Override public void drawChart() { List<Entry> entries = new ArrayList<Entry>(); for(int i=0;i<series.size();i++) { entries.add(new Entry((float) series.get(i), i)); } PieDataSet dataSet = new PieDataSet(entries, ""); dataSet.setColors(randomColors); dataSet.setValueLinePart1OffsetPercentage(80.f); dataSet.setValueLinePart1Length(0.2f); dataSet.setValueLinePart2Length(0.4f); dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); PieData data = new PieData(labels, dataSet); data.setValueTextSize(getResources().getDimension(R.dimen.pie_value_font_size)); data.setValueTextColor(textColor); pieChart.setData(data); pieChart.highlightValues(null); pieChart.invalidate(); } @Override public void onSearchTextChanged(String s) { datasource.onSearchTextChanged(s); refresh(); } @Override public void addFilter(Filter filter) { datasource.addFilter(filter); } @Override public void clearFilters() { datasource.clearFilters(); } @Override public void refresh() { loadData(); pieChart.animateY(getResources().getInteger(R.integer.animation_duration), Easing.EasingOption.EaseInOutCirc); } private void setListShown(boolean shown) { if (progressContainer != null && pieChartContainer != null) { progressContainer.setVisibility(shown ? View.GONE : View.VISIBLE); pieChartContainer.setVisibility(shown ? View.VISIBLE : View.GONE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.refresh_menu, menu); MenuItem item = menu.findItem(R.id.action_refresh); ColorUtils.tintIcon(item, R.color.textBarColor, getActivity()); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_refresh){ refresh(); return true; } return super.onOptionsItemSelected(item); } // Delegates protected abstract Datasource<T> getDatasource(); protected abstract void loadChart(List<T> items); }
package hex.tree.drf; import hex.Model; import hex.ModelMetricsBinomial; import org.junit.*; import static org.junit.Assert.assertEquals; import water.*; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.Frame; import water.fvec.RebalanceDataSet; import water.fvec.Vec; import water.util.Log; import java.util.Arrays; import java.util.Random; public class DRFTest extends TestUtil { @BeforeClass public static void stall() { stall_till_cloudsize(1); } abstract static class PrepData { abstract int prep(Frame fr); } static String[] s(String...arr) { return arr; } static long[] a(long ...arr) { return arr; } static long[][] a(long[] ...arr) { return arr; } @Test public void testClassIris1() throws Throwable { // iris ntree=1 // the DRF should use only subset of rows since it is using oob validation basicDRFTestOOBE_Classification( "./smalldata/iris/iris.csv", "iris.hex", new PrepData() { @Override int prep(Frame fr) { return fr.numCols() - 1; } }, 1, 20, 1, 20, ard(ard(25, 0, 0), ard(0, 17, 1), ard(2, 1, 15)), s("Iris-setosa", "Iris-versicolor", "Iris-virginica")); } @Test public void testClassIris5() throws Throwable { // iris ntree=50 basicDRFTestOOBE_Classification( "./smalldata/iris/iris.csv", "iris5.hex", new PrepData() { @Override int prep(Frame fr) { return fr.numCols() - 1; } }, 5, 20, 1, 20, ard(ard(41, 0, 0), ard(1, 39, 2), ard(1, 3, 41)), s("Iris-setosa", "Iris-versicolor", "Iris-virginica")); } @Test public void testClassCars1() throws Throwable { // cars ntree=1 basicDRFTestOOBE_Classification( "./smalldata/junit/cars.csv", "cars.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("name").remove(); return fr.find("cylinders"); } }, 1, 20, 1, 20, ard(ard(0, 0, 0, 0, 0), ard(3, 65, 0, 1, 0), ard(0, 1, 0, 0, 0), ard(0, 0, 1, 30, 0), ard(0, 0, 0, 1, 39)), s("3", "4", "5", "6", "8")); } @Test public void testClassCars5() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/junit/cars.csv", "cars5.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("name").remove(); return fr.find("cylinders"); } }, 5, 20, 1, 20, ard(ard(3, 0, 0, 0, 0), ard(2, 177, 1, 4, 0), ard(0, 1, 1, 0, 0), ard(0, 2, 2, 69, 1), ard(0, 0, 0, 3, 87)), s("3", "4", "5", "6", "8")); } @Test public void testConstantCols() throws Throwable { try { basicDRFTestOOBE_Classification( "./smalldata/poker/poker100", "poker.hex", new PrepData() { @Override int prep(Frame fr) { for (int i = 0; i < 7; i++) { fr.remove(3).remove(); } return 3; } }, 1, 20, 1, 20, null, null); Assert.fail(); } catch( H2OModelBuilderIllegalArgumentException iae ) { /*pass*/ } } @Ignore @Test public void testBadData() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/junit/drf_infinities.csv", "infinitys.hex", new PrepData() { @Override int prep(Frame fr) { return fr.find("DateofBirth"); } }, 1, 20, 1, 20, ard(ard(6, 0), ard(9, 1)), s("0", "1")); } //@Test public void testCreditSample1() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/kaggle/creditsample-training.csv.gz", "credit.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("MonthlyIncome").remove(); return fr.find("SeriousDlqin2yrs"); } }, 1, 20, 1, 20, ard(ard(46294, 202), ard(3187, 107)), s("0", "1")); } @Test public void testCreditProstate1() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/logreg/prostate.csv", "prostate.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("CAPSULE"); } }, 1, 20, 1, 20, ard(ard(0, 81), ard(0, 53)), s("0", "1")); } @Test public void testCreditProstateRegression1() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/logreg/prostate.csv", "prostateRegression.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("AGE"); } }, 1, 20, 1, 10, 84.83960821204235 ); } @Test public void testCreditProstateRegression5() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/logreg/prostate.csv", "prostateRegression5.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("AGE"); } }, 5, 20, 1, 10, 62.34506879389341 ); } @Test public void testCreditProstateRegression50() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/logreg/prostate.csv", "prostateRegression50.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("AGE"); } }, 50, 20, 1, 10, 48.16452593965962 ); } @Test public void testCzechboard() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/gbm_test/czechboard_300x300.csv", "czechboard_300x300.hex", new PrepData() { @Override int prep(Frame fr) { Vec resp = fr.remove("C2"); fr.add("C2", resp.toEnum()); resp.remove(); return fr.find("C3"); } }, 50, 20, 1, 20, ard(ard(0, 45000), ard(0, 45000)), s("0", "1")); } @Test public void testProstate() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/prostate/prostate.csv.zip", "prostate2.zip.hex", new PrepData() { @Override int prep(Frame fr) { String[] names = fr.names().clone(); Vec[] en = fr.remove(new int[]{1,4,5,8}); fr.add(names[1], en[0].toEnum()); //CAPSULE fr.add(names[4], en[1].toEnum()); //DPROS fr.add(names[5], en[2].toEnum()); //DCAPS fr.add(names[8], en[3].toEnum()); //GLEASON for (Vec v : en) v.remove(); fr.remove(0).remove(); //drop ID return 4; //CAPSULE } }, 4, //ntrees 2, //bins 1, //min_rows 1, //max_depth null, s("0", "1")); } @Test public void testAlphabet() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/gbm_test/alphabet_cattest.csv", "alphabetClassification.hex", new PrepData() { @Override int prep(Frame fr) { return fr.find("y"); } }, 1, 20, 1, 20, ard(ard(664, 0), ard(0, 702)), s("0", "1")); } @Test public void testAlphabetRegression() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/gbm_test/alphabet_cattest.csv", "alphabetRegression.hex", new PrepData() { @Override int prep(Frame fr) { return fr.find("y"); } }, 1, 20, 1, 10, 0.0); } @Ignore //1-vs-5 node discrepancy (parsing into different number of chunks?) @Test public void testAirlines() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/airlines/allyears2k_headers.zip", "airlines.hex", new PrepData() { @Override int prep(Frame fr) { for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { fr.remove(s).remove(); } return fr.find("IsDepDelayed"); } }, 7, 20, 1, 20, ard(ard(7958, 11707), //1-node ard(2709, 19024)), // a(a(7841, 11822), //5-node // a(2666, 19053)), s("NO", "YES")); } // Put response as the last vector in the frame and return possible frames to clean up later // Also fill DRF. static Vec unifyFrame(DRFModel.DRFParameters drf, Frame fr, PrepData prep, boolean classification) { int idx = prep.prep(fr); if( idx < 0 ) { idx = ~idx; } String rname = fr._names[idx]; drf._response_column = fr.names()[idx]; Vec resp = fr.vecs()[idx]; Vec ret = null; if (classification) { ret = fr.remove(idx); fr.add(rname,resp.toEnum()); } else { fr.remove(idx); fr.add(rname,resp); } return ret; } public void basicDRFTestOOBE_Classification(String fnametrain, String hexnametrain, PrepData prep, int ntree, int nbins, int min_rows, int max_depth, double[][] expCM, String[] expRespDom) throws Throwable { basicDRF(fnametrain, hexnametrain, null, prep, ntree, max_depth, nbins, true, min_rows, expCM, -1, expRespDom); } public void basicDRFTestOOBE_Regression(String fnametrain, String hexnametrain, PrepData prep, int ntree, int nbins, int min_rows, int max_depth, double expMSE) throws Throwable { basicDRF(fnametrain, hexnametrain, null, prep, ntree, max_depth, nbins, false, min_rows, null, expMSE, null); } public void basicDRF(String fnametrain, String hexnametrain, String fnametest, PrepData prep, int ntree, int max_depth, int nbins, boolean classification, int min_rows, double[][] expCM, double expMSE, String[] expRespDom) throws Throwable { Scope.enter(); DRFModel.DRFParameters drf = new DRFModel.DRFParameters(); Frame frTest = null, pred = null; Frame frTrain = null; Frame test = null, res = null; DRFModel model = null; try { frTrain = parse_test_file(fnametrain); Vec removeme = unifyFrame(drf, frTrain, prep, classification); if (removeme != null) Scope.track(removeme._key); DKV.put(frTrain._key, frTrain); // Configure DRF drf._train = frTrain._key; drf._response_column = ((Frame)DKV.getGet(drf._train)).lastVecName(); drf._ntrees = ntree; drf._max_depth = max_depth; drf._min_rows = min_rows; // drf._binomial_double_trees = new Random().nextBoolean(); drf._nbins = nbins; drf._nbins_cats = nbins; drf._mtries = -1; drf._sample_rate = 0.66667f; // Simulated sampling with replacement drf._seed = (1L<<32)|2; drf._model_id = Key.make("DRF_model_4_" + hexnametrain); // Invoke DRF and block till the end DRF job = null; try { job = new DRF(drf); // Get the model model = job.trainModel().get(); Log.info(model._output); } finally { if (job != null) job.remove(); } Assert.assertTrue(job._state == water.Job.JobState.DONE); //HEX-1817 hex.ModelMetrics mm; if (fnametest != null) { frTest = parse_test_file(fnametest); pred = model.score(frTest); mm = hex.ModelMetrics.getFromDKV(model, frTest); // Check test set CM } else { mm = hex.ModelMetrics.getFromDKV(model, frTrain); } Assert.assertEquals("Number of trees differs!", ntree, model._output._ntrees); test = parse_test_file(fnametrain); res = model.score(test); // Build a POJO, validate same results Assert.assertTrue(model.testJavaScoring(test,res,1e-15)); if (classification && expCM != null) { Assert.assertTrue("Expected: " + Arrays.deepToString(expCM) + ", Got: " + Arrays.deepToString(mm.cm()._cm), Arrays.deepEquals(mm.cm()._cm, expCM)); String[] cmDom = model._output._domains[model._output._domains.length - 1]; Assert.assertArrayEquals("CM domain differs!", expRespDom, cmDom); Log.info("\nOOB Training CM:\n" + mm.cm().toASCII()); Log.info("\nTraining CM:\n" + hex.ModelMetrics.getFromDKV(model, test).cm().toASCII()); } else if (!classification) { Assert.assertTrue("Expected: " + expMSE + ", Got: " + mm.mse(), expMSE == mm.mse()); Log.info("\nOOB Training MSE: " + mm.mse()); Log.info("\nTraining MSE: " + hex.ModelMetrics.getFromDKV(model, test).mse()); } hex.ModelMetrics.getFromDKV(model, test); } finally { if (frTrain!=null) frTrain.remove(); if (frTest!=null) frTest.remove(); if( model != null ) model.delete(); // Remove the model if( pred != null ) pred.delete(); if( test != null ) test.delete(); if( res != null ) res.delete(); Scope.exit(); } } // HEXDEV-194 Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters @Test public void testReproducibility() { Frame tfr=null; final int N = 5; double[] mses = new double[N]; Scope.enter(); try { // Load data, hack frames tfr = parse_test_file("smalldata/covtype/covtype.20k.data"); // rebalance to 256 chunks Key dest = Key.make("df.rebalanced.hex"); RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256); H2O.submitTask(rb); rb.join(); tfr.delete(); tfr = DKV.get(dest).get(); // Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key); // DKV.put(tfr); for (int i=0; i<N; ++i) { DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "C55"; parms._nbins = 1000; parms._ntrees = 1; parms._max_depth = 8; parms._mtries = -1; parms._min_rows = 10; parms._seed = 1234; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); DRFModel drf = job.trainModel().get(); assertEquals(drf._output._ntrees, parms._ntrees); mses[i] = drf._output._scored_train[drf._output._scored_train.length-1]._mse; job.remove(); drf.delete(); } } finally{ if (tfr != null) tfr.remove(); } Scope.exit(); for (int i=0; i<mses.length; ++i) { Log.info("trial: " + i + " -> MSE: " + mses[i]); } for(double mse : mses) assertEquals(mse, mses[0], 1e-15); } // PUBDEV-557 Test dependency on # nodes (for small number of bins, but fixed number of chunks) @Test public void testReprodubilityAirline() { Frame tfr=null; final int N = 1; double[] mses = new double[N]; Scope.enter(); try { // Load data, hack frames tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip"); // rebalance to fixed number of chunks Key dest = Key.make("df.rebalanced.hex"); RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256); H2O.submitTask(rb); rb.join(); tfr.delete(); tfr = DKV.get(dest).get(); // Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key); // DKV.put(tfr); for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { tfr.remove(s).remove(); } DKV.put(tfr); for (int i=0; i<N; ++i) { DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "IsDepDelayed"; parms._nbins = 10; parms._nbins_cats = 1024; parms._ntrees = 7; parms._max_depth = 10; parms._binomial_double_trees = false; parms._mtries = -1; parms._min_rows = 1; parms._sample_rate = 0.632f; // Simulated sampling with replacement parms._balance_classes = true; parms._seed = (1L<<32)|2; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); DRFModel drf = job.trainModel().get(); assertEquals(drf._output._ntrees, parms._ntrees); mses[i] = drf._output._training_metrics.mse(); job.remove(); drf.delete(); } } finally{ if (tfr != null) tfr.remove(); } Scope.exit(); for (int i=0; i<mses.length; ++i) { Log.info("trial: " + i + " -> MSE: " + mses[i]); } for (int i=0; i<mses.length; ++i) { assertEquals(0.20934191392060025, mses[i], 1e-4); //check for the same result on 1 nodes and 5 nodes } } // HEXDEV-319 @Ignore @Test public void testAirline() { Frame tfr=null; Frame test=null; Scope.enter(); try { // Load data, hack frames tfr = parse_test_file(Key.make("air.hex"), "/users/arno/sz_bench_data/train-1m.csv"); test = parse_test_file(Key.make("airt.hex"), "/users/arno/sz_bench_data/test.csv"); // for (int i : new int[]{0,1,2}) { // tfr.vecs()[i] = tfr.vecs()[i].toEnum(); // test.vecs()[i] = test.vecs()[i].toEnum(); // } DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._valid = test._key; parms._ignored_columns = new String[]{"Origin","Dest"}; // parms._ignored_columns = new String[]{"UniqueCarrier","Origin","Dest"}; // parms._ignored_columns = new String[]{"UniqueCarrier","Origin"}; // parms._ignored_columns = new String[]{"Month","DayofMonth","DayOfWeek","DepTime","UniqueCarrier","Origin","Distance"}; parms._response_column = "dep_delayed_15min"; parms._nbins = 20; parms._nbins_cats = 1024; parms._binomial_double_trees = new Random().nextBoolean(); //doesn't matter! parms._ntrees = 1; parms._max_depth = 3; parms._mtries = -1; parms._sample_rate = 0.632f; parms._min_rows = 10; parms._seed = 12; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); DRFModel drf = job.trainModel().get(); Log.info("Training set AUC: " + drf._output._training_metrics.auc()._auc); Log.info("Validation set AUC: " + drf._output._validation_metrics.auc()._auc); // all numerical assertEquals(drf._output._training_metrics.auc()._auc, 0.6498819479528417, 1e-8); assertEquals(drf._output._validation_metrics.auc()._auc, 0.6479974533672835, 1e-8); job.remove(); drf.delete(); } finally{ if (tfr != null) tfr.remove(); if (test != null) test.remove(); } Scope.exit(); } static double _AUC = 0.9285714285714285; static double _MSE = 0.07692307692307693; static double _R2 = 0.6904761904761905; static double _LogLoss = 2.656828953454668; @Test public void testNoRowWeights() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/no_weights.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._seed = 234; parms._min_rows = 1; parms._max_depth = 2; parms._ntrees = 3; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); // OOB ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics; assertEquals(_AUC, mm.auc()._auc, 1e-8); assertEquals(_MSE, mm.mse(), 1e-8); assertEquals(_R2, mm.r2(), 1e-6); assertEquals(_LogLoss, mm.logloss(), 1e-6); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.remove(); Scope.exit(); } } @Test public void testRowWeightsOne() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/weights_all_ones.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._weights_column = "weight"; parms._seed = 234; parms._min_rows = 1; parms._max_depth = 2; parms._ntrees = 3; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); // OOB ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics; assertEquals(_AUC, mm.auc()._auc, 1e-8); assertEquals(_MSE, mm.mse(), 1e-8); assertEquals(_R2, mm.r2(), 1e-6); assertEquals(_LogLoss, mm.logloss(), 1e-6); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Test public void testRowWeightsTwo() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/weights_all_twos.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._weights_column = "weight"; parms._seed = 234; parms._min_rows = 2; //in terms of weighted rows parms._max_depth = 2; parms._ntrees = 3; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); // OOB ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics; assertEquals(_AUC, mm.auc()._auc, 1e-8); assertEquals(_MSE, mm.mse(), 1e-8); assertEquals(_R2, mm.r2(), 1e-6); assertEquals(_LogLoss, mm.logloss(), 1e-6); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Ignore @Test public void testRowWeightsTiny() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/weights_all_tiny.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._weights_column = "weight"; parms._seed = 234; parms._min_rows = 0.01242; // in terms of weighted rows parms._max_depth = 2; parms._ntrees = 3; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); // OOB ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics; assertEquals(_AUC, mm.auc()._auc, 1e-8); assertEquals(_MSE, mm.mse(), 1e-8); assertEquals(_R2, mm.r2(), 1e-6); assertEquals(_LogLoss, mm.logloss(), 1e-6); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Test public void testNoRowWeightsShuffled() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/no_weights_shuffled.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._seed = 234; parms._min_rows = 1; parms._max_depth = 2; parms._ntrees = 3; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); // OOB // Shuffling changes the row sampling -> results differ ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics; assertEquals(0.975, mm.auc()._auc, 1e-8); assertEquals(0.09254807692307693, mm.mse(), 1e-8); assertEquals(0.6089843749999999, mm.r2(), 1e-6); assertEquals(0.24567709133200652, mm.logloss(), 1e-6); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Test public void testRowWeights() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/weights.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._weights_column = "weight"; parms._seed = 234; parms._min_rows = 1; parms._max_depth = 2; parms._ntrees = 3; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); // OOB // Reduced number of rows changes the row sampling -> results differ ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics; assertEquals(0.9, mm.auc()._auc, 1e-8); assertEquals(0.09090909090909091, mm.mse(), 1e-8); assertEquals(0.6333333333333333, mm.r2(), 1e-6); assertEquals(3.1398887631736985, mm.logloss(), 1e-6); // test set scoring (on the same dataset, but without normalizing the weights) drf.score(parms.train()); hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(drf, parms.train()); // Non-OOB assertEquals(1, mm2.auc()._auc, 1e-8); assertEquals(0.006172839506172841, mm2.mse(), 1e-8); assertEquals(0.9753086419753086, mm2.r2(), 1e-8); assertEquals(0.02252583933934247, mm2.logloss(), 1e-8); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Ignore @Test public void testNFold() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip"); for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { tfr.remove(s).remove(); } DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "IsDepDelayed"; parms._seed = 234; parms._min_rows = 2; parms._nfolds = 3; parms._max_depth = 5; parms._ntrees = 5; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._cross_validation_metrics; assertEquals(0.7276154565296726, mm.auc()._auc, 1e-8); // 1 node assertEquals(0.21211607823987555, mm.mse(), 1e-8); assertEquals(0.14939930970822446, mm.r2(), 1e-6); assertEquals(0.6121968624307211, mm.logloss(), 1e-6); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Test public void testNFoldBalanceClasses() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip"); for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { tfr.remove(s).remove(); } DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "IsDepDelayed"; parms._seed = 234; parms._min_rows = 2; parms._nfolds = 3; parms._max_depth = 5; parms._balance_classes = true; parms._ntrees = 5; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); drf = job.trainModel().get(); job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Test public void testNfoldsOneVsRest() { Frame tfr = null; DRFModel drf1 = null; DRFModel drf2 = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/weights.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "response"; parms._seed = 9999; parms._min_rows = 2; parms._nfolds = (int) tfr.numRows(); parms._fold_assignment = Model.Parameters.FoldAssignmentScheme.Modulo; parms._max_depth = 5; parms._ntrees = 5; DRF job1 = new DRF(parms); drf1 = job1.trainModel().get(); // parms._nfolds = (int) tfr.numRows() + 1; //this is now an error DRF job2 = new DRF(parms); drf2 = job2.trainModel().get(); ModelMetricsBinomial mm1 = (ModelMetricsBinomial)drf1._output._cross_validation_metrics; ModelMetricsBinomial mm2 = (ModelMetricsBinomial)drf2._output._cross_validation_metrics; assertEquals(mm1.auc()._auc, mm2.auc()._auc, 1e-12); assertEquals(mm1.mse(), mm2.mse(), 1e-12); assertEquals(mm1.r2(), mm2.r2(), 1e-12); assertEquals(mm1.logloss(), mm2.logloss(), 1e-12); //TODO: add check: the correct number of individual models were built. PUBDEV-1690 job1.remove(); job2.remove(); } finally { if (tfr != null) tfr.remove(); if (drf1 != null) drf1.delete(); if (drf2 != null) drf2.delete(); Scope.exit(); } } @Test public void testNfoldsInvalidValues() { Frame tfr = null; DRFModel drf1 = null; DRFModel drf2 = null; DRFModel drf3 = null; Scope.enter(); try { tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip"); for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { tfr.remove(s).remove(); } DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "IsDepDelayed"; parms._seed = 234; parms._min_rows = 2; parms._max_depth = 5; parms._ntrees = 5; parms._nfolds = 0; DRF job1 = new DRF(parms); drf1 = job1.trainModel().get(); parms._nfolds = 1; DRF job2 = new DRF(parms); try { Log.info("Trying nfolds==1."); drf2 = job2.trainModel().get(); Assert.fail("Should toss H2OModelBuilderIllegalArgumentException instead of reaching here"); } catch(H2OModelBuilderIllegalArgumentException e) {} parms._nfolds = -99; DRF job3 = new DRF(parms); try { Log.info("Trying nfolds==-99."); drf3 = job3.trainModel().get(); Assert.fail("Should toss H2OModelBuilderIllegalArgumentException instead of reaching here"); } catch(H2OModelBuilderIllegalArgumentException e) {} job1.remove(); job2.remove(); job3.remove(); } finally { if (tfr != null) tfr.remove(); if (drf1 != null) drf1.delete(); if (drf2 != null) drf2.delete(); if (drf3 != null) drf3.delete(); Scope.exit(); } } @Test public void testNfoldsCVAndValidation() { Frame tfr = null, vfr = null; DRFModel drf = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/weights.csv"); vfr = parse_test_file("smalldata/junit/weights.csv"); DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._valid = vfr._key; parms._response_column = "response"; parms._min_rows = 2; parms._max_depth = 2; parms._nfolds = 2; parms._ntrees = 3; parms._seed = 11233; DRF job = new DRF(parms); try { Log.info("Trying N-fold cross-validation AND Validation dataset provided."); drf = job.trainModel().get(); } catch(H2OModelBuilderIllegalArgumentException e) { Assert.fail("Should not toss H2OModelBuilderIllegalArgumentException."); } job.remove(); } finally { if (tfr != null) tfr.remove(); if (vfr != null) vfr.remove(); if (drf != null) drf.delete(); Scope.exit(); } } @Test public void testNfoldsConsecutiveModelsSame() { Frame tfr = null; Vec old = null; DRFModel drf1 = null; DRFModel drf2 = null; Scope.enter(); try { tfr = parse_test_file("smalldata/junit/cars_20mpg.csv"); tfr.remove("name").remove(); // Remove unique id tfr.remove("economy").remove(); old = tfr.remove("economy_20mpg"); tfr.add("economy_20mpg", old.toEnum()); // response to last column DKV.put(tfr); DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "economy_20mpg"; parms._min_rows = 2; parms._max_depth = 2; parms._nfolds = 3; parms._ntrees = 3; parms._seed = 77777; DRF job1 = new DRF(parms); drf1 = job1.trainModel().get(); DRF job2 = new DRF(parms); drf2 = job2.trainModel().get(); ModelMetricsBinomial mm1 = (ModelMetricsBinomial)drf1._output._cross_validation_metrics; ModelMetricsBinomial mm2 = (ModelMetricsBinomial)drf2._output._cross_validation_metrics; assertEquals(mm1.auc()._auc, mm2.auc()._auc, 1e-12); assertEquals(mm1.mse(), mm2.mse(), 1e-12); assertEquals(mm1.r2(), mm2.r2(), 1e-12); assertEquals(mm1.logloss(), mm2.logloss(), 1e-12); job1.remove(); job2.remove(); } finally { if (tfr != null) tfr.remove(); if (old != null) old.remove(); if (drf1 != null) drf1.delete(); if (drf2 != null) drf2.delete(); Scope.exit(); } } }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * A request message for Routers.Get. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetRouterRequest} */ public final class GetRouterRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetRouterRequest) GetRouterRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetRouterRequest.newBuilder() to construct. private GetRouterRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetRouterRequest() { project_ = ""; region_ = ""; router_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GetRouterRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private GetRouterRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 1111570338: { java.lang.String s = input.readStringRequireUtf8(); region_ = s; break; } case 1188870730: { java.lang.String s = input.readStringRequireUtf8(); router_ = s; break; } case 1820481738: { java.lang.String s = input.readStringRequireUtf8(); project_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetRouterRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetRouterRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetRouterRequest.class, com.google.cloud.compute.v1.GetRouterRequest.Builder.class); } public static final int PROJECT_FIELD_NUMBER = 227560217; private volatile java.lang.Object project_; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REGION_FIELD_NUMBER = 138946292; private volatile java.lang.Object region_; /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The region. */ @java.lang.Override public java.lang.String getRegion() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } } /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for region. */ @java.lang.Override public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ROUTER_FIELD_NUMBER = 148608841; private volatile java.lang.Object router_; /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The router. */ @java.lang.Override public java.lang.String getRouter() { java.lang.Object ref = router_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); router_ = s; return s; } } /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for router. */ @java.lang.Override public com.google.protobuf.ByteString getRouterBytes() { java.lang.Object ref = router_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); router_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(router_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 148608841, router_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(router_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(148608841, router_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.GetRouterRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.GetRouterRequest other = (com.google.cloud.compute.v1.GetRouterRequest) obj; if (!getProject().equals(other.getProject())) return false; if (!getRegion().equals(other.getRegion())) return false; if (!getRouter().equals(other.getRouter())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); hash = (37 * hash) + REGION_FIELD_NUMBER; hash = (53 * hash) + getRegion().hashCode(); hash = (37 * hash) + ROUTER_FIELD_NUMBER; hash = (53 * hash) + getRouter().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.GetRouterRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetRouterRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetRouterRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.compute.v1.GetRouterRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A request message for Routers.Get. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetRouterRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetRouterRequest) com.google.cloud.compute.v1.GetRouterRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetRouterRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetRouterRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetRouterRequest.class, com.google.cloud.compute.v1.GetRouterRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.GetRouterRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); project_ = ""; region_ = ""; router_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetRouterRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.GetRouterRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.GetRouterRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.GetRouterRequest build() { com.google.cloud.compute.v1.GetRouterRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.GetRouterRequest buildPartial() { com.google.cloud.compute.v1.GetRouterRequest result = new com.google.cloud.compute.v1.GetRouterRequest(this); result.project_ = project_; result.region_ = region_; result.router_ = router_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.GetRouterRequest) { return mergeFrom((com.google.cloud.compute.v1.GetRouterRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.GetRouterRequest other) { if (other == com.google.cloud.compute.v1.GetRouterRequest.getDefaultInstance()) return this; if (!other.getProject().isEmpty()) { project_ = other.project_; onChanged(); } if (!other.getRegion().isEmpty()) { region_ = other.region_; onChanged(); } if (!other.getRouter().isEmpty()) { router_ = other.router_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.compute.v1.GetRouterRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.GetRouterRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; onChanged(); return this; } private java.lang.Object region_ = ""; /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The region. */ public java.lang.String getRegion() { java.lang.Object ref = region_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for region. */ public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The region to set. * @return This builder for chaining. */ public Builder setRegion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } region_ = value; onChanged(); return this; } /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearRegion() { region_ = getDefaultInstance().getRegion(); onChanged(); return this; } /** * * * <pre> * Name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for region to set. * @return This builder for chaining. */ public Builder setRegionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); region_ = value; onChanged(); return this; } private java.lang.Object router_ = ""; /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The router. */ public java.lang.String getRouter() { java.lang.Object ref = router_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); router_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for router. */ public com.google.protobuf.ByteString getRouterBytes() { java.lang.Object ref = router_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); router_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The router to set. * @return This builder for chaining. */ public Builder setRouter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } router_ = value; onChanged(); return this; } /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearRouter() { router_ = getDefaultInstance().getRouter(); onChanged(); return this; } /** * * * <pre> * Name of the Router resource to return. * </pre> * * <code>string router = 148608841 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for router to set. * @return This builder for chaining. */ public Builder setRouterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); router_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.GetRouterRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetRouterRequest) private static final com.google.cloud.compute.v1.GetRouterRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetRouterRequest(); } public static com.google.cloud.compute.v1.GetRouterRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetRouterRequest> PARSER = new com.google.protobuf.AbstractParser<GetRouterRequest>() { @java.lang.Override public GetRouterRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new GetRouterRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<GetRouterRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetRouterRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.GetRouterRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright (c) Facebook, Inc. and 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 com.facebook.buck.versions; import com.facebook.buck.core.cell.Cells; import com.facebook.buck.core.cell.nameresolver.CellNameResolver; import com.facebook.buck.core.description.arg.ConstructorArg; import com.facebook.buck.core.model.BaseName; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.targetgraph.TargetNode; import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.SourceWithFlags; import com.facebook.buck.rules.coercer.DataTransferObjectDescriptor; import com.facebook.buck.rules.coercer.ParamInfo; import com.facebook.buck.rules.coercer.TypeCoercerFactory; import com.facebook.buck.util.types.Pair; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import java.util.Map; import java.util.Optional; /** * A helper class which uses reflection to translate {@link BuildTarget}s in {@link TargetNode}s. * The API methods use an {@link Optional} for their return types, so that {@link Optional#empty()} * can be used to signify a translation was not needed. This may allow some translation functions to * avoid copying or creating unnecessary new objects. */ public abstract class TargetNodeTranslator { private final TypeCoercerFactory typeCoercerFactory; // Translators registered for various types. private final ImmutableList<TargetTranslator<?>> translators; private final Cells cells; public TargetNodeTranslator( TypeCoercerFactory typeCoercerFactory, ImmutableList<TargetTranslator<?>> translators, Cells cells) { this.typeCoercerFactory = typeCoercerFactory; this.translators = translators; this.cells = cells; } public abstract Optional<BuildTarget> translateBuildTarget(BuildTarget target); public abstract Optional<ImmutableMap<BuildTarget, Version>> getSelectedVersions( BuildTarget target); private <A> Optional<Optional<A>> translateOptional( CellNameResolver cellNameResolver, BaseName targetBaseName, Optional<A> val) { if (!val.isPresent()) { return Optional.empty(); } Optional<A> inner = translate(cellNameResolver, targetBaseName, val.get()); if (!inner.isPresent()) { return Optional.empty(); } return Optional.of(inner); } private <A> Optional<ImmutableList<A>> translateList( CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableList<A> val) { boolean modified = false; ImmutableList.Builder<A> builder = ImmutableList.builder(); for (A a : val) { Optional<A> item = translate(cellNameResolver, targetBaseName, a); modified = modified || item.isPresent(); builder.add(item.orElse(a)); } return modified ? Optional.of(builder.build()) : Optional.empty(); } private <A> Optional<ImmutableSet<A>> translateSet( CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSet<A> val) { boolean modified = false; ImmutableSet.Builder<A> builder = ImmutableSet.builder(); for (A a : val) { Optional<A> item = translate(cellNameResolver, targetBaseName, a); modified = modified || item.isPresent(); builder.add(item.orElse(a)); } return modified ? Optional.of(builder.build()) : Optional.empty(); } private <A extends Comparable<?>> Optional<ImmutableSortedSet<A>> translateSortedSet( CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSortedSet<A> val) { boolean modified = false; ImmutableSortedSet.Builder<A> builder = ImmutableSortedSet.naturalOrder(); for (A a : val) { Optional<A> item = translate(cellNameResolver, targetBaseName, a); modified = modified || item.isPresent(); builder.add(item.orElse(a)); } return modified ? Optional.of(builder.build()) : Optional.empty(); } private <A extends Comparable<?>, B> Optional<ImmutableMap<A, B>> translateMap( CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableMap<A, B> val) { boolean modified = false; ImmutableMap.Builder<A, B> builder = ImmutableMap.builder(); for (Map.Entry<A, B> ent : val.entrySet()) { Optional<A> key = translate(cellNameResolver, targetBaseName, ent.getKey()); Optional<B> value = translate(cellNameResolver, targetBaseName, ent.getValue()); modified = modified || key.isPresent() || value.isPresent(); builder.put(key.orElse(ent.getKey()), value.orElse(ent.getValue())); } return modified ? Optional.of(builder.build()) : Optional.empty(); } private <A extends Comparable<?>, B> Optional<ImmutableSortedMap<A, B>> translateSortedMap( CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSortedMap<A, B> val) { boolean modified = false; ImmutableSortedMap.Builder<A, B> builder = ImmutableSortedMap.naturalOrder(); for (Map.Entry<A, B> ent : val.entrySet()) { Optional<A> key = translate(cellNameResolver, targetBaseName, ent.getKey()); Optional<B> value = translate(cellNameResolver, targetBaseName, ent.getValue()); modified = modified || key.isPresent() || value.isPresent(); builder.put(key.orElse(ent.getKey()), value.orElse(ent.getValue())); } return modified ? Optional.of(builder.build()) : Optional.empty(); } @VisibleForTesting <A, B> Optional<Pair<A, B>> translatePair( CellNameResolver cellNameResolver, BaseName targetBaseName, Pair<A, B> val) { Optional<A> first = translate(cellNameResolver, targetBaseName, val.getFirst()); Optional<B> second = translate(cellNameResolver, targetBaseName, val.getSecond()); if (!first.isPresent() && !second.isPresent()) { return Optional.empty(); } return Optional.of(new Pair<>(first.orElse(val.getFirst()), second.orElse(val.getSecond()))); } @VisibleForTesting Optional<DefaultBuildTargetSourcePath> translateBuildTargetSourcePath( CellNameResolver cellNameResolver, BaseName targetBaseName, DefaultBuildTargetSourcePath val) { BuildTarget target = val.getTarget(); Optional<BuildTarget> translatedTarget = translate(cellNameResolver, targetBaseName, target); return translatedTarget.map(DefaultBuildTargetSourcePath::of); } @VisibleForTesting Optional<SourceWithFlags> translateSourceWithFlags( CellNameResolver cellNameResolver, BaseName targetBaseName, SourceWithFlags val) { Optional<SourcePath> translatedSourcePath = translate(cellNameResolver, targetBaseName, val.getSourcePath()); return translatedSourcePath.map(sourcePath -> SourceWithFlags.of(sourcePath, val.getFlags())); } @SuppressWarnings("unchecked") private <A, T> Optional<Optional<T>> tryTranslate( CellNameResolver cellPathResolver, BaseName targetBaseName, TargetTranslator<A> translator, T object) { Class<A> clazz = translator.getTranslatableClass(); if (!clazz.isAssignableFrom(object.getClass())) { return Optional.empty(); } return Optional.of( (Optional<T>) translator.translateTargets(cellPathResolver, targetBaseName, this, (A) object)); } @SuppressWarnings("unchecked") public <A> Optional<A> translate( CellNameResolver cellNameResolver, BaseName targetBaseName, A object) { // `null`s require no translating. if (object == null) { return Optional.empty(); } // First try all registered translators. for (TargetTranslator<?> translator : translators) { if (translator.getTranslatableClass().isAssignableFrom(object.getClass())) { Optional<Optional<A>> translated = tryTranslate(cellNameResolver, targetBaseName, translator, object); if (translated.isPresent()) { return translated.get(); } } } if (object instanceof Optional) { return (Optional<A>) translateOptional(cellNameResolver, targetBaseName, (Optional<?>) object); } else if (object instanceof ImmutableList) { return (Optional<A>) translateList(cellNameResolver, targetBaseName, (ImmutableList<?>) object); } else if (object instanceof ImmutableSortedSet) { return (Optional<A>) translateSortedSet( cellNameResolver, targetBaseName, (ImmutableSortedSet<? extends Comparable<?>>) object); } else if (object instanceof ImmutableSet) { return (Optional<A>) translateSet(cellNameResolver, targetBaseName, (ImmutableSet<?>) object); } else if (object instanceof ImmutableSortedMap) { return (Optional<A>) translateSortedMap( cellNameResolver, targetBaseName, (ImmutableSortedMap<? extends Comparable<?>, ?>) object); } else if (object instanceof ImmutableMap) { return (Optional<A>) translateMap( cellNameResolver, targetBaseName, (ImmutableMap<? extends Comparable<?>, ?>) object); } else if (object instanceof Pair) { return (Optional<A>) translatePair(cellNameResolver, targetBaseName, (Pair<?, ?>) object); } else if (object instanceof DefaultBuildTargetSourcePath) { return (Optional<A>) translateBuildTargetSourcePath( cellNameResolver, targetBaseName, (DefaultBuildTargetSourcePath) object); } else if (object instanceof SourceWithFlags) { return (Optional<A>) translateSourceWithFlags(cellNameResolver, targetBaseName, (SourceWithFlags) object); } else if (object instanceof BuildTarget) { return (Optional<A>) translateBuildTarget((BuildTarget) object); } else if (object instanceof TargetTranslatable) { TargetTranslatable<A> targetTranslatable = (TargetTranslatable<A>) object; return targetTranslatable.translateTargets(cellNameResolver, targetBaseName, this); } else { return Optional.empty(); } } private boolean translateConstructorArg( CellNameResolver cellNameResolver, BaseName targetBaseName, ConstructorArg constructorArg, Object newConstructorArgOrBuilder) { boolean modified = false; for (ParamInfo<?> param : typeCoercerFactory .getConstructorArgDescriptor(constructorArg.getClass()) .getParamInfos() .values()) { Object value = param.get(constructorArg); Optional<Object> newValue = translate(cellNameResolver, targetBaseName, value); modified |= newValue.isPresent(); param.setCoercedValue(newConstructorArgOrBuilder, newValue.orElse(value)); } return modified; } private <A extends ConstructorArg> Optional<A> translateConstructorArg( BaseName targetBaseName, TargetNode<A> node) { CellNameResolver cellNameResolver = cells.getCell(node.getBuildTarget().getCell()).getCellNameResolver(); A constructorArg = node.getConstructorArg(); DataTransferObjectDescriptor<A> newArgAndBuild = typeCoercerFactory.getConstructorArgDescriptor( node.getDescription().getConstructorArgType()); Object builder = newArgAndBuild.getBuilderFactory().get(); boolean modified = translateConstructorArg(cellNameResolver, targetBaseName, constructorArg, builder); if (!modified) { return Optional.empty(); } return Optional.of(newArgAndBuild.build(builder, node.getBuildTarget())); } /** * @return a copy of the given {@link TargetNode} with all found {@link BuildTarget}s translated, * or {@link Optional#empty()} if the node requires no translation. */ public <A extends ConstructorArg> Optional<TargetNode<A>> translateNode(TargetNode<A> node) { CellNameResolver cellNameResolver = cells.getCell(node.getBuildTarget().getCell()).getCellNameResolver(); BaseName targetBaseName = node.getBuildTarget().getBaseName(); Optional<BuildTarget> target = translateBuildTarget(node.getBuildTarget()); Optional<A> constructorArg = translateConstructorArg(targetBaseName, node); Optional<ImmutableSet<BuildTarget>> declaredDeps = translateSet(cellNameResolver, targetBaseName, node.getDeclaredDeps()); Optional<ImmutableSortedSet<BuildTarget>> extraDeps = translateSortedSet(cellNameResolver, targetBaseName, node.getExtraDeps()); Optional<ImmutableSortedSet<BuildTarget>> targetGraphOnlyDeps = translateSortedSet(cellNameResolver, targetBaseName, node.getTargetGraphOnlyDeps()); Optional<ImmutableMap<BuildTarget, Version>> newSelectedVersions = getSelectedVersions(node.getBuildTarget()); Optional<ImmutableMap<BuildTarget, Version>> oldSelectedVersions = node.getSelectedVersions(); Optional<Optional<ImmutableMap<BuildTarget, Version>>> selectedVersions = oldSelectedVersions.equals(newSelectedVersions) ? Optional.empty() : Optional.of(newSelectedVersions); // If nothing has changed, don't generate a new node. if (!target.isPresent() && !constructorArg.isPresent() && !declaredDeps.isPresent() && !extraDeps.isPresent() && !targetGraphOnlyDeps.isPresent() && !selectedVersions.isPresent()) { return Optional.empty(); } return Optional.of( node.withBuildTarget(target.orElse(node.getBuildTarget())) .withConstructorArg(constructorArg.orElse(node.getConstructorArg())) .withDeclaredDeps(declaredDeps.orElse(node.getDeclaredDeps())) .withExtraDeps(extraDeps.orElse(node.getExtraDeps())) .withTargetGraphOnlyDeps(targetGraphOnlyDeps.orElse(node.getTargetGraphOnlyDeps())) .withSelectedVersions(selectedVersions.orElse(oldSelectedVersions))); } }
/* * Copyright 2016 Phil Shadlyn * * 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.physphil.android.unitconverterultimate.fragments; import android.content.ClipData; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.ViewFlipper; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.physphil.android.unitconverterultimate.BuildConfig; import com.physphil.android.unitconverterultimate.R; import com.physphil.android.unitconverterultimate.UnitConverterApplication; import com.physphil.android.unitconverterultimate.data.DataAccess; import com.physphil.android.unitconverterultimate.models.Conversion; import com.physphil.android.unitconverterultimate.models.ConversionState; import com.physphil.android.unitconverterultimate.models.Unit; import com.physphil.android.unitconverterultimate.presenters.ConversionPresenter; import com.physphil.android.unitconverterultimate.presenters.ConversionView; import com.physphil.android.unitconverterultimate.settings.Preferences; import com.physphil.android.unitconverterultimate.settings.PreferencesActivity; import com.physphil.android.unitconverterultimate.util.Conversions; import com.physphil.android.unitconverterultimate.util.IntentFactory; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import androidx.annotation.Nullable; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; /** * Base fragment to display units to convert * Created by Phizz on 15-07-28. */ public final class ConversionFragment extends Fragment implements ConversionView, SharedPreferences.OnSharedPreferenceChangeListener, RadioGroup.OnCheckedChangeListener { private static final String ARGS_CONVERSION_ID = "conversion_id"; private ConversionPresenter mPresenter; private RadioGroup mGrpFrom, mGrpTo; private EditText mTxtValue, mTxtResult; private ProgressBar mProgressSpinner; private TextView mProgressText, mTxtUnitFrom, mTxtUnitTo; private ViewFlipper mFlipper; private CoordinatorLayout mCoordinatorLayout; private int mConversionId, mIndexConversion, mIndexProgress; private double mResult; private Preferences mPrefs; private ConversionState mState; private Context mAppContext; /** * Create a new ConversionFragment to display * * @param id id of the conversion it will handle * @return new ConversionFragment instance */ public static ConversionFragment newInstance(@Conversion.id int id) { ConversionFragment f = new ConversionFragment(); Bundle args = new Bundle(); args.putInt(ARGS_CONVERSION_ID, id); f.setArguments(args); return f; } @Override public void onAttach(Context context) { super.onAttach(context); Preferences.getInstance(context).getPreferences().registerOnSharedPreferenceChangeListener(this); mAppContext = context.getApplicationContext(); } @Override public void onDetach() { super.onDetach(); Preferences.getInstance(getActivity()).getPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); mConversionId = getArguments().getInt(ARGS_CONVERSION_ID, Conversion.AREA); mPresenter = new ConversionPresenter(this); mPrefs = Preferences.getInstance(getActivity()); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_conversion, container, false); mFlipper = (ViewFlipper) v.findViewById(R.id.viewflipper_conversion); mIndexConversion = mFlipper.indexOfChild(mFlipper.findViewById(R.id.conversion_container)); mIndexProgress = mFlipper.indexOfChild(mFlipper.findViewById(R.id.conversion_progress_container)); mProgressSpinner = (ProgressBar) v.findViewById(R.id.progress_circle_conversion); mProgressText = (TextView) v.findViewById(R.id.progress_text_conversion); mTxtUnitFrom = (TextView) v.findViewById(R.id.header_text_unit_from); mTxtUnitTo = (TextView) v.findViewById(R.id.header_text_unit_to); mTxtValue = (EditText) v.findViewById(R.id.header_value_from); if (savedInstanceState == null) { String value = mPrefs.getLastValue(); if (mConversionId != Conversion.TEMPERATURE) { // adjust value if it was negative coming from temperature conversion value = value.replace("-", ""); value = value.replace("+", ""); } mTxtValue.setText(value); mTxtValue.setSelection(mTxtValue.getText().length()); } // Only allow negative values for temperature if (mConversionId == Conversion.TEMPERATURE) { mTxtValue.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); } else { mTxtValue.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); } mTxtResult = (EditText) v.findViewById(R.id.header_value_to); mTxtResult.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // Copy text to clipboard android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Conversion Result", ((EditText) v).getText().toString()); clipboard.setPrimaryClip(clip); showToast(R.string.toast_copied_clipboard); return true; } }); mGrpFrom = (RadioGroup) v.findViewById(R.id.radio_group_from); mGrpTo = (RadioGroup) v.findViewById(R.id.radio_group_to); mCoordinatorLayout = (CoordinatorLayout) v.findViewById(R.id.list_coordinator_layout); FloatingActionButton fab = (FloatingActionButton) mCoordinatorLayout.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { swapUnits(); } }); return v; } @Override public void onResume() { super.onResume(); mTxtValue.addTextChangedListener(mTextWatcher); mGrpFrom.setOnCheckedChangeListener(this); mGrpTo.setOnCheckedChangeListener(this); } @Override public void onPause() { super.onPause(); mTxtValue.removeTextChangedListener(mTextWatcher); mPrefs.setLastValue(mTxtValue.getText().toString()); mPrefs.setLastConversion(mConversionId); if (mState != null) { DataAccess.getInstance(getActivity()).saveConversionState(mState); } } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); mPresenter.onGetUnitsToDisplay(mConversionId); // Takes care of restoring the ViewState after a screen rotation if (mState != null) { if (mState.getFromId() < 0 || mState.getToId() < 0) { // Empty initial state, set state from default checked buttons mState.setFromId(mGrpFrom.getCheckedRadioButtonId()); mState.setToId(mGrpTo.getCheckedRadioButtonId()); } else { // Overwrite default checked state with last saved state mGrpFrom.check(mState.getFromId()); mGrpTo.check(mState.getToId()); } mTxtUnitFrom.setText(getCheckedUnit(mGrpFrom).getLabelResource()); mTxtUnitTo.setText(getCheckedUnit(mGrpTo).getLabelResource()); } } @Override public void onDestroyView() { super.onDestroyView(); mPresenter.onDestroy(); } /** * Set radio buttons to their saved state (if any) */ public void restoreConversionState(final ConversionState state) { mState = state; if (mState.getFromId() < 0 || mState.getToId() < 0) { // Empty initial state, set state from default checked buttons mState.setFromId(mGrpFrom.getCheckedRadioButtonId()); mState.setToId(mGrpTo.getCheckedRadioButtonId()); } else { // Overwrite default checked state with last saved state mGrpFrom.check(mState.getFromId()); mGrpTo.check(mState.getToId()); } mTxtUnitFrom.setText(getCheckedUnit(mGrpFrom).getLabelResource()); mTxtUnitTo.setText(getCheckedUnit(mGrpTo).getLabelResource()); mGrpFrom.setOnCheckedChangeListener(this); mGrpTo.setOnCheckedChangeListener(this); convert(); } /** * Convert value from one unit to another */ private void convert() { // If input isn't a number yet then set to 0 String input = mTxtValue.getText().toString(); double value = isNumeric(input) ? Double.parseDouble(input) : 0; switch (mConversionId) { case Conversion.TEMPERATURE: mPresenter.convertTemperatureValue(value, getCheckedUnit(mGrpFrom), getCheckedUnit(mGrpTo)); break; case Conversion.FUEL: mPresenter.convertFuelValue(value, getCheckedUnit(mGrpFrom), getCheckedUnit(mGrpTo)); break; default: mPresenter.convert(value, getCheckedUnit(mGrpFrom), getCheckedUnit(mGrpTo)); break; } } /** * Get the Unit associated with the checked button in a radio group * * @param group RadioGroup which contains the button * @return Unit associated with checked button */ private Unit getCheckedUnit(RadioGroup group) { int id = group.getCheckedRadioButtonId(); Conversion c = Conversions.getInstance().getById(mConversionId); for (Unit unit : c.getUnits()) { if (unit.getId() == id) { return unit; } } return c.getUnits().get(0); } /** * Add units to From and To radio groups */ private void addUnits(Conversion c) { mGrpFrom.removeAllViews(); mGrpTo.removeAllViews(); RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); lp.bottomMargin = mAppContext.getResources().getDimensionPixelSize(R.dimen.margin_view_small); lp.topMargin = mAppContext.getResources().getDimensionPixelSize(R.dimen.margin_view_small); for (int i = 0; i < c.getUnits().size(); i++) { Unit u = c.getUnits().get(i); boolean fromChecked = false; boolean toChecked = false; // Set default checked state. Will be overridden later on if there is a saved state to restore if (i == 0) { fromChecked = true; } else if (i == 1) { toChecked = true; } mGrpFrom.addView(getRadioButton(u, fromChecked), lp); mGrpTo.addView(getRadioButton(u, toChecked), lp); } } /** * Retrieve the last saved ConversionState for this conversion */ private void getLastConversionState() { mPresenter.getLastConversionState(mConversionId); } /** * Create Radio Button to display in group * * @param u unit which the button represents * @param checked if the button is checked or not * @return RadioButton to display */ private RadioButton getRadioButton(Unit u, boolean checked) { RadioButton btn = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.unit_radio_button, null); btn.setId(u.getId()); btn.setTag(u); btn.setText(u.getLabelResource()); btn.setChecked(checked); return btn; } /** * Checks to see if a string contains a numeric value * * @param number string input * @return if the input is a numeric value */ private boolean isNumeric(String number) { try { double d = Double.parseDouble(number); return true; } catch (NumberFormatException e) { return false; } } /** * Get DecimalFormat used to format result * * @return DecimalFormat */ private DecimalFormat getDecimalFormat() { DecimalFormat formatter = new DecimalFormat(); //Set maximum number of decimal places formatter.setMaximumFractionDigits(mPrefs.getNumberDecimals()); //Set group and decimal separators DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); symbols.setDecimalSeparator(mPrefs.getDecimalSeparator().charAt(0)); Character groupSeparator = mPrefs.getGroupSeparator(); boolean isSeparatorUsed = groupSeparator != null; formatter.setGroupingUsed(isSeparatorUsed); if (isSeparatorUsed) { symbols.setGroupingSeparator(groupSeparator); } formatter.setDecimalFormatSymbols(symbols); return formatter; } /** * Swap units between From and To */ private void swapUnits() { int fromId = mGrpFrom.getCheckedRadioButtonId(); int toId = mGrpTo.getCheckedRadioButtonId(); // Check individual button to avoid calling OnCheckChanged listener 6 times // RadioGroup.check(id) actually fires OnCheckChanged 3 times per each button ((RadioButton) mGrpFrom.findViewById(toId)).setChecked(true); ((RadioButton) mGrpTo.findViewById(fromId)).setChecked(true); } private TextWatcher mTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { convert(); } }; @Override public void showResult(double result) { mResult = result; mTxtResult.setText(getDecimalFormat().format(result)); } @Override public void showUnitsList(Conversion conversion) { mFlipper.setDisplayedChild(mIndexConversion); addUnits(conversion); getLastConversionState(); } @Override public void showProgressCircle() { mFlipper.setDisplayedChild(mIndexProgress); mProgressSpinner.setVisibility(View.VISIBLE); mProgressText.setText(R.string.progress_loading); } @Override public void showLoadingError(int message) { mFlipper.setDisplayedChild(mIndexProgress); mProgressSpinner.setVisibility(View.GONE); mProgressText.setText(message); } @Override public void updateCurrencyConversion() { convert(); } @Override public void showToast(int message) { Snackbar sb = Snackbar.make(mCoordinatorLayout, message, Snackbar.LENGTH_LONG); sb.getView().setBackgroundResource(R.color.color_primary); sb.show(); } @Override public void showToastError(int message) { Snackbar sb = Snackbar.make(mCoordinatorLayout, message, Snackbar.LENGTH_LONG); sb.getView().setBackgroundResource(R.color.theme_red); sb.show(); } @Override public Context getContext() { return mAppContext; } // Radio Group checked change listener @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (mState != null) { Unit unit = getCheckedUnit(group); switch (group.getId()) { case R.id.radio_group_from: mState.setFromId(checkedId); mTxtUnitFrom.setText(unit.getLabelResource()); break; case R.id.radio_group_to: mState.setToId(checkedId); mTxtUnitTo.setText(unit.getLabelResource()); break; } convert(); } } // Change in shared preferences @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Preferences.PREFS_NUMBER_OF_DECIMALS) || key.equals(Preferences.PREFS_DECIMAL_SEPARATOR) || key.equals(Preferences.PREFS_GROUP_SEPARATOR_V2)) { mTxtResult.setText(getDecimalFormat().format(mResult)); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_conversion_fragment, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem download = menu.findItem(R.id.menu_download); download.setVisible(mConversionId == Conversion.CURRENCY); MenuItem donate = menu.findItem(R.id.menu_donate); donate.setVisible(BuildConfig.FLAVOR.equals(UnitConverterApplication.BUILD_FLAVOUR_GOOGLE)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_download: mPresenter.onUpdateCurrencyConversions(); return true; case R.id.menu_clear: mTxtValue.setText(""); return true; case R.id.menu_help: HelpDialogFragment.newInstance().show(getChildFragmentManager(), HelpDialogFragment.TAG); return true; case R.id.menu_settings: PreferencesActivity.start(getActivity()); return true; case R.id.menu_donate: startActivity(IntentFactory.getDonateIntent(getActivity())); default: return super.onOptionsItemSelected(item); } } }
/* ==================================================================== 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.poi.xwpf.usermodel; import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlOptions; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; /** * Holds details of built-in, default and user styles, which * apply to tables / paragraphs / lists etc. * Text within one of those with custom stylings has the style * information stored in the {@link XWPFRun} */ public class XWPFStyles extends POIXMLDocumentPart { private CTStyles ctStyles; private List<XWPFStyle> listStyle = new ArrayList<XWPFStyle>(); private XWPFLatentStyles latentStyles; private XWPFDefaultRunStyle defaultRunStyle; private XWPFDefaultParagraphStyle defaultParaStyle; /** * Construct XWPFStyles from a package part * * @param part the package part holding the data of the styles, * * @since POI 3.14-Beta1 */ public XWPFStyles(PackagePart part) throws IOException, OpenXML4JException { super(part); } /** * Construct XWPFStyles from scratch for a new document. */ public XWPFStyles() { } /** * Read document */ @Override protected void onDocumentRead() throws IOException { StylesDocument stylesDoc; InputStream is = getPackagePart().getInputStream(); try { stylesDoc = StylesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); setStyles(stylesDoc.getStyles()); latentStyles = new XWPFLatentStyles(ctStyles.getLatentStyles(), this); } catch (XmlException e) { throw new POIXMLException("Unable to read styles", e); } finally { is.close(); } } @Override protected void commit() throws IOException { if (ctStyles == null) { throw new IllegalStateException("Unable to write out styles that were never read in!"); } XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles")); PackagePart part = getPackagePart(); OutputStream out = part.getOutputStream(); ctStyles.save(out, xmlOptions); out.close(); } protected void ensureDocDefaults() { if (!ctStyles.isSetDocDefaults()) { ctStyles.addNewDocDefaults(); } CTDocDefaults docDefaults = ctStyles.getDocDefaults(); if (!docDefaults.isSetPPrDefault()) docDefaults.addNewPPrDefault(); if (!docDefaults.isSetRPrDefault()) docDefaults.addNewRPrDefault(); CTPPrDefault pprd = docDefaults.getPPrDefault(); CTRPrDefault rprd = docDefaults.getRPrDefault(); if (!pprd.isSetPPr()) pprd.addNewPPr(); if (!rprd.isSetRPr()) rprd.addNewRPr(); defaultRunStyle = new XWPFDefaultRunStyle(rprd.getRPr()); defaultParaStyle = new XWPFDefaultParagraphStyle(pprd.getPPr()); } /** * Sets the ctStyles * * @param styles */ public void setStyles(CTStyles styles) { ctStyles = styles; // Build up all the style objects for (CTStyle style : ctStyles.getStyleArray()) { listStyle.add(new XWPFStyle(style, this)); } if (ctStyles.isSetDocDefaults()) { CTDocDefaults docDefaults = ctStyles.getDocDefaults(); if (docDefaults.isSetRPrDefault() && docDefaults.getRPrDefault().isSetRPr()) { defaultRunStyle = new XWPFDefaultRunStyle( docDefaults.getRPrDefault().getRPr()); } if (docDefaults.isSetPPrDefault() && docDefaults.getPPrDefault().isSetPPr()) { defaultParaStyle = new XWPFDefaultParagraphStyle( docDefaults.getPPrDefault().getPPr()); } } } /** * checks whether style with styleID exist * * @param styleID styleID of the Style in the style-Document * @return true if style exist, false if style not exist */ public boolean styleExist(String styleID) { for (XWPFStyle style : listStyle) { if (style.getStyleId().equals(styleID)) return true; } return false; } /** * add a style to the document * * @param style * @throws IOException */ public void addStyle(XWPFStyle style) { listStyle.add(style); ctStyles.addNewStyle(); int pos = ctStyles.sizeOfStyleArray() - 1; ctStyles.setStyleArray(pos, style.getCTStyle()); } /** * Get style by a styleID * * @param styleID styleID of the searched style * @return style */ public XWPFStyle getStyle(String styleID) { for (XWPFStyle style : listStyle) { try { if (style.getStyleId().equals(styleID)) return style; } catch (NullPointerException e) { // Ignore NPE } } return null; } public int getNumberOfStyles() { return listStyle.size(); } /** * get the styles which are related to the parameter style and their relatives * this method can be used to copy all styles from one document to another document * * @param style * @return a list of all styles which were used by this method */ public List<XWPFStyle> getUsedStyleList(XWPFStyle style) { List<XWPFStyle> usedStyleList = new ArrayList<XWPFStyle>(); usedStyleList.add(style); return getUsedStyleList(style, usedStyleList); } /** * get the styles which are related to parameter style * * @param style * @return all Styles of the parameterList */ private List<XWPFStyle> getUsedStyleList(XWPFStyle style, List<XWPFStyle> usedStyleList) { String basisStyleID = style.getBasisStyleID(); XWPFStyle basisStyle = getStyle(basisStyleID); if ((basisStyle != null) && (!usedStyleList.contains(basisStyle))) { usedStyleList.add(basisStyle); getUsedStyleList(basisStyle, usedStyleList); } String linkStyleID = style.getLinkStyleID(); XWPFStyle linkStyle = getStyle(linkStyleID); if ((linkStyle != null) && (!usedStyleList.contains(linkStyle))) { usedStyleList.add(linkStyle); getUsedStyleList(linkStyle, usedStyleList); } String nextStyleID = style.getNextStyleID(); XWPFStyle nextStyle = getStyle(nextStyleID); if ((nextStyle != null) && (!usedStyleList.contains(nextStyle))) { usedStyleList.add(linkStyle); getUsedStyleList(linkStyle, usedStyleList); } return usedStyleList; } protected CTLanguage getCTLanguage() { ensureDocDefaults(); CTLanguage lang = null; if (defaultRunStyle.getRPr().isSetLang()) { lang = defaultRunStyle.getRPr().getLang(); } else { lang = defaultRunStyle.getRPr().addNewLang(); } return lang; } /** * Sets the default spelling language on ctStyles DocDefaults parameter * * @param strSpellingLanguage */ public void setSpellingLanguage(String strSpellingLanguage) { CTLanguage lang = getCTLanguage(); lang.setVal(strSpellingLanguage); lang.setBidi(strSpellingLanguage); } /** * Sets the default East Asia spelling language on ctStyles DocDefaults parameter * * @param strEastAsia */ public void setEastAsia(String strEastAsia) { CTLanguage lang = getCTLanguage(); lang.setEastAsia(strEastAsia); } /** * Sets the default font on ctStyles DocDefaults parameter * TODO Replace this with specific setters for each type, possibly * on XWPFDefaultRunStyle */ public void setDefaultFonts(CTFonts fonts) { ensureDocDefaults(); CTRPr runProps = defaultRunStyle.getRPr(); runProps.setRFonts(fonts); } /** * get the style with the same name * if this style is not existing, return null */ public XWPFStyle getStyleWithSameName(XWPFStyle style) { for (XWPFStyle ownStyle : listStyle) { if (ownStyle.hasSameName(style)) { return ownStyle; } } return null; } /** * Get the default style which applies text runs in the document */ public XWPFDefaultRunStyle getDefaultRunStyle() { ensureDocDefaults(); return defaultRunStyle; } /** * Get the default paragraph style which applies to the document */ public XWPFDefaultParagraphStyle getDefaultParagraphStyle() { ensureDocDefaults(); return defaultParaStyle; } /** * Get the definition of all the Latent Styles */ public XWPFLatentStyles getLatentStyles() { return latentStyles; } }
/** * 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.thimbleware.jmemcached.util; /** A variety of high efficiency bit twiddling routines. * @lucene.internal */ final class BitUtil { /** Returns the number of bits set in the long */ public static int pop(long x) { /* Hacker's Delight 32 bit pop function: * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc * int pop(unsigned x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x = x + (x >> 8); x = x + (x >> 16); return x & 0x0000003F; } ***/ // 64 bit java version of the C function from above x = x - ((x >>> 1) & 0x5555555555555555L); x = (x & 0x3333333333333333L) + ((x >>>2 ) & 0x3333333333333333L); x = (x + (x >>> 4)) & 0x0F0F0F0F0F0F0F0FL; x = x + (x >>> 8); x = x + (x >>> 16); x = x + (x >>> 32); return ((int)x) & 0x7F; } /*** Returns the number of set bits in an array of longs. */ public static long pop_array(long A[], int wordOffset, int numWords) { /* * Robert Harley and David Seal's bit counting algorithm, as documented * in the revisions of Hacker's Delight * http://www.hackersdelight.org/revisions.pdf * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc * * This function was adapted to Java, and extended to use 64 bit words. * if only we had access to wider registers like SSE from java... * * This function can be transformed to compute the popcount of other functions * on bitsets via something like this: * sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' * */ int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, A[i], A[i+1]) { long b=A[i], c=A[i+1]; long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, A[i+2], A[i+3]) { long b=A[i+2], c=A[i+3]; long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, A[i+4], A[i+5]) { long b=A[i+4], c=A[i+5]; long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, A[i+6], A[i+7]) { long b=A[i+6], c=A[i+7]; long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } // handle trailing words in a binary-search manner... // derived from the loop above by setting specific elements to 0. // the original method in Hackers Delight used a simple for loop: // for (i = i; i < n; i++) // Add in the last elements // tot = tot + pop(A[i]); if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=A[i], c=A[i+1]; long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=A[i+2], c=A[i+3]; long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=A[i], c=A[i+1]; long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop(A[i]); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of the two sets after an intersection. * Neither array is modified. */ public static long pop_intersect(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] & B[i]), (A[i+1] & B[i+1])) { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] & B[i+2]), (A[i+3] & B[i+3])) { long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] & B[i+4]), (A[i+5] & B[i+5])) { long b=(A[i+4] & B[i+4]), c=(A[i+5] & B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] & B[i+6]), (A[i+7] & B[i+7])) { long b=(A[i+6] & B[i+6]), c=(A[i+7] & B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] & B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of the union of two sets. * Neither array is modified. */ public static long pop_union(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \| B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] | B[i]), (A[i+1] | B[i+1])) { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] | B[i+2]), (A[i+3] | B[i+3])) { long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] | B[i+4]), (A[i+5] | B[i+5])) { long b=(A[i+4] | B[i+4]), c=(A[i+5] | B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] | B[i+6]), (A[i+7] | B[i+7])) { long b=(A[i+6] | B[i+6]), c=(A[i+7] | B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] | B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of A & ~B * Neither array is modified. */ public static long pop_andnot(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& ~B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] & ~B[i]), (A[i+1] & ~B[i+1])) { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] & ~B[i+2]), (A[i+3] & ~B[i+3])) { long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] & ~B[i+4]), (A[i+5] & ~B[i+5])) { long b=(A[i+4] & ~B[i+4]), c=(A[i+5] & ~B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] & ~B[i+6]), (A[i+7] & ~B[i+7])) { long b=(A[i+6] & ~B[i+6]), c=(A[i+7] & ~B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] & ~B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } public static long pop_xor(long A[], long B[], int wordOffset, int numWords) { int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] ^ B[i]), (A[i+1] ^ B[i+1])) { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] ^ B[i+2]), (A[i+3] ^ B[i+3])) { long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] ^ B[i+4]), (A[i+5] ^ B[i+5])) { long b=(A[i+4] ^ B[i+4]), c=(A[i+5] ^ B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] ^ B[i+6]), (A[i+7] ^ B[i+7])) { long b=(A[i+6] ^ B[i+6]), c=(A[i+7] ^ B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] ^ B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /* python code to generate ntzTable def ntz(val): if val==0: return 8 i=0 while (val&0x01)==0: i = i+1 val >>= 1 return i print ','.join([ str(ntz(i)) for i in range(256) ]) ***/ /** table of number of trailing zeros in a byte */ public static final byte[] ntzTable = {8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0}; /** Returns number of trailing zeros in a 64 bit long value. */ public static int ntz(long val) { // A full binary search to determine the low byte was slower than // a linear search for nextSetBit(). This is most likely because // the implementation of nextSetBit() shifts bits to the right, increasing // the probability that the first non-zero byte is in the rhs. // // This implementation does a single binary search at the top level only // so that all other bit shifting can be done on ints instead of longs to // remain friendly to 32 bit architectures. In addition, the case of a // non-zero first byte is checked for first because it is the most common // in dense bit arrays. int lower = (int)val; int lowByte = lower & 0xff; if (lowByte != 0) return ntzTable[lowByte]; if (lower!=0) { lowByte = (lower>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 8; lowByte = (lower>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 16; // no need to mask off low byte for the last byte in the 32 bit word // no need to check for zero on the last byte either. return ntzTable[lower>>>24] + 24; } else { // grab upper 32 bits int upper=(int)(val>>32); lowByte = upper & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 32; lowByte = (upper>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 40; lowByte = (upper>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 48; // no need to mask off low byte for the last byte in the 32 bit word // no need to check for zero on the last byte either. return ntzTable[upper>>>24] + 56; } } /** Returns number of trailing zeros in a 32 bit int value. */ public static int ntz(int val) { // This implementation does a single binary search at the top level only. // In addition, the case of a non-zero first byte is checked for first // because it is the most common in dense bit arrays. int lowByte = val & 0xff; if (lowByte != 0) return ntzTable[lowByte]; lowByte = (val>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 8; lowByte = (val>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 16; // no need to mask off low byte for the last byte. // no need to check for zero on the last byte either. return ntzTable[val>>>24] + 24; } /** returns 0 based index of first set bit * (only works for x!=0) * <br/> This is an alternate implementation of ntz() */ public static int ntz2(long x) { int n = 0; int y = (int)x; if (y==0) {n+=32; y = (int)(x>>>32); } // the only 64 bit shift necessary if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } return (ntzTable[ y & 0xff ]) + n; } /** returns 0 based index of first set bit * <br/> This is an alternate implementation of ntz() */ public static int ntz3(long x) { // another implementation taken from Hackers Delight, extended to 64 bits // and converted to Java. // Many 32 bit ntz algorithms are at http://www.hackersdelight.org/HDcode/ntz.cc int n = 1; // do the first step as a long, all others as ints. int y = (int)x; if (y==0) {n+=32; y = (int)(x>>>32); } if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } if ((y & 0x0000000F) == 0) { n+=4; y>>>=4; } if ((y & 0x00000003) == 0) { n+=2; y>>>=2; } return n - (y & 1); } /** returns true if v is a power of two or zero*/ public static boolean isPowerOfTwo(int v) { return ((v & (v-1)) == 0); } /** returns true if v is a power of two or zero*/ public static boolean isPowerOfTwo(long v) { return ((v & (v-1)) == 0); } /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ public static int nextHighestPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ public static long nextHighestPowerOfTwo(long v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; v++; return v; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.27 at 10:02:54 AM CDT // package com.mastercard.mcwallet.sdk.xml.allservices; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PrecheckoutCard complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PrecheckoutCard"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="BrandId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="BrandName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="BillingAddress" type="{}Address"/> * &lt;element name="CardHolderName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ExpiryMonth" type="{}Month" minOccurs="0"/> * &lt;element name="ExpiryYear" type="{}Year" minOccurs="0"/> * &lt;element name="CardId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="LastFour" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CardAlias" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="SelectedAsDefault" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PrecheckoutCard", propOrder = { "brandId", "brandName", "billingAddress", "cardHolderName", "expiryMonth", "expiryYear", "cardId", "lastFour", "cardAlias", "selectedAsDefault" }) public class PrecheckoutCard { @XmlElement(name = "BrandId", required = true) protected String brandId; @XmlElement(name = "BrandName", required = true) protected String brandName; @XmlElement(name = "BillingAddress", required = true) protected Address billingAddress; @XmlElement(name = "CardHolderName", required = true) protected String cardHolderName; @XmlElement(name = "ExpiryMonth") protected Integer expiryMonth; @XmlElement(name = "ExpiryYear") protected Integer expiryYear; @XmlElement(name = "CardId", required = true) protected String cardId; @XmlElement(name = "LastFour", required = true) protected String lastFour; @XmlElement(name = "CardAlias", required = true) protected String cardAlias; @XmlElement(name = "SelectedAsDefault") protected boolean selectedAsDefault; /** * Gets the value of the brandId property. * * @return * possible object is * {@link String } * */ public String getBrandId() { return brandId; } /** * Sets the value of the brandId property. * * @param value * allowed object is * {@link String } * */ public void setBrandId(String value) { this.brandId = value; } /** * Gets the value of the brandName property. * * @return * possible object is * {@link String } * */ public String getBrandName() { return brandName; } /** * Sets the value of the brandName property. * * @param value * allowed object is * {@link String } * */ public void setBrandName(String value) { this.brandName = value; } /** * Gets the value of the billingAddress property. * * @return * possible object is * {@link Address } * */ public Address getBillingAddress() { return billingAddress; } /** * Sets the value of the billingAddress property. * * @param value * allowed object is * {@link Address } * */ public void setBillingAddress(Address value) { this.billingAddress = value; } /** * Gets the value of the cardHolderName property. * * @return * possible object is * {@link String } * */ public String getCardHolderName() { return cardHolderName; } /** * Sets the value of the cardHolderName property. * * @param value * allowed object is * {@link String } * */ public void setCardHolderName(String value) { this.cardHolderName = value; } /** * Gets the value of the expiryMonth property. * * @return * possible object is * {@link Integer } * */ public Integer getExpiryMonth() { return expiryMonth; } /** * Sets the value of the expiryMonth property. * * @param value * allowed object is * {@link Integer } * */ public void setExpiryMonth(Integer value) { this.expiryMonth = value; } /** * Gets the value of the expiryYear property. * * @return * possible object is * {@link Integer } * */ public Integer getExpiryYear() { return expiryYear; } /** * Sets the value of the expiryYear property. * * @param value * allowed object is * {@link Integer } * */ public void setExpiryYear(Integer value) { this.expiryYear = value; } /** * Gets the value of the cardId property. * * @return * possible object is * {@link String } * */ public String getCardId() { return cardId; } /** * Sets the value of the cardId property. * * @param value * allowed object is * {@link String } * */ public void setCardId(String value) { this.cardId = value; } /** * Gets the value of the lastFour property. * * @return * possible object is * {@link String } * */ public String getLastFour() { return lastFour; } /** * Sets the value of the lastFour property. * * @param value * allowed object is * {@link String } * */ public void setLastFour(String value) { this.lastFour = value; } /** * Gets the value of the cardAlias property. * * @return * possible object is * {@link String } * */ public String getCardAlias() { return cardAlias; } /** * Sets the value of the cardAlias property. * * @param value * allowed object is * {@link String } * */ public void setCardAlias(String value) { this.cardAlias = value; } /** * Gets the value of the selectedAsDefault property. * */ public boolean isSelectedAsDefault() { return selectedAsDefault; } /** * Sets the value of the selectedAsDefault property. * */ public void setSelectedAsDefault(boolean value) { this.selectedAsDefault = value; } }
/* * Copyright 2010 Ning, Inc. * * Ning 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.asynchttpclient; import static org.asynchttpclient.util.MiscUtil.isNonEmpty; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** * An implementation of a {@code String -> List<String>} map that adds a fluent interface, i.e. methods that * return this instance. This class differs from {@link FluentStringsMap} in that keys are treated in an * case-insensitive matter, i.e. case of the key doesn't matter when retrieving values or changing the map. * However, the map preserves the key case (of the first insert or replace) and returns the keys in their * original case in the appropriate methods (e.g. {@link FluentCaseInsensitiveStringsMap#keySet()}). */ public class FluentCaseInsensitiveStringsMap implements Map<String, List<String>>, Iterable<Map.Entry<String, List<String>>> { private final Map<String, List<String>> values = new LinkedHashMap<String, List<String>>(); private final Map<String, String> keyLookup = new LinkedHashMap<String, String>(); public FluentCaseInsensitiveStringsMap() { } public FluentCaseInsensitiveStringsMap(FluentCaseInsensitiveStringsMap src) { if (src != null) { for (Map.Entry<String, List<String>> header : src) { add(header.getKey(), header.getValue()); } } } public FluentCaseInsensitiveStringsMap(Map<String, Collection<String>> src) { if (src != null) { for (Map.Entry<String, Collection<String>> header : src.entrySet()) { add(header.getKey(), header.getValue()); } } } /** * Adds the specified values and returns this object. * * @param key The key * @param values The value(s); if null then this method has no effect. Use the empty string to * generate an empty value * @return This object */ public FluentCaseInsensitiveStringsMap add(String key, String... values) { if (isNonEmpty(values)) { add(key, Arrays.asList(values)); } return this; } private List<String> fetchValues(Collection<String> values) { List<String> result = null; if (values != null) { for (String value : values) { if (value == null) { value = ""; } if (result == null) { // lazy initialization result = new ArrayList<String>(); } result.add(value); } } return result; } /** * Adds the specified values and returns this object. * * @param key The key * @param values The value(s); if null then this method has no effect. Use an empty collection * to generate an empty value * @return This object */ public FluentCaseInsensitiveStringsMap add(String key, Collection<String> values) { if (key != null) { List<String> nonNullValues = fetchValues(values); if (nonNullValues != null) { String lcKey = key.toLowerCase(Locale.ENGLISH); String realKey = keyLookup.get(lcKey); List<String> curValues = null; if (realKey == null) { realKey = key; keyLookup.put(lcKey, key); } else { curValues = this.values.get(realKey); } if (curValues == null) { curValues = new ArrayList<String>(); this.values.put(realKey, curValues); } curValues.addAll(nonNullValues); } } return this; } /** * Adds all key-values pairs from the given object to this object and returns this object. * * @param src The source object * @return This object */ public FluentCaseInsensitiveStringsMap addAll(FluentCaseInsensitiveStringsMap src) { if (src != null) { for (Map.Entry<String, List<String>> header : src) { add(header.getKey(), header.getValue()); } } return this; } /** * Adds all key-values pairs from the given map to this object and returns this object. * * @param src The source map * @return This object */ public FluentCaseInsensitiveStringsMap addAll(Map<String, Collection<String>> src) { if (src != null) { for (Map.Entry<String, Collection<String>> header : src.entrySet()) { add(header.getKey(), header.getValue()); } } return this; } /** * Replaces the values for the given key with the given values. * * @param key The key * @param values The new values * @return This object */ public FluentCaseInsensitiveStringsMap replace(final String key, final String... values) { return replace(key, Arrays.asList(values)); } /** * Replaces the values for the given key with the given values. * * @param key The key * @param values The new values * @return This object */ public FluentCaseInsensitiveStringsMap replace(final String key, final Collection<String> values) { if (key != null) { List<String> nonNullValues = fetchValues(values); String lcKkey = key.toLowerCase(Locale.ENGLISH); String realKey = keyLookup.get(lcKkey); if (nonNullValues == null) { keyLookup.remove(lcKkey); if (realKey != null) { this.values.remove(realKey); } } else { if (!key.equals(realKey)) { keyLookup.put(lcKkey, key); this.values.remove(realKey); } this.values.put(key, nonNullValues); } } return this; } /** * Replace the values for all keys from the given map that are also present in this object, with the values from the given map. * All key-values from the given object that are not present in this object, will be added to it. * * @param src The source object * @return This object */ public FluentCaseInsensitiveStringsMap replaceAll(FluentCaseInsensitiveStringsMap src) { if (src != null) { for (Map.Entry<String, List<String>> header : src) { replace(header.getKey(), header.getValue()); } } return this; } /** * Replace the values for all keys from the given map that are also present in this object, with the values from the given map. * All key-values from the given object that are not present in this object, will be added to it. * * @param src The source map * @return This object */ public FluentCaseInsensitiveStringsMap replaceAll(Map<? extends String, ? extends Collection<String>> src) { if (src != null) { for (Map.Entry<? extends String, ? extends Collection<String>> header : src.entrySet()) { replace(header.getKey(), header.getValue()); } } return this; } /** * {@inheritDoc} */ @Override public List<String> put(String key, List<String> value) { if (key == null) { throw new NullPointerException("Null keys are not allowed"); } List<String> oldValue = get(key); replace(key, value); return oldValue; } /** * {@inheritDoc} */ @Override public void putAll(Map<? extends String, ? extends List<String>> values) { replaceAll(values); } /** * Removes the values for the given key if present and returns this object. * * @param key The key * @return This object */ public FluentCaseInsensitiveStringsMap delete(String key) { if (key != null) { String lcKey = key.toLowerCase(Locale.ENGLISH); String realKey = keyLookup.remove(lcKey); if (realKey != null) { values.remove(realKey); } } return this; } /** * Removes the values for the given keys if present and returns this object. * * @param keys The keys * @return This object */ public FluentCaseInsensitiveStringsMap deleteAll(String... keys) { if (keys != null) { for (String key : keys) { remove(key); } } return this; } /** * Removes the values for the given keys if present and returns this object. * * @param keys The keys * @return This object */ public FluentCaseInsensitiveStringsMap deleteAll(Collection<String> keys) { if (keys != null) { for (String key : keys) { remove(key); } } return this; } /** * {@inheritDoc} */ @Override public List<String> remove(Object key) { if (key == null) { return null; } else { List<String> oldValues = get(key.toString()); delete(key.toString()); return oldValues; } } /** * {@inheritDoc} */ @Override public void clear() { keyLookup.clear(); values.clear(); } /** * {@inheritDoc} */ @Override public Iterator<Map.Entry<String, List<String>>> iterator() { return Collections.unmodifiableSet(values.entrySet()).iterator(); } /** * {@inheritDoc} */ @Override public Set<String> keySet() { return new LinkedHashSet<String>(keyLookup.values()); } /** * {@inheritDoc} */ @Override public Set<Entry<String, List<String>>> entrySet() { return values.entrySet(); } /** * {@inheritDoc} */ @Override public int size() { return values.size(); } /** * {@inheritDoc} */ @Override public boolean isEmpty() { return values.isEmpty(); } /** * {@inheritDoc} */ @Override public boolean containsKey(Object key) { return key == null ? false : keyLookup.containsKey(key.toString().toLowerCase(Locale.ENGLISH)); } /** * {@inheritDoc} */ @Override public boolean containsValue(Object value) { return values.containsValue(value); } /** * Returns the value for the given key. If there are multiple values for this key, * then only the first one will be returned. * * @param key The key * @return The first value */ public String getFirstValue(String key) { List<String> values = get(key); if (values == null) { return null; } else if (values.isEmpty()) { return ""; } else { return values.get(0); } } /** * Returns the values for the given key joined into a single string using the given delimiter. * * @param key The key * @return The value as a single string */ public String getJoinedValue(String key, String delimiter) { List<String> values = get(key); if (values == null) { return null; } else if (values.size() == 1) { return values.get(0); } else { StringBuilder result = new StringBuilder(); for (String value : values) { if (result.length() > 0) { result.append(delimiter); } result.append(value); } return result.toString(); } } /** * {@inheritDoc} */ @Override public List<String> get(Object key) { if (key == null) { return null; } String lcKey = key.toString().toLowerCase(Locale.ENGLISH); String realKey = keyLookup.get(lcKey); if (realKey == null) { return null; } else { return values.get(realKey); } } /** * {@inheritDoc} */ @Override public Collection<List<String>> values() { return values.values(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final FluentCaseInsensitiveStringsMap other = (FluentCaseInsensitiveStringsMap) obj; if (values == null) { if (other.values != null) { return false; } } else if (!values.equals(other.values)) { return false; } return true; } @Override public int hashCode() { return values == null ? 0 : values.hashCode(); } @Override public String toString() { StringBuilder result = new StringBuilder(); for (Map.Entry<String, List<String>> entry : values.entrySet()) { if (result.length() > 0) { result.append("; "); } result.append("\""); result.append(entry.getKey()); result.append("="); boolean needsComma = false; for (String value : entry.getValue()) { if (needsComma) { result.append(", "); } else { needsComma = true; } result.append(value); } result.append("\""); } return result.toString(); } }
/* * EncodedDataInBinaryFileOut.java * * Copyright (C) 2010-2015 by Revolution Analytics Inc. * * This program is licensed to you under the terms of Version 2.0 of the * Apache License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0) for more details. * */ package com.revo.deployr.client.example.data.io.auth.stateful.exec; import com.revo.deployr.client.*; import com.revo.deployr.client.data.*; import com.revo.deployr.client.factory.*; import com.revo.deployr.client.params.*; import com.revo.deployr.client.auth.RAuthentication; import com.revo.deployr.client.auth.basic.RBasicAuthentication; import java.util.*; import java.io.*; import java.net.*; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; public class EncodedDataInBinaryFileOut { private static Logger log = Logger.getLogger(EncodedDataInBinaryFileOut.class); /* * Hipparcos star dataset URL endpoint. */ public static void main(String args[]) throws Exception { RClient rClient = null; RProject rProject = null; try { /* * Determine DeployR server endpoint. */ String endpoint = System.getProperty("endpoint"); log.info("[ CONFIGURATION ] Using endpoint=" + endpoint); /* * Establish RClient connection to DeployR server. * * An RClient connection is the mandatory starting * point for any application using the client library. */ rClient = RClientFactory.createClient(endpoint); log.info("[ CONNECTION ] Established anonymous " + "connection [ RClient ]."); /* * Build a basic authentication token. */ RAuthentication rAuth = new RBasicAuthentication(System.getProperty("username"), System.getProperty("password")); /* * Establish an authenticated handle with the DeployR * server, rUser. Following this call the rClient * connection is operating as an authenticated connection * and all calls on rClient inherit the access permissions * of the authenticated user, rUser. */ RUser rUser = rClient.login(rAuth); log.info("[ AUTHENTICATION ] Upgraded to authenticated " + "connection [ RUser ]."); /* * Create a temporary project (R session). * * Optionally: * ProjectCreationOptions options = * new ProjectCreationOptions(); * * Populate options as needed, then: * * rProject = rUser.createProject(options); */ rProject = rUser.createProject(); log.info("[ GO STATEFUL ] Created stateful temporary " + "R session [ RProject ]."); /* * Create a ProjectExecutionOptions instance * to specify data inputs and output to the * execution of the repository-managed R script. * * This options object can be used to pass standard * execution model parameters on execution calls. All * fields are optional. * * See the Standard Execution Model chapter in the * Client Library Tutorial on the DeployR website for * further details. */ ProjectExecutionOptions options = new ProjectExecutionOptions(); /* * Simulate application generated data. This data * is first encoded using the RDataFactory before * being passed as an input on the execution. * * This encoded R input is automatically converted * into a workspace object before script execution. */ RData generatedData = simulateGeneratedData(); if(generatedData != null) { List<RData> rinputs = Arrays.asList(generatedData); options.rinputs = rinputs; } log.info("[ DATA INPUT ] DeployR-encoded R input set on execution, " + "[ ProjectExecutionOptions.rinputs ]."); /* * Execute a public analytics Web service as an authenticated * user based on a repository-managed R script: * /testuser/example-data-io/dataIO.R */ RProjectExecution exec = rProject.executeScript("dataIO.R", "example-data-io", "testuser", null, options); log.info("[ EXECUTION ] Stateful R script " + "execution completed [ RProjectExecution ]."); /* * Retrieve the working directory file (artifact) called * hip.rData that was generated by the execution. * * Outputs generated by an execution can be used in any * number of ways by client applications, including: * * 1. Use output data to perform further calculations. * 2. Display output data to an end-user. * 3. Write output data to a database. * 4. Pass output data along to another Web service. * 5. etc. */ List<RProjectFile> wdFiles = exec.about().artifacts; for(RProjectFile wdFile : wdFiles) { if(wdFile.about().filename.equals("hip.rData")) { log.info("[ DATA OUTPUT ] Retrieved working directory " + "file output " + wdFile.about().filename + " [ RProjectFile ]."); InputStream fis = null; try { fis = wdFile.download(); } catch(Exception ex) { log.warn("Working directory binary file download " + ex); } finally { IOUtils.closeQuietly(fis); } } } } catch (Exception ex) { log.warn("Unexpected runtime exception=" + ex); } finally { try { if (rProject != null) { /* * Close rProject before application exits. */ rProject.close(); } } catch (Exception fex) { } try { if (rClient != null) { /* * Release rClient connection before application exits. */ rClient.release(); } } catch (Exception fex) { } } } /* * simulateGeneratedData * * This method is used to generate sample data within the * application. In a real-world application this data may * originate from any number of sources, for example: * * - Data read from a file * - Data read from a database * - Data read from an external Web service * - Data read from direct user input * - Data generated in real time by the application itself * * This data is encoded using the RDataFactory and then * passed as an input the execution. * */ private static RData simulateGeneratedData() { RData df = null; try { URL url = new URL("http://astrostatistics.psu.edu/datasets/HIP_star.dat"); InputStream is = url.openStream(); RDataTable table = RDataFactory.createDataTable(is, "\\s+", true, true); df = table.asDataFrame("hip"); } catch(Exception ex) { log.warn("Simulate generated data failed, ex=" + ex); } finally { return df; } } }
/* * #%L * wcm.io * %% * Copyright (C) 2020 wcm.io * %% * 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. * #L% */ package io.wcm.qa.glnm.hamcrest.galen; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ExecutionException; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import io.wcm.qa.glnm.differences.base.Difference; import io.wcm.qa.glnm.differences.generic.MutableDifferences; import io.wcm.qa.glnm.exceptions.GaleniumException; import io.wcm.qa.glnm.galen.specs.GalenSpecRun; import io.wcm.qa.glnm.galen.specs.imagecomparison.ImageComparisonSpecDefinition; import io.wcm.qa.glnm.galen.specs.page.GalenCorrectionRect; import io.wcm.qa.glnm.galen.validation.GalenValidation; import io.wcm.qa.glnm.hamcrest.baseline.DifferentiatingMatcher; import io.wcm.qa.glnm.hamcrest.selector.SelectorMatcher; import io.wcm.qa.glnm.selectors.base.Selector; /** * Matcher doing visual comparison on element defined by Selector. * * @since 5.0.0 */ public class VisuallyCompare extends SelectorMatcher<GalenSpecRun> implements DifferentiatingMatcher<Selector> { private final ImageComparisonSpecDefinition specDefinition = new ImageComparisonSpecDefinition(); private final LoadingCache<Selector, GalenSpecRun> visualComparisons = CacheBuilder.newBuilder().build( new CacheLoader<Selector, GalenSpecRun>() { @Override public GalenSpecRun load(Selector key) throws Exception { ImageComparisonSpecDefinition def = new ImageComparisonSpecDefinition(specDefinition); def.setSelector(key); return GalenValidation.imageComparison(def); } }); protected VisuallyCompare() { super(GalenSpecRunMatcher.successfulRun()); } /** {@inheritDoc} */ @Override public void add(Difference difference) { specDefinition.addDifference(difference); } /** {@inheritDoc} */ @Override public String getKey() { return getDifferences().getKey(); } /** {@inheritDoc} */ @Override public Iterator<Difference> iterator() { return getDifferences().iterator(); } /** {@inheritDoc} */ @Override public void prepend(Difference difference) { MutableDifferences newDifferences = new MutableDifferences(); newDifferences.add(difference); newDifferences.addAll(getDifferences()); specDefinition.setDifferences(newDifferences); } /** * <p>whileIgnoring.</p> * * @param ignore a {@link io.wcm.qa.glnm.selectors.base.Selector} object. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare whileIgnoring(Selector... ignore) { if (ignore == null) { return this; } for (Selector selectorToIgnore : ignore) { specDefinition.addObjectToIgnore(selectorToIgnore); } return this; } /** * <p>withAllowedErrorPercent.</p> * * @param error a double. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withAllowedErrorPercent(double error) { specDefinition.setAllowedErrorPercent(error); return this; } /** * <p>withAllowedErrorPixel.</p> * * @param error a int. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withAllowedErrorPixel(int error) { specDefinition.setAllowedErrorPixel(error); return this; } /** * <p>withAllowedOffset.</p> * * @param offset a int. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withAllowedOffset(int offset) { specDefinition.setAllowedOffset(offset); return this; } /** * <p>withCorrections.</p> * * @param corrections a {@link io.wcm.qa.glnm.galen.specs.page.GalenCorrectionRect} object. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withCorrections(GalenCorrectionRect corrections) { specDefinition.setCorrections(corrections); return this; } /** * <p>withCropIfOutside.</p> * * @param crop a boolean. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withCropIfOutside(boolean crop) { specDefinition.setCropIfOutside(crop); return this; } /** * <p>withDifferences.</p> * * @param differences a {@link java.util.Collection} object. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withDifferences(Collection<Difference> differences) { specDefinition.addAll(differences); return this; } /** * <p>withElementName.</p> * * @param name a {@link java.lang.String} object. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withElementName(String name) { specDefinition.setElementName(name); return this; } /** * <p>withSectionName.</p> * * @param name a {@link java.lang.String} object. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withSectionName(String name) { specDefinition.setSectionName(name); return this; } /** * <p>withZeroToleranceWarning.</p> * * @param warning a boolean. * @return a {@link io.wcm.qa.glnm.hamcrest.galen.VisuallyCompare} object. */ public VisuallyCompare withZeroToleranceWarning(boolean warning) { specDefinition.setZeroToleranceWarning(warning); return this; } protected MutableDifferences getDifferences() { return specDefinition.getDifferences(); } @Override protected GalenSpecRun map(Selector item) { try { return visualComparisons.get(item); } catch (ExecutionException ex) { throw new GaleniumException("when executing visual comparison", ex); } } /** * <p> * visuallyCompare. * </p> * * @return visual comparison matcher * @since 5.0.0 */ public static VisuallyCompare visuallyCompare() { return new VisuallyCompare(); } }
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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.broad.igv.data; //~--- non-JDK imports -------------------------------------------------------- import htsjdk.samtools.seekablestream.SeekableStream; import org.broad.igv.logging.*; import org.broad.igv.Globals; import org.broad.igv.exceptions.ParserException; import org.broad.igv.feature.genome.Genome; import org.broad.igv.track.TrackType; import org.broad.igv.track.WindowFunction; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.collections.FloatArrayList; import org.broad.igv.util.collections.IntArrayList; import org.broad.igv.util.stream.IGVSeekableStreamFactory; import htsjdk.tribble.readers.AsciiLineReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Class description * * @author Enter your name here... * @version Enter version here..., 08/11/11 */ public class IGVDatasetParser { private static Logger log = LogManager.getLogger(IGVDatasetParser.class); private ResourceLocator dataResourceLocator; private int chrColumn = -1; private int startColumn = -1; private int endColumn = -1; private int firstDataColumn = -1; private int lastDataColumn = -1; private int probeColumn = -1; private boolean hasEndLocations = false; private boolean hasCalls = false; private Genome genome; private IGV igv; private int startBase = 0; public IGVDatasetParser(ResourceLocator copyNoFile, Genome genome) { this.dataResourceLocator = copyNoFile; this.genome = genome; this.igv = IGV.hasInstance() ? IGV.getInstance() : null; } private void setColumnDefaults() { String format = dataResourceLocator.getFormat(); switch (format) { case "igv": chrColumn = 0; startColumn = 1; endColumn = 2; probeColumn = 3; firstDataColumn = 4; hasEndLocations = true; hasCalls = false; break; case "cn": case "snp": case "xcn": case "loh": probeColumn = 0; chrColumn = 1; startColumn = 2; endColumn = -1; firstDataColumn = 3; hasEndLocations = false; hasCalls = format.equals("xcn") || format.equals("snp"); break; case ".expr": //gene_id bundle_id chr left right FPKM FPKM_conf_lo FPKM_conf_hi probeColumn = 0; chrColumn = 2; startColumn = 3; endColumn = 4; startBase = 1; firstDataColumn = 5; lastDataColumn = 5; hasEndLocations = true; break; default: // TODO -- popup dialog and ask user to define columns, and csv vs tsv? throw new ParserException("Unknown file type: ", 0); } } /** * Scan the datafile for chromosome breaks. * * @param dataset * @return */ public List<ChromosomeSummary> scan(IGVDataset dataset) { int estLineCount = ParsingUtils.estimateLineCount(dataResourceLocator.getPath()); Map<String, Integer> longestFeatureMap = new HashMap(); float dataMin = 0; float dataMax = 0; InputStream is = null; AsciiLineReader reader = null; String nextLine = null; ChromosomeSummary chrSummary = null; List<ChromosomeSummary> chrSummaries = new ArrayList(); String[] headings = null; WholeGenomeData wgData = null; int nRows = 0; int headerRows = 0; int count = 0; boolean logNormalized; try { int skipColumns = hasCalls ? 2 : 1; // BufferedReader reader = ParsingUtils.openBufferedReader(dataResourceLocator); is = ParsingUtils.openInputStreamGZ(dataResourceLocator); reader = new AsciiLineReader(is); // Infer datatype from extension. This can be overriden in the // comment section if (isCopyNumberFileExt(dataResourceLocator.getPath())) { dataset.setTrackType(TrackType.COPY_NUMBER); dataset.getTrackProperties().setWindowingFunction(WindowFunction.mean); } else if (isLOHFileExt(dataResourceLocator.getPath())) { dataset.setTrackType(TrackType.LOH); dataset.getTrackProperties().setWindowingFunction(WindowFunction.mean); } else { dataset.getTrackProperties().setWindowingFunction(WindowFunction.mean); } // Parse comments and directives, if any nextLine = reader.readLine(); while (nextLine.startsWith("#") || (nextLine.trim().length() == 0)) { headerRows++; if (nextLine.length() > 0) { parseDirective(nextLine, dataset); } nextLine = reader.readLine(); } if (chrColumn < 0) { setColumnDefaults(); } // Parse column headings String[] data = nextLine.trim().split("\t"); // Set last data column if (lastDataColumn < 0) { lastDataColumn = data.length - 1; } headings = getHeadings(data, skipColumns); dataset.setDataHeadings(headings); // Infer if the data is logNormalized by looking for negative data values. // Assume it is not until proven otherwise logNormalized = false; wgData = new WholeGenomeData(headings); int chrRowCount = 0; // Update int updateCount = 5000; long lastPosition = 0; while ((nextLine = reader.readLine()) != null) { if (igv != null && ++count % updateCount == 0) { igv.setStatusBarMessage("Loaded: " + count + " / " + estLineCount + " (est)"); } // Distance since last sample String[] tokens = Globals.tabPattern.split(nextLine, -1); int nTokens = tokens.length; if (nTokens > 0) { String thisChr = genome.getCanonicalChrName(tokens[chrColumn]); if (chrSummary == null || !thisChr.equals(chrSummary.getName())) { // Update whole genome and previous chromosome summary, unless this is // the first chromosome if (chrSummary != null) { updateWholeGenome(chrSummary.getName(), dataset, headings, wgData); chrSummary.setNDataPoints(nRows); } // Shart the next chromosome chrSummary = new ChromosomeSummary(thisChr, lastPosition); chrSummaries.add(chrSummary); nRows = 0; wgData = new WholeGenomeData(headings); chrRowCount = 0; } lastPosition = reader.getPosition(); int location = -1; try { location = ParsingUtils.parseInt(tokens[startColumn]) - startBase; } catch (NumberFormatException numberFormatException) { log.error("Column " + tokens[startColumn] + " is not a number"); throw new ParserException("Column " + (startColumn + 1) + " must contain an integer value." + " Found: " + tokens[startColumn], count + headerRows, nextLine); } int length = 1; if (hasEndLocations) { try { length = ParsingUtils.parseInt(tokens[endColumn].trim()) - location + 1; } catch (NumberFormatException numberFormatException) { log.error("Column " + tokens[endColumn] + " is not a number"); throw new ParserException("Column " + (endColumn + 1) + " must contain an integer value." + " Found: " + tokens[endColumn], count + headerRows, nextLine); } } updateLongestFeature(longestFeatureMap, thisChr, length); if (wgData.locations.size() > 0 && wgData.locations.get(wgData.locations.size() - 1) > location) { throw new ParserException("File is not sorted, .igv and .cn files must be sorted by start position." + " Use igvtools (File > Run igvtools..) to sort the file.", count + headerRows); } wgData.locations.add(location); for (int idx = 0; idx < headings.length; idx++) { int i = firstDataColumn + idx * skipColumns; float copyNo = i < tokens.length ? readFloat(tokens[i]) : Float.NaN; if (!Float.isNaN(copyNo)) { dataMin = Math.min(dataMin, copyNo); dataMax = Math.max(dataMax, copyNo); } if (copyNo < 0) { logNormalized = true; } String heading = headings[idx]; wgData.data.get(heading).add(copyNo); } nRows++; } chrRowCount++; } dataset.setLongestFeatureMap(longestFeatureMap); } catch (ParserException pe) { throw pe; } catch (FileNotFoundException e) { // DialogUtils.showError("SNP file not found: " + dataSource.getCopyNoFile()); log.error("File not found: " + dataResourceLocator); throw new RuntimeException(e); } catch (Exception e) { log.error("Exception when loading: " + dataResourceLocator.getPath(), e); if (nextLine != null && (count + headerRows != 0)) { throw new ParserException(e.getMessage(), e, count + headerRows, nextLine); } else { throw new RuntimeException(e); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error("Error closing IGVDataset stream", e); } } } // Update last chromosome if (chrSummary != null) { updateWholeGenome(chrSummary.getName(), dataset, headings, wgData); chrSummary.setNDataPoints(nRows); } dataset.setLogNormalized(logNormalized); dataset.setDataMin(dataMin); dataset.setDataMax(dataMax); return chrSummaries; } private void updateLongestFeature(Map<String, Integer> longestFeatureMap, String thisChr, int length) { if (longestFeatureMap.containsKey(thisChr)) { longestFeatureMap.put(thisChr, Math.max(longestFeatureMap.get(thisChr), length)); } else { longestFeatureMap.put(thisChr, length); } } private float readFloat(String token) { float copyNo = Float.NaN; try { if (token != null) { copyNo = Float.parseFloat(token); } } catch (NumberFormatException e) { // This is an expected condition. } return copyNo; } /** * Load data for a single chromosome. * * @param chrSummary * @param dataHeaders * @return */ public ChromosomeData loadChromosomeData(ChromosomeSummary chrSummary, String[] dataHeaders) { // InputStream is = null; SeekableStream is = null; try { int skipColumns = hasCalls ? 2 : 1; // Get an estimate of the number of snps (rows). THIS IS ONLY AN ESTIMATE int nRowsEst = chrSummary.getNDataPts(); is = IGVSeekableStreamFactory.getInstance().getStreamFor(dataResourceLocator.getPath()); is.seek(chrSummary.getStartPosition()); AsciiLineReader reader = new AsciiLineReader(is); // Create containers to hold data IntArrayList startLocations = new IntArrayList(nRowsEst); IntArrayList endLocations = (hasEndLocations ? new IntArrayList(nRowsEst) : null); List<String> probes = new ArrayList(nRowsEst); Map<String, FloatArrayList> dataMap = new HashMap(); for (String h : dataHeaders) { dataMap.put(h, new FloatArrayList(nRowsEst)); } // Begin loop through rows String chromosome = chrSummary.getName(); boolean chromosomeStarted = false; String nextLine = reader.readLine(); int skippedLineCount = 0; while ((nextLine != null) && (nextLine.trim().length() > 0)) { if (!nextLine.startsWith("#")) { try { String[] tokens = Globals.tabPattern.split(nextLine, -1); String thisChromosome = genome.getCanonicalChrName(tokens[chrColumn].trim()); if (thisChromosome.equals(chromosome)) { chromosomeStarted = true; // chromosomeData.setMarkerId(nRows, tokens[0]); // The probe. A new string is created to prevent holding on to the entire row through a substring reference String probe = new String(tokens[probeColumn]); probes.add(probe); int start = ParsingUtils.parseInt(tokens[startColumn].trim()) - startBase; if (hasEndLocations) { endLocations.add(ParsingUtils.parseInt(tokens[endColumn].trim())); } startLocations.add(start); if (tokens.length <= firstDataColumn + (dataHeaders.length - 1) * skipColumns) { String msg = "Line has too few data columns: " + nextLine; log.error(msg); throw new RuntimeException(msg); } for (int idx = 0; idx < dataHeaders.length; idx++) { int i = firstDataColumn + idx * skipColumns; float copyNo = i <= lastDataColumn ? readFloat(tokens[i]) : Float.NaN; String heading = dataHeaders[idx]; dataMap.get(heading).add(copyNo); } } else if (chromosomeStarted) { break; } } catch (NumberFormatException numberFormatException) { if (skippedLineCount < 5) { skippedLineCount++; if (skippedLineCount == 5) { log.warn("Skipping line: " + nextLine + (skippedLineCount < 5 ? "" : " Further skipped lines will not be logged")); } } } } nextLine = reader.readLine(); } // Loop complete ChromosomeData cd = new ChromosomeData(chrSummary.getName()); cd.setProbes(probes.toArray(new String[]{})); cd.setStartLocations(startLocations.toArray()); if (hasEndLocations) { cd.setEndLocations(endLocations.toArray()); } for (String h : dataHeaders) { cd.setData(h, dataMap.get(h).toArray()); } return cd; } catch (IOException ex) { log.error("Error parsing igv file " + this.dataResourceLocator.getPath(), ex); throw new RuntimeException("Error parsing igv file", ex); } finally { try { is.close(); } catch (IOException e) { log.error("Error closing igv file " + this.dataResourceLocator.getPath(), e); } } } /** * Note: This is an exact copy of the method in ExpressionFileParser. Refactor to merge these * two parsers, or share a common base class. * * @param comment * @param dataset */ private void parseDirective(String comment, IGVDataset dataset) { String tmp = comment.substring(1, comment.length()); if (tmp.startsWith("track")) { ParsingUtils.parseTrackLine(tmp, dataset.getTrackProperties()); } else if (tmp.startsWith("columns")) { parseColumnLine(tmp); } else { String[] tokens = tmp.split("="); if (tokens.length != 2) { return; } String key = tokens[0].trim().toLowerCase(); if (key.equals("name")) { dataset.setName(tokens[1].trim()); } else if (key.equals("type")) { try { dataset.setTrackType(TrackType.valueOf(tokens[1].trim().toUpperCase())); } catch (Exception exception) { // Ignore } } else if (key.equals("coords")) { startBase = Integer.parseInt(tokens[1].trim()); } } } private boolean isCopyNumberFileExt(String filename) { String tmp = ((filename.endsWith(".txt") || filename.endsWith(".tab") || filename.endsWith(".xls") ? filename.substring(0, filename.length() - 4) : filename)).toLowerCase(); return tmp.endsWith(".cn") || tmp.endsWith(".xcn") || tmp.endsWith(".snp"); } private boolean isLOHFileExt(String filename) { String tmp = (filename.endsWith(".txt") || filename.endsWith(".tab") || filename.endsWith(".xls") ? filename.substring(0, filename.length() - 4) : filename); return tmp.endsWith(".loh"); } /** * Return the sample headings for the copy number file. * * @param tokens * @param skipColumns * @return */ public String[] getHeadings(String[] tokens, int skipColumns) { return getHeadings(tokens, skipColumns, false); } /** * Return the sample headings for the copy number file. * * @param tokens * @param skipColumns * @param removeDuplicates , whether to remove any duplicate headings * @return */ public String[] getHeadings(String[] tokens, int skipColumns, boolean removeDuplicates) { ArrayList headings = new ArrayList(); String previousHeading = null; for (int i = firstDataColumn; i <= lastDataColumn; i += skipColumns) { if (removeDuplicates) { if (previousHeading != null && tokens[i].equals(previousHeading) || tokens[i].equals("")) { continue; } previousHeading = tokens[i]; } headings.add(tokens[i].trim()); } return (String[]) headings.toArray(new String[0]); } private void parseColumnLine(String tmp) { String[] tokens = tmp.split("\\s+"); String neg_colnum = "Error parsing column line: " + tmp + "<br>Column numbers must be > 0"; if (tokens.length > 1) { for (int i = 1; i < tokens.length; i++) { String[] kv = tokens[i].split("="); if (kv.length == 2) { if (kv[0].toLowerCase().equals("chr")) { int c = Integer.parseInt(kv[1]); if (c < 1) { MessageUtils.showMessage(neg_colnum); } else { chrColumn = c - 1; } } else if (kv[0].toLowerCase().equals("start")) { int c = Integer.parseInt(kv[1]); if (c < 1) { MessageUtils.showMessage(neg_colnum); } else { startColumn = c - 1; } } else if (kv[0].toLowerCase().equals("end")) { int c = Integer.parseInt(kv[1]); if (c < 1) { MessageUtils.showMessage(neg_colnum); } else { endColumn = c - 1; hasEndLocations = true; } } else if (kv[0].toLowerCase().equals("probe")) { int c = Integer.parseInt(kv[1]); if (c < 1) { MessageUtils.showMessage(neg_colnum); } else { probeColumn = c - 1; } } else if (kv[0].toLowerCase().equals("data")) { // examples 4, 4-8, 4- String[] se = kv[1].split("-"); int c = Integer.parseInt(se[0]); if (c < 1) { MessageUtils.showMessage(neg_colnum); } else { this.firstDataColumn = c - 1; } if (se.length > 1) { c = Integer.parseInt(se[1]); if (c < 1) { MessageUtils.showMessage(neg_colnum); } else { this.lastDataColumn = c - 1; } } } } } } } private void updateWholeGenome(String currentChromosome, IGVDataset dataset, String[] headings, IGVDatasetParser.WholeGenomeData wgData) { if (!genome.getHomeChromosome().equals(Globals.CHR_ALL)) { return; } // Update whole genome data int[] locations = wgData.locations.toArray(); if (locations.length > 0) { Map<String, float[]> tmp = new HashMap(wgData.data.size()); for (String s : wgData.headings) { tmp.put(s, wgData.data.get(s).toArray()); } GenomeSummaryData genomeSummary = dataset.getGenomeSummary(); if (genomeSummary == null) { genomeSummary = new GenomeSummaryData(genome, headings); dataset.setGenomeSummary(genomeSummary); } genomeSummary.addData(currentChromosome, locations, tmp); } } class WholeGenomeData { String[] headings; IntArrayList locations = new IntArrayList(50000); Map<String, FloatArrayList> data = new HashMap(); WholeGenomeData(String[] headings) { this.headings = headings; for (String h : headings) { data.put(h, new FloatArrayList(50000)); } } } }
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.debezium; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ExtendedPropertyConfigurerGetter; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class DebeziumMongodbComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private org.apache.camel.component.debezium.configuration.MongoDbConnectorEmbeddedDebeziumConfiguration getOrCreateConfiguration(DebeziumMongodbComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.debezium.configuration.MongoDbConnectorEmbeddedDebeziumConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { DebeziumMongodbComponent target = (DebeziumMongodbComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionalproperties": case "additionalProperties": getOrCreateConfiguration(target).setAdditionalProperties(property(camelContext, java.util.Map.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "collectionexcludelist": case "collectionExcludeList": getOrCreateConfiguration(target).setCollectionExcludeList(property(camelContext, java.lang.String.class, value)); return true; case "collectionincludelist": case "collectionIncludeList": getOrCreateConfiguration(target).setCollectionIncludeList(property(camelContext, java.lang.String.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.debezium.configuration.MongoDbConnectorEmbeddedDebeziumConfiguration.class, value)); return true; case "connectbackoffinitialdelayms": case "connectBackoffInitialDelayMs": getOrCreateConfiguration(target).setConnectBackoffInitialDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "connectbackoffmaxdelayms": case "connectBackoffMaxDelayMs": getOrCreateConfiguration(target).setConnectBackoffMaxDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "connectmaxattempts": case "connectMaxAttempts": getOrCreateConfiguration(target).setConnectMaxAttempts(property(camelContext, int.class, value)); return true; case "converters": getOrCreateConfiguration(target).setConverters(property(camelContext, java.lang.String.class, value)); return true; case "databaseexcludelist": case "databaseExcludeList": getOrCreateConfiguration(target).setDatabaseExcludeList(property(camelContext, java.lang.String.class, value)); return true; case "databasehistoryfilefilename": case "databaseHistoryFileFilename": getOrCreateConfiguration(target).setDatabaseHistoryFileFilename(property(camelContext, java.lang.String.class, value)); return true; case "databaseincludelist": case "databaseIncludeList": getOrCreateConfiguration(target).setDatabaseIncludeList(property(camelContext, java.lang.String.class, value)); return true; case "eventprocessingfailurehandlingmode": case "eventProcessingFailureHandlingMode": getOrCreateConfiguration(target).setEventProcessingFailureHandlingMode(property(camelContext, java.lang.String.class, value)); return true; case "fieldexcludelist": case "fieldExcludeList": getOrCreateConfiguration(target).setFieldExcludeList(property(camelContext, java.lang.String.class, value)); return true; case "fieldrenames": case "fieldRenames": getOrCreateConfiguration(target).setFieldRenames(property(camelContext, java.lang.String.class, value)); return true; case "heartbeatintervalms": case "heartbeatIntervalMs": getOrCreateConfiguration(target).setHeartbeatIntervalMs(property(camelContext, int.class, value)); return true; case "heartbeattopicsprefix": case "heartbeatTopicsPrefix": getOrCreateConfiguration(target).setHeartbeatTopicsPrefix(property(camelContext, java.lang.String.class, value)); return true; case "internalkeyconverter": case "internalKeyConverter": getOrCreateConfiguration(target).setInternalKeyConverter(property(camelContext, java.lang.String.class, value)); return true; case "internalvalueconverter": case "internalValueConverter": getOrCreateConfiguration(target).setInternalValueConverter(property(camelContext, java.lang.String.class, value)); return true; case "maxbatchsize": case "maxBatchSize": getOrCreateConfiguration(target).setMaxBatchSize(property(camelContext, int.class, value)); return true; case "maxqueuesize": case "maxQueueSize": getOrCreateConfiguration(target).setMaxQueueSize(property(camelContext, int.class, value)); return true; case "maxqueuesizeinbytes": case "maxQueueSizeInBytes": getOrCreateConfiguration(target).setMaxQueueSizeInBytes(property(camelContext, long.class, value)); return true; case "mongodbauthsource": case "mongodbAuthsource": getOrCreateConfiguration(target).setMongodbAuthsource(property(camelContext, java.lang.String.class, value)); return true; case "mongodbconnecttimeoutms": case "mongodbConnectTimeoutMs": getOrCreateConfiguration(target).setMongodbConnectTimeoutMs(property(camelContext, int.class, value)); return true; case "mongodbhosts": case "mongodbHosts": getOrCreateConfiguration(target).setMongodbHosts(property(camelContext, java.lang.String.class, value)); return true; case "mongodbmembersautodiscover": case "mongodbMembersAutoDiscover": getOrCreateConfiguration(target).setMongodbMembersAutoDiscover(property(camelContext, boolean.class, value)); return true; case "mongodbname": case "mongodbName": getOrCreateConfiguration(target).setMongodbName(property(camelContext, java.lang.String.class, value)); return true; case "mongodbpassword": case "mongodbPassword": getOrCreateConfiguration(target).setMongodbPassword(property(camelContext, java.lang.String.class, value)); return true; case "mongodbpollintervalms": case "mongodbPollIntervalMs": getOrCreateConfiguration(target).setMongodbPollIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "mongodbserverselectiontimeoutms": case "mongodbServerSelectionTimeoutMs": getOrCreateConfiguration(target).setMongodbServerSelectionTimeoutMs(property(camelContext, int.class, value)); return true; case "mongodbsockettimeoutms": case "mongodbSocketTimeoutMs": getOrCreateConfiguration(target).setMongodbSocketTimeoutMs(property(camelContext, int.class, value)); return true; case "mongodbsslenabled": case "mongodbSslEnabled": getOrCreateConfiguration(target).setMongodbSslEnabled(property(camelContext, boolean.class, value)); return true; case "mongodbsslinvalidhostnameallowed": case "mongodbSslInvalidHostnameAllowed": getOrCreateConfiguration(target).setMongodbSslInvalidHostnameAllowed(property(camelContext, boolean.class, value)); return true; case "mongodbuser": case "mongodbUser": getOrCreateConfiguration(target).setMongodbUser(property(camelContext, java.lang.String.class, value)); return true; case "offsetcommitpolicy": case "offsetCommitPolicy": getOrCreateConfiguration(target).setOffsetCommitPolicy(property(camelContext, java.lang.String.class, value)); return true; case "offsetcommittimeoutms": case "offsetCommitTimeoutMs": getOrCreateConfiguration(target).setOffsetCommitTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "offsetflushintervalms": case "offsetFlushIntervalMs": getOrCreateConfiguration(target).setOffsetFlushIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "offsetstorage": case "offsetStorage": getOrCreateConfiguration(target).setOffsetStorage(property(camelContext, java.lang.String.class, value)); return true; case "offsetstoragefilename": case "offsetStorageFileName": getOrCreateConfiguration(target).setOffsetStorageFileName(property(camelContext, java.lang.String.class, value)); return true; case "offsetstoragepartitions": case "offsetStoragePartitions": getOrCreateConfiguration(target).setOffsetStoragePartitions(property(camelContext, int.class, value)); return true; case "offsetstoragereplicationfactor": case "offsetStorageReplicationFactor": getOrCreateConfiguration(target).setOffsetStorageReplicationFactor(property(camelContext, int.class, value)); return true; case "offsetstoragetopic": case "offsetStorageTopic": getOrCreateConfiguration(target).setOffsetStorageTopic(property(camelContext, java.lang.String.class, value)); return true; case "pollintervalms": case "pollIntervalMs": getOrCreateConfiguration(target).setPollIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "providetransactionmetadata": case "provideTransactionMetadata": getOrCreateConfiguration(target).setProvideTransactionMetadata(property(camelContext, boolean.class, value)); return true; case "queryfetchsize": case "queryFetchSize": getOrCreateConfiguration(target).setQueryFetchSize(property(camelContext, int.class, value)); return true; case "retriablerestartconnectorwaitms": case "retriableRestartConnectorWaitMs": getOrCreateConfiguration(target).setRetriableRestartConnectorWaitMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "sanitizefieldnames": case "sanitizeFieldNames": getOrCreateConfiguration(target).setSanitizeFieldNames(property(camelContext, boolean.class, value)); return true; case "signaldatacollection": case "signalDataCollection": getOrCreateConfiguration(target).setSignalDataCollection(property(camelContext, java.lang.String.class, value)); return true; case "skippedoperations": case "skippedOperations": getOrCreateConfiguration(target).setSkippedOperations(property(camelContext, java.lang.String.class, value)); return true; case "snapshotcollectionfilteroverrides": case "snapshotCollectionFilterOverrides": getOrCreateConfiguration(target).setSnapshotCollectionFilterOverrides(property(camelContext, java.lang.String.class, value)); return true; case "snapshotdelayms": case "snapshotDelayMs": getOrCreateConfiguration(target).setSnapshotDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "snapshotfetchsize": case "snapshotFetchSize": getOrCreateConfiguration(target).setSnapshotFetchSize(property(camelContext, int.class, value)); return true; case "snapshotincludecollectionlist": case "snapshotIncludeCollectionList": getOrCreateConfiguration(target).setSnapshotIncludeCollectionList(property(camelContext, java.lang.String.class, value)); return true; case "snapshotmaxthreads": case "snapshotMaxThreads": getOrCreateConfiguration(target).setSnapshotMaxThreads(property(camelContext, int.class, value)); return true; case "snapshotmode": case "snapshotMode": getOrCreateConfiguration(target).setSnapshotMode(property(camelContext, java.lang.String.class, value)); return true; case "sourcestructversion": case "sourceStructVersion": getOrCreateConfiguration(target).setSourceStructVersion(property(camelContext, java.lang.String.class, value)); return true; case "tombstonesondelete": case "tombstonesOnDelete": getOrCreateConfiguration(target).setTombstonesOnDelete(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "additionalproperties": case "additionalProperties": return java.util.Map.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "collectionexcludelist": case "collectionExcludeList": return java.lang.String.class; case "collectionincludelist": case "collectionIncludeList": return java.lang.String.class; case "configuration": return org.apache.camel.component.debezium.configuration.MongoDbConnectorEmbeddedDebeziumConfiguration.class; case "connectbackoffinitialdelayms": case "connectBackoffInitialDelayMs": return long.class; case "connectbackoffmaxdelayms": case "connectBackoffMaxDelayMs": return long.class; case "connectmaxattempts": case "connectMaxAttempts": return int.class; case "converters": return java.lang.String.class; case "databaseexcludelist": case "databaseExcludeList": return java.lang.String.class; case "databasehistoryfilefilename": case "databaseHistoryFileFilename": return java.lang.String.class; case "databaseincludelist": case "databaseIncludeList": return java.lang.String.class; case "eventprocessingfailurehandlingmode": case "eventProcessingFailureHandlingMode": return java.lang.String.class; case "fieldexcludelist": case "fieldExcludeList": return java.lang.String.class; case "fieldrenames": case "fieldRenames": return java.lang.String.class; case "heartbeatintervalms": case "heartbeatIntervalMs": return int.class; case "heartbeattopicsprefix": case "heartbeatTopicsPrefix": return java.lang.String.class; case "internalkeyconverter": case "internalKeyConverter": return java.lang.String.class; case "internalvalueconverter": case "internalValueConverter": return java.lang.String.class; case "maxbatchsize": case "maxBatchSize": return int.class; case "maxqueuesize": case "maxQueueSize": return int.class; case "maxqueuesizeinbytes": case "maxQueueSizeInBytes": return long.class; case "mongodbauthsource": case "mongodbAuthsource": return java.lang.String.class; case "mongodbconnecttimeoutms": case "mongodbConnectTimeoutMs": return int.class; case "mongodbhosts": case "mongodbHosts": return java.lang.String.class; case "mongodbmembersautodiscover": case "mongodbMembersAutoDiscover": return boolean.class; case "mongodbname": case "mongodbName": return java.lang.String.class; case "mongodbpassword": case "mongodbPassword": return java.lang.String.class; case "mongodbpollintervalms": case "mongodbPollIntervalMs": return long.class; case "mongodbserverselectiontimeoutms": case "mongodbServerSelectionTimeoutMs": return int.class; case "mongodbsockettimeoutms": case "mongodbSocketTimeoutMs": return int.class; case "mongodbsslenabled": case "mongodbSslEnabled": return boolean.class; case "mongodbsslinvalidhostnameallowed": case "mongodbSslInvalidHostnameAllowed": return boolean.class; case "mongodbuser": case "mongodbUser": return java.lang.String.class; case "offsetcommitpolicy": case "offsetCommitPolicy": return java.lang.String.class; case "offsetcommittimeoutms": case "offsetCommitTimeoutMs": return long.class; case "offsetflushintervalms": case "offsetFlushIntervalMs": return long.class; case "offsetstorage": case "offsetStorage": return java.lang.String.class; case "offsetstoragefilename": case "offsetStorageFileName": return java.lang.String.class; case "offsetstoragepartitions": case "offsetStoragePartitions": return int.class; case "offsetstoragereplicationfactor": case "offsetStorageReplicationFactor": return int.class; case "offsetstoragetopic": case "offsetStorageTopic": return java.lang.String.class; case "pollintervalms": case "pollIntervalMs": return long.class; case "providetransactionmetadata": case "provideTransactionMetadata": return boolean.class; case "queryfetchsize": case "queryFetchSize": return int.class; case "retriablerestartconnectorwaitms": case "retriableRestartConnectorWaitMs": return long.class; case "sanitizefieldnames": case "sanitizeFieldNames": return boolean.class; case "signaldatacollection": case "signalDataCollection": return java.lang.String.class; case "skippedoperations": case "skippedOperations": return java.lang.String.class; case "snapshotcollectionfilteroverrides": case "snapshotCollectionFilterOverrides": return java.lang.String.class; case "snapshotdelayms": case "snapshotDelayMs": return long.class; case "snapshotfetchsize": case "snapshotFetchSize": return int.class; case "snapshotincludecollectionlist": case "snapshotIncludeCollectionList": return java.lang.String.class; case "snapshotmaxthreads": case "snapshotMaxThreads": return int.class; case "snapshotmode": case "snapshotMode": return java.lang.String.class; case "sourcestructversion": case "sourceStructVersion": return java.lang.String.class; case "tombstonesondelete": case "tombstonesOnDelete": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { DebeziumMongodbComponent target = (DebeziumMongodbComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionalproperties": case "additionalProperties": return getOrCreateConfiguration(target).getAdditionalProperties(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "collectionexcludelist": case "collectionExcludeList": return getOrCreateConfiguration(target).getCollectionExcludeList(); case "collectionincludelist": case "collectionIncludeList": return getOrCreateConfiguration(target).getCollectionIncludeList(); case "configuration": return target.getConfiguration(); case "connectbackoffinitialdelayms": case "connectBackoffInitialDelayMs": return getOrCreateConfiguration(target).getConnectBackoffInitialDelayMs(); case "connectbackoffmaxdelayms": case "connectBackoffMaxDelayMs": return getOrCreateConfiguration(target).getConnectBackoffMaxDelayMs(); case "connectmaxattempts": case "connectMaxAttempts": return getOrCreateConfiguration(target).getConnectMaxAttempts(); case "converters": return getOrCreateConfiguration(target).getConverters(); case "databaseexcludelist": case "databaseExcludeList": return getOrCreateConfiguration(target).getDatabaseExcludeList(); case "databasehistoryfilefilename": case "databaseHistoryFileFilename": return getOrCreateConfiguration(target).getDatabaseHistoryFileFilename(); case "databaseincludelist": case "databaseIncludeList": return getOrCreateConfiguration(target).getDatabaseIncludeList(); case "eventprocessingfailurehandlingmode": case "eventProcessingFailureHandlingMode": return getOrCreateConfiguration(target).getEventProcessingFailureHandlingMode(); case "fieldexcludelist": case "fieldExcludeList": return getOrCreateConfiguration(target).getFieldExcludeList(); case "fieldrenames": case "fieldRenames": return getOrCreateConfiguration(target).getFieldRenames(); case "heartbeatintervalms": case "heartbeatIntervalMs": return getOrCreateConfiguration(target).getHeartbeatIntervalMs(); case "heartbeattopicsprefix": case "heartbeatTopicsPrefix": return getOrCreateConfiguration(target).getHeartbeatTopicsPrefix(); case "internalkeyconverter": case "internalKeyConverter": return getOrCreateConfiguration(target).getInternalKeyConverter(); case "internalvalueconverter": case "internalValueConverter": return getOrCreateConfiguration(target).getInternalValueConverter(); case "maxbatchsize": case "maxBatchSize": return getOrCreateConfiguration(target).getMaxBatchSize(); case "maxqueuesize": case "maxQueueSize": return getOrCreateConfiguration(target).getMaxQueueSize(); case "maxqueuesizeinbytes": case "maxQueueSizeInBytes": return getOrCreateConfiguration(target).getMaxQueueSizeInBytes(); case "mongodbauthsource": case "mongodbAuthsource": return getOrCreateConfiguration(target).getMongodbAuthsource(); case "mongodbconnecttimeoutms": case "mongodbConnectTimeoutMs": return getOrCreateConfiguration(target).getMongodbConnectTimeoutMs(); case "mongodbhosts": case "mongodbHosts": return getOrCreateConfiguration(target).getMongodbHosts(); case "mongodbmembersautodiscover": case "mongodbMembersAutoDiscover": return getOrCreateConfiguration(target).isMongodbMembersAutoDiscover(); case "mongodbname": case "mongodbName": return getOrCreateConfiguration(target).getMongodbName(); case "mongodbpassword": case "mongodbPassword": return getOrCreateConfiguration(target).getMongodbPassword(); case "mongodbpollintervalms": case "mongodbPollIntervalMs": return getOrCreateConfiguration(target).getMongodbPollIntervalMs(); case "mongodbserverselectiontimeoutms": case "mongodbServerSelectionTimeoutMs": return getOrCreateConfiguration(target).getMongodbServerSelectionTimeoutMs(); case "mongodbsockettimeoutms": case "mongodbSocketTimeoutMs": return getOrCreateConfiguration(target).getMongodbSocketTimeoutMs(); case "mongodbsslenabled": case "mongodbSslEnabled": return getOrCreateConfiguration(target).isMongodbSslEnabled(); case "mongodbsslinvalidhostnameallowed": case "mongodbSslInvalidHostnameAllowed": return getOrCreateConfiguration(target).isMongodbSslInvalidHostnameAllowed(); case "mongodbuser": case "mongodbUser": return getOrCreateConfiguration(target).getMongodbUser(); case "offsetcommitpolicy": case "offsetCommitPolicy": return getOrCreateConfiguration(target).getOffsetCommitPolicy(); case "offsetcommittimeoutms": case "offsetCommitTimeoutMs": return getOrCreateConfiguration(target).getOffsetCommitTimeoutMs(); case "offsetflushintervalms": case "offsetFlushIntervalMs": return getOrCreateConfiguration(target).getOffsetFlushIntervalMs(); case "offsetstorage": case "offsetStorage": return getOrCreateConfiguration(target).getOffsetStorage(); case "offsetstoragefilename": case "offsetStorageFileName": return getOrCreateConfiguration(target).getOffsetStorageFileName(); case "offsetstoragepartitions": case "offsetStoragePartitions": return getOrCreateConfiguration(target).getOffsetStoragePartitions(); case "offsetstoragereplicationfactor": case "offsetStorageReplicationFactor": return getOrCreateConfiguration(target).getOffsetStorageReplicationFactor(); case "offsetstoragetopic": case "offsetStorageTopic": return getOrCreateConfiguration(target).getOffsetStorageTopic(); case "pollintervalms": case "pollIntervalMs": return getOrCreateConfiguration(target).getPollIntervalMs(); case "providetransactionmetadata": case "provideTransactionMetadata": return getOrCreateConfiguration(target).isProvideTransactionMetadata(); case "queryfetchsize": case "queryFetchSize": return getOrCreateConfiguration(target).getQueryFetchSize(); case "retriablerestartconnectorwaitms": case "retriableRestartConnectorWaitMs": return getOrCreateConfiguration(target).getRetriableRestartConnectorWaitMs(); case "sanitizefieldnames": case "sanitizeFieldNames": return getOrCreateConfiguration(target).isSanitizeFieldNames(); case "signaldatacollection": case "signalDataCollection": return getOrCreateConfiguration(target).getSignalDataCollection(); case "skippedoperations": case "skippedOperations": return getOrCreateConfiguration(target).getSkippedOperations(); case "snapshotcollectionfilteroverrides": case "snapshotCollectionFilterOverrides": return getOrCreateConfiguration(target).getSnapshotCollectionFilterOverrides(); case "snapshotdelayms": case "snapshotDelayMs": return getOrCreateConfiguration(target).getSnapshotDelayMs(); case "snapshotfetchsize": case "snapshotFetchSize": return getOrCreateConfiguration(target).getSnapshotFetchSize(); case "snapshotincludecollectionlist": case "snapshotIncludeCollectionList": return getOrCreateConfiguration(target).getSnapshotIncludeCollectionList(); case "snapshotmaxthreads": case "snapshotMaxThreads": return getOrCreateConfiguration(target).getSnapshotMaxThreads(); case "snapshotmode": case "snapshotMode": return getOrCreateConfiguration(target).getSnapshotMode(); case "sourcestructversion": case "sourceStructVersion": return getOrCreateConfiguration(target).getSourceStructVersion(); case "tombstonesondelete": case "tombstonesOnDelete": return getOrCreateConfiguration(target).isTombstonesOnDelete(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "additionalproperties": case "additionalProperties": return java.lang.Object.class; default: return null; } } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ecs.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * An object representing the elastic network interface for tasks that use the <code>awsvpc</code> network mode. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/NetworkInterface" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class NetworkInterface implements Serializable, Cloneable, StructuredPojo { /** * <p> * The attachment ID for the network interface. * </p> */ private String attachmentId; /** * <p> * The private IPv4 address for the network interface. * </p> */ private String privateIpv4Address; /** * <p> * The private IPv6 address for the network interface. * </p> */ private String ipv6Address; /** * <p> * The attachment ID for the network interface. * </p> * * @param attachmentId * The attachment ID for the network interface. */ public void setAttachmentId(String attachmentId) { this.attachmentId = attachmentId; } /** * <p> * The attachment ID for the network interface. * </p> * * @return The attachment ID for the network interface. */ public String getAttachmentId() { return this.attachmentId; } /** * <p> * The attachment ID for the network interface. * </p> * * @param attachmentId * The attachment ID for the network interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkInterface withAttachmentId(String attachmentId) { setAttachmentId(attachmentId); return this; } /** * <p> * The private IPv4 address for the network interface. * </p> * * @param privateIpv4Address * The private IPv4 address for the network interface. */ public void setPrivateIpv4Address(String privateIpv4Address) { this.privateIpv4Address = privateIpv4Address; } /** * <p> * The private IPv4 address for the network interface. * </p> * * @return The private IPv4 address for the network interface. */ public String getPrivateIpv4Address() { return this.privateIpv4Address; } /** * <p> * The private IPv4 address for the network interface. * </p> * * @param privateIpv4Address * The private IPv4 address for the network interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkInterface withPrivateIpv4Address(String privateIpv4Address) { setPrivateIpv4Address(privateIpv4Address); return this; } /** * <p> * The private IPv6 address for the network interface. * </p> * * @param ipv6Address * The private IPv6 address for the network interface. */ public void setIpv6Address(String ipv6Address) { this.ipv6Address = ipv6Address; } /** * <p> * The private IPv6 address for the network interface. * </p> * * @return The private IPv6 address for the network interface. */ public String getIpv6Address() { return this.ipv6Address; } /** * <p> * The private IPv6 address for the network interface. * </p> * * @param ipv6Address * The private IPv6 address for the network interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkInterface withIpv6Address(String ipv6Address) { setIpv6Address(ipv6Address); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAttachmentId() != null) sb.append("AttachmentId: ").append(getAttachmentId()).append(","); if (getPrivateIpv4Address() != null) sb.append("PrivateIpv4Address: ").append(getPrivateIpv4Address()).append(","); if (getIpv6Address() != null) sb.append("Ipv6Address: ").append(getIpv6Address()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof NetworkInterface == false) return false; NetworkInterface other = (NetworkInterface) obj; if (other.getAttachmentId() == null ^ this.getAttachmentId() == null) return false; if (other.getAttachmentId() != null && other.getAttachmentId().equals(this.getAttachmentId()) == false) return false; if (other.getPrivateIpv4Address() == null ^ this.getPrivateIpv4Address() == null) return false; if (other.getPrivateIpv4Address() != null && other.getPrivateIpv4Address().equals(this.getPrivateIpv4Address()) == false) return false; if (other.getIpv6Address() == null ^ this.getIpv6Address() == null) return false; if (other.getIpv6Address() != null && other.getIpv6Address().equals(this.getIpv6Address()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAttachmentId() == null) ? 0 : getAttachmentId().hashCode()); hashCode = prime * hashCode + ((getPrivateIpv4Address() == null) ? 0 : getPrivateIpv4Address().hashCode()); hashCode = prime * hashCode + ((getIpv6Address() == null) ? 0 : getIpv6Address().hashCode()); return hashCode; } @Override public NetworkInterface clone() { try { return (NetworkInterface) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.ecs.model.transform.NetworkInterfaceMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.session; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.session.data.redis.RedisFlushMode; import org.springframework.session.hazelcast.HazelcastFlushMode; /** * Configuration properties for Spring Session. * * @author Tommy Ludwig * @author Stephane Nicoll * @author Vedran Pavic * @since 1.4.0 */ @ConfigurationProperties(prefix = "spring.session") public class SessionProperties { /** * Session store type. */ private StoreType storeType; private Integer timeout; private final Hazelcast hazelcast = new Hazelcast(); private final Jdbc jdbc = new Jdbc(); private final Redis redis = new Redis(); public SessionProperties(ObjectProvider<ServerProperties> serverProperties) { ServerProperties properties = serverProperties.getIfUnique(); this.timeout = (properties != null ? properties.getSession().getTimeout() : null); } public StoreType getStoreType() { return this.storeType; } public void setStoreType(StoreType storeType) { this.storeType = storeType; } /** * Return the session timeout in seconds. * @return the session timeout in seconds * @see ServerProperties#getSession() */ public Integer getTimeout() { return this.timeout; } public Hazelcast getHazelcast() { return this.hazelcast; } public Jdbc getJdbc() { return this.jdbc; } public Redis getRedis() { return this.redis; } public static class Hazelcast { /** * Name of the map used to store sessions. */ private String mapName = "spring:session:sessions"; /** * Sessions flush mode. */ private HazelcastFlushMode flushMode = HazelcastFlushMode.ON_SAVE; public String getMapName() { return this.mapName; } public void setMapName(String mapName) { this.mapName = mapName; } public HazelcastFlushMode getFlushMode() { return this.flushMode; } public void setFlushMode(HazelcastFlushMode flushMode) { this.flushMode = flushMode; } } public static class Jdbc { private static final String DEFAULT_SCHEMA_LOCATION = "classpath:org/springframework/" + "session/jdbc/schema-@@platform@@.sql"; private static final String DEFAULT_TABLE_NAME = "SPRING_SESSION"; /** * Path to the SQL file to use to initialize the database schema. */ private String schema = DEFAULT_SCHEMA_LOCATION; /** * Name of database table used to store sessions. */ private String tableName = DEFAULT_TABLE_NAME; private final Initializer initializer = new Initializer(); public String getSchema() { return this.schema; } public void setSchema(String schema) { this.schema = schema; } public String getTableName() { return this.tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public Initializer getInitializer() { return this.initializer; } public class Initializer { /** * Create the required session tables on startup if necessary. Enabled * automatically if the default table name is set or a custom schema is * configured. */ private Boolean enabled; public boolean isEnabled() { if (this.enabled != null) { return this.enabled; } boolean defaultTableName = DEFAULT_TABLE_NAME .equals(Jdbc.this.getTableName()); boolean customSchema = !DEFAULT_SCHEMA_LOCATION .equals(Jdbc.this.getSchema()); return (defaultTableName || customSchema); } public void setEnabled(boolean enabled) { this.enabled = enabled; } } } public static class Redis { /** * Namespace for keys used to store sessions. */ private String namespace = ""; /** * Sessions flush mode. */ private RedisFlushMode flushMode = RedisFlushMode.ON_SAVE; public String getNamespace() { return this.namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public RedisFlushMode getFlushMode() { return this.flushMode; } public void setFlushMode(RedisFlushMode flushMode) { this.flushMode = flushMode; } } }
package com.eolwral.osmonitor.classical; import java.io.DataOutputStream; import java.io.IOException; import android.app.ActivityManager; import android.os.Handler; import android.os.Message; import android.content.Context; public class JNIInterface { private static JNIInterface singletone = null; // Design Pattern "Singletone" public static JNIInterface getInstance() { if(singletone == null) { System.loadLibrary("osmonitor"); singletone = new JNIInterface(); } return singletone; } /* Load Module */ public final int doTaskProcess = 1; public final int doTaskInterface = 2; public final int doTaskNetwork = 3; public final int doTaskMisc = 4; public final int doTaskDMesg = 5; public final int doTaskLogcat = 6; public native int doTaskStop(); public native int doTaskStart(int TaskType); public native int doDataLoad(); public native int doDataSwap(); public native int doDataRefresh(); public native int doDataTime(int Time); public native int doCPUUpdate(int Update); /* Root */ public native int GetRooted(); /* CPU */ public native String GetCPUUsage(); public native int GetCPUUsageValue(); /* Processor */ public native int GetProcessorMax(); public native int GetProcessorMin(); public native int GetProcessorScalMax(); public native int GetProcessorScalMin(); public native int GetProcessorScalCur(); public native int GetProcessorOMAPTemp(); public native String GetProcessorScalGov(); /* Memory */ public native long GetMemTotal(); public native long GetMemFree(); public native long GetMemCached(); public native long GetMemBuffer(); /* Power */ public native int GetPowerCapacity(); public native int GetPowerVoltage(); public native int GetPowerTemperature(); public native int GetUSBOnline(); public native int GetACOnline(); public native String GetPowerHealth(); public native String GetPowerStatus(); public native String GetPowerTechnology(); /* Disk */ public native double GetSystemMemTotal(); public native double GetDataMemTotal(); public native double GetSDCardMemTotal(); public native double GetCacheMemTotal(); public native double GetSystemMemUsed(); public native double GetDataMemUsed(); public native double GetSDCardMemUsed(); public native double GetCacheMemUsed(); public native double GetSystemMemAvail(); public native double GetDataMemAvail(); public native double GetSDCardMemAvail(); public native double GetCacheMemAvail(); /* Process */ public final int doSortPID = 1; public final int doSortLoad = 2; public final int doSortMem = 3; public final int doSortThreads = 4; public final int doSortName = 5; public final int doOrderASC = 0; public final int doOrderDESC = 1; public native int SetProcessFilter(int Filter); public native int SetProcessAlgorithm(int Algorithm); public native int SetProcessSort(int Sort); public native int SetProcessOrder(int Order); public native int GetProcessCounts(); public native int GetProcessPID(int position); public native int GetProcessUID(int position); public native int GetProcessLoad(int position); public native long GetProcessUTime(int position); public native long GetProcessSTime(int position); public native int GetProcessThreads(int position); public native long GetProcessRSS(int position); public native String GetProcessName(int position); public native String GetProcessOwner(int position); public native String GetProcessStatus(int position); public native String GetProcessNamebyUID(int uid); public native int doInterfaceNext(); public native int doInterfaceReset(); public native int GetInterfaceCounts(); public native int GetInterfaceOutSize(int position); public native int GetInterfaceInSize(int position); public native String GetInterfaceName(int position); public native String GetInterfaceAddr(int position); public native String GetInterfaceAddr6(int position); public native String GetInterfaceNetMask(int position); public native String GetInterfaceNetMask6(int position); public native String GetInterfaceMac(int position); public native String GetInterfaceScope(int position); public native String GetInterfaceFlags(int position); public native int SetNetworkIP6To4(int value); public native int GetNetworkCounts(); public native String GetNetworkProtocol(int position); public native String GetNetworkLocalIP(int position); public native int GetNetworkLocalPort(int position); public native String GetNetworkRemoteIP(int position); public native int GetNetworkRemotePort(int position); public native String GetNetworkStatus(int position); public native int GetNetworkUID(int position); /* 0: KERN_EMERG 1: KERN_ALERT 2: KERN_CRIT 3: KERN_ERR 4: KERN_WARNING 5: KERN_NOTICE 6: KERN_INFO 7: KERN_DEBUG */ public final int doDMesgEMERG = 1; public final int doDMesgALERT = 2; public final int doDMesgERR = 3; public final int doDMesgWARNING = 4; public final int doDMesgNOTICE = 5; public final int doDMesgINFO = 6; public final int doDMesgDEBUG = 7; public final int doDMesgNONE = 8; public native int GetDebugMessageCounts(); public native String GetDebugMessageTime(int position); public native String GetDebugMessageLevel(int position); public native String GetDebugMessage(int position); public native int SetDebugMessageLevel(int value); public native int SetDebugMessage(String filter); public native int SetDebugMessageFilter(int value); public native String GetDebugMessage(); public final int doLogcatNONE = 0; public final int doLogcatVERBOSE = 2; public final int doLogcatDEBUG = 3; public final int doLogcatINFO = 4; public final int doLogcatWARN = 5; public final int doLogcatERROR = 6; public final int doLogcatFATAL = 7; public native int GetLogcatCounts(); public native int GetLogcatSize(); public native int GetLogcatCurrentSize(); public native String GetLogcatLevel(int position); public native int GetLogcatPID(int position); public native String GetLogcatTime(int position); public native String GetLogcatTag(int position); public native String GetLogcatMessage(int position); public native int SetLogcatSource(int value); public native int SetLogcatFilter(int value); public native int SetLogcatPID(int value); public native int SetLogcatLevel(int value); public native int SetLogcatMessage(String filter); public void execCommand(String command) { try { Process shProc = Runtime.getRuntime().exec("su"); DataOutputStream InputCmd = new DataOutputStream(shProc.getOutputStream()); InputCmd.writeBytes(command); // Close the terminal InputCmd.writeBytes("exit\n"); InputCmd.flush(); InputCmd.close(); try { shProc.waitFor(); } catch (InterruptedException e) { }; } catch (IOException e) {} } private static Handler EndHelper = new Handler() { public void handleMessage(Message msg) { android.os.Process.killProcess(android.os.Process.myPid()); } }; public void killSelf(Context target) { if(CompareFunc.getSDKVersion() <= 7) { ((ActivityManager) target.getSystemService(Context.ACTIVITY_SERVICE)) .restartPackage("com.eolwral.osmonitor.classical"); } else { EndHelper.sendEmptyMessageDelayed(0, 500); } } }
package org.sistemafinanciero.entity.dto; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class ResumenOperacionesCaja implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; @XmlElement private String agencia; @XmlElement private String caja; @XmlElement private Date fechaApertura; @XmlElement private Date fechaCierre; @XmlElement private Date horaApertura; @XmlElement private Date horaCierre; @XmlElement private String trabajador; @XmlElement private int depositosAporte; @XmlElement private int depositosPlazoFijo; @XmlElement private int depositosLibre; @XmlElement private int depositosRecaudadora; @XmlElement private int retirosAporte; @XmlElement private int retirosPlazoFijo; @XmlElement private int retirosLibre; @XmlElement private int retirosRecaudadora; @XmlElement private int compra; @XmlElement private int venta; @XmlElement private int transExtornadoDepositoRetiro; @XmlElement private int transExtornadoCompraVenta; @XmlElement private int transExtornadoAporte; @XmlElement private int transExtornadoCheque; @XmlElement private int depositoMayorCuantia; @XmlElement private int retiroMayorCuantia; @XmlElement private int compraVentaMayorCuantia; @XmlElement private int enviadoCajaCaja; @XmlElement private int recibidoCajaCaja; @XmlElement private int enviadoBovedaCaja; @XmlElement private int recibidoBovedaCaja; @XmlElement private int sobrante; @XmlElement private int faltante; @XmlElement private int pendienteSobrante; @XmlElement private int pendienteFaltante; @XmlElement private int transaccionCheque; public String getAgencia() { return agencia; } public void setAgencia(String agencia) { this.agencia = agencia; } public String getCaja() { return caja; } public void setCaja(String caja) { this.caja = caja; } public Date getFechaApertura() { return fechaApertura; } public void setFechaApertura(Date fechaApertura) { this.fechaApertura = fechaApertura; } public Date getFechaCierre() { return fechaCierre; } public void setFechaCierre(Date fechaCierre) { this.fechaCierre = fechaCierre; } public Date getHoraApertura() { return horaApertura; } public void setHoraApertura(Date horaApertura) { this.horaApertura = horaApertura; } public Date getHoraCierre() { return horaCierre; } public void setHoraCierre(Date horaCierre) { this.horaCierre = horaCierre; } public String getTrabajador() { return trabajador; } public void setTrabajador(String trabajador) { this.trabajador = trabajador; } public int getDepositosAporte() { return depositosAporte; } public void setDepositosAporte(int depositosAporte) { this.depositosAporte = depositosAporte; } public int getDepositosPlazoFijo() { return depositosPlazoFijo; } public void setDepositosPlazoFijo(int depositosPlazoFijo) { this.depositosPlazoFijo = depositosPlazoFijo; } public int getDepositosLibre() { return depositosLibre; } public void setDepositosLibre(int depositosLibre) { this.depositosLibre = depositosLibre; } public int getDepositosRecaudadora() { return depositosRecaudadora; } public void setDepositosRecaudadora(int depositosRecaudadora) { this.depositosRecaudadora = depositosRecaudadora; } public int getRetirosAporte() { return retirosAporte; } public void setRetirosAporte(int retirosAporte) { this.retirosAporte = retirosAporte; } public int getRetirosPlazoFijo() { return retirosPlazoFijo; } public void setRetirosPlazoFijo(int retirosPlazoFijo) { this.retirosPlazoFijo = retirosPlazoFijo; } public int getRetirosLibre() { return retirosLibre; } public void setRetirosLibre(int retirosLibre) { this.retirosLibre = retirosLibre; } public int getRetirosRecaudadora() { return retirosRecaudadora; } public void setRetirosRecaudadora(int retirosRecaudadora) { this.retirosRecaudadora = retirosRecaudadora; } public int getCompra() { return compra; } public void setCompra(int compra) { this.compra = compra; } public int getVenta() { return venta; } public void setVenta(int venta) { this.venta = venta; } public int getTransExtornadoDepositoRetiro() { return transExtornadoDepositoRetiro; } public void setTransExtornadoDepositoRetiro(int transExtornadoDepositoRetiro) { this.transExtornadoDepositoRetiro = transExtornadoDepositoRetiro; } public int getTransExtornadoCompraVenta() { return transExtornadoCompraVenta; } public void setTransExtornadoCompraVenta(int transExtornadoCompraVenta) { this.transExtornadoCompraVenta = transExtornadoCompraVenta; } public int getTransExtornadoAporte() { return transExtornadoAporte; } public void setTransExtornadoAporte(int transExtornadoAporte) { this.transExtornadoAporte = transExtornadoAporte; } public int getDepositoMayorCuantia() { return depositoMayorCuantia; } public void setDepositoMayorCuantia(int depositoMayorCuantia) { this.depositoMayorCuantia = depositoMayorCuantia; } public int getRetiroMayorCuantia() { return retiroMayorCuantia; } public void setRetiroMayorCuantia(int retiroMayorCuantia) { this.retiroMayorCuantia = retiroMayorCuantia; } public int getCompraVentaMayorCuantia() { return compraVentaMayorCuantia; } public void setCompraVentaMayorCuantia(int compraVentaMayorCuantia) { this.compraVentaMayorCuantia = compraVentaMayorCuantia; } public int getEnviadoCajaCaja() { return enviadoCajaCaja; } public void setEnviadoCajaCaja(int enviadoCajaCaja) { this.enviadoCajaCaja = enviadoCajaCaja; } public int getRecibidoCajaCaja() { return recibidoCajaCaja; } public void setRecibidoCajaCaja(int recibidoCajaCaja) { this.recibidoCajaCaja = recibidoCajaCaja; } public int getEnviadoBovedaCaja() { return enviadoBovedaCaja; } public void setEnviadoBovedaCaja(int enviadoBovedaCaja) { this.enviadoBovedaCaja = enviadoBovedaCaja; } public int getRecibidoBovedaCaja() { return recibidoBovedaCaja; } public void setRecibidoBovedaCaja(int recibidoBovedaCaja) { this.recibidoBovedaCaja = recibidoBovedaCaja; } public int getSobrante() { return sobrante; } public void setSobrante(int sobrante) { this.sobrante = sobrante; } public int getFaltante() { return faltante; } public void setFaltante(int faltante) { this.faltante = faltante; } public int getPendienteSobrante() { return pendienteSobrante; } public void setPendienteSobrante(int pendienteSobrante) { this.pendienteSobrante = pendienteSobrante; } public int getPendienteFaltante() { return pendienteFaltante; } public void setPendienteFaltante(int pendienteFaltante) { this.pendienteFaltante = pendienteFaltante; } public int getTransaccionCheque() { return transaccionCheque; } public void setTransaccionCheque(int transaccionCheque) { this.transaccionCheque = transaccionCheque; } public int getTransExtornadoCheque() { return transExtornadoCheque; } public void setTransExtornadoCheque(int transExtornadoCheque) { this.transExtornadoCheque = transExtornadoCheque; } }
/* * 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.kafka.common.requests; import org.apache.kafka.common.network.NetworkSend; import org.apache.kafka.common.network.Send; import org.apache.kafka.common.protocol.ApiKeys; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.protocol.types.Struct; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public abstract class AbstractResponse implements AbstractRequestResponse { public static final int DEFAULT_THROTTLE_TIME = 0; protected Send toSend(String destination, ResponseHeader header, short apiVersion) { return new NetworkSend(destination, RequestUtils.serialize(header.toStruct(), toStruct(apiVersion))); } /** * Visible for testing, typically {@link #toSend(String, ResponseHeader, short)} should be used instead. */ public ByteBuffer serialize(short version, ResponseHeader responseHeader) { return RequestUtils.serialize(responseHeader.toStruct(), toStruct(version)); } /** * Visible for testing, typically {@link #toSend(String, ResponseHeader, short)} should be used instead. */ public ByteBuffer serialize(ApiKeys apiKey, short version, int correlationId) { ResponseHeader header = new ResponseHeader(correlationId, apiKey.responseHeaderVersion(version)); return RequestUtils.serialize(header.toStruct(), toStruct(version)); } public abstract Map<Errors, Integer> errorCounts(); protected Map<Errors, Integer> errorCounts(Errors error) { return Collections.singletonMap(error, 1); } protected Map<Errors, Integer> errorCounts(Stream<Errors> errors) { return errors.collect(Collectors.groupingBy(e -> e, Collectors.summingInt(e -> 1))); } protected Map<Errors, Integer> errorCounts(Collection<Errors> errors) { Map<Errors, Integer> errorCounts = new HashMap<>(); for (Errors error : errors) updateErrorCounts(errorCounts, error); return errorCounts; } protected Map<Errors, Integer> apiErrorCounts(Map<?, ApiError> errors) { Map<Errors, Integer> errorCounts = new HashMap<>(); for (ApiError apiError : errors.values()) updateErrorCounts(errorCounts, apiError.error()); return errorCounts; } protected void updateErrorCounts(Map<Errors, Integer> errorCounts, Errors error) { Integer count = errorCounts.getOrDefault(error, 0); errorCounts.put(error, count + 1); } protected abstract Struct toStruct(short version); public static AbstractResponse parseResponse(ApiKeys apiKey, Struct struct, short version) { switch (apiKey) { case PRODUCE: return new ProduceResponse(struct); case FETCH: return FetchResponse.parse(struct); case LIST_OFFSETS: return new ListOffsetResponse(struct); case METADATA: return new MetadataResponse(struct, version); case OFFSET_COMMIT: return new OffsetCommitResponse(struct, version); case OFFSET_FETCH: return new OffsetFetchResponse(struct, version); case FIND_COORDINATOR: return new FindCoordinatorResponse(struct, version); case JOIN_GROUP: return new JoinGroupResponse(struct, version); case HEARTBEAT: return new HeartbeatResponse(struct, version); case LEAVE_GROUP: return new LeaveGroupResponse(struct, version); case SYNC_GROUP: return new SyncGroupResponse(struct, version); case STOP_REPLICA: return new StopReplicaResponse(struct, version); case CONTROLLED_SHUTDOWN: return new ControlledShutdownResponse(struct, version); case UPDATE_METADATA: return new UpdateMetadataResponse(struct, version); case LEADER_AND_ISR: return new LeaderAndIsrResponse(struct, version); case DESCRIBE_GROUPS: return new DescribeGroupsResponse(struct, version); case LIST_GROUPS: return new ListGroupsResponse(struct, version); case SASL_HANDSHAKE: return new SaslHandshakeResponse(struct, version); case API_VERSIONS: return ApiVersionsResponse.fromStruct(struct, version); case CREATE_TOPICS: return new CreateTopicsResponse(struct, version); case DELETE_TOPICS: return new DeleteTopicsResponse(struct, version); case DELETE_RECORDS: return new DeleteRecordsResponse(struct, version); case INIT_PRODUCER_ID: return new InitProducerIdResponse(struct, version); case OFFSET_FOR_LEADER_EPOCH: return new OffsetsForLeaderEpochResponse(struct); case ADD_PARTITIONS_TO_TXN: return new AddPartitionsToTxnResponse(struct, version); case ADD_OFFSETS_TO_TXN: return new AddOffsetsToTxnResponse(struct, version); case END_TXN: return new EndTxnResponse(struct, version); case WRITE_TXN_MARKERS: return new WriteTxnMarkersResponse(struct, version); case TXN_OFFSET_COMMIT: return new TxnOffsetCommitResponse(struct, version); case DESCRIBE_ACLS: return new DescribeAclsResponse(struct, version); case CREATE_ACLS: return new CreateAclsResponse(struct, version); case DELETE_ACLS: return new DeleteAclsResponse(struct, version); case DESCRIBE_CONFIGS: return new DescribeConfigsResponse(struct); case ALTER_CONFIGS: return new AlterConfigsResponse(struct, version); case ALTER_REPLICA_LOG_DIRS: return new AlterReplicaLogDirsResponse(struct); case DESCRIBE_LOG_DIRS: return new DescribeLogDirsResponse(struct, version); case SASL_AUTHENTICATE: return new SaslAuthenticateResponse(struct, version); case CREATE_PARTITIONS: return new CreatePartitionsResponse(struct, version); case CREATE_DELEGATION_TOKEN: return new CreateDelegationTokenResponse(struct, version); case RENEW_DELEGATION_TOKEN: return new RenewDelegationTokenResponse(struct, version); case EXPIRE_DELEGATION_TOKEN: return new ExpireDelegationTokenResponse(struct, version); case DESCRIBE_DELEGATION_TOKEN: return new DescribeDelegationTokenResponse(struct, version); case DELETE_GROUPS: return new DeleteGroupsResponse(struct, version); case ELECT_LEADERS: return new ElectLeadersResponse(struct, version); case INCREMENTAL_ALTER_CONFIGS: return new IncrementalAlterConfigsResponse(struct, version); case ALTER_PARTITION_REASSIGNMENTS: return new AlterPartitionReassignmentsResponse(struct, version); case LIST_PARTITION_REASSIGNMENTS: return new ListPartitionReassignmentsResponse(struct, version); case OFFSET_DELETE: return new OffsetDeleteResponse(struct, version); case DESCRIBE_CLIENT_QUOTAS: return new DescribeClientQuotasResponse(struct, version); case ALTER_CLIENT_QUOTAS: return new AlterClientQuotasResponse(struct, version); default: throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseResponse`, the " + "code should be updated to do so.", apiKey)); } } /** * Returns whether or not client should throttle upon receiving a response of the specified version with a non-zero * throttle time. Client-side throttling is needed when communicating with a newer version of broker which, on * quota violation, sends out responses before throttling. */ public boolean shouldClientThrottle(short version) { return false; } public int throttleTimeMs() { return DEFAULT_THROTTLE_TIME; } public String toString(short version) { return toStruct(version).toString(); } }
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.plugins.haxe.lang.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes; import com.intellij.plugins.haxe.lang.psi.*; import com.intellij.plugins.haxe.util.HaxeDebugLogger; import com.intellij.plugins.haxe.util.UsefulPsiTreeUtil; import com.intellij.psi.*; import com.intellij.psi.impl.PsiSuperMethodImplUtil; import com.intellij.psi.impl.source.tree.java.PsiTypeParameterImpl; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.apache.log4j.Level; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by ebishton on 10/22/14. */ public class HaxeTypeListPartPsiMixinImpl extends HaxePsiCompositeElementImpl implements HaxeTypeListPartPsiMixin { // XXX: TypeListPart might be better just being a private entry in the BNF. I'm not sure. // // The thing I most dislike about subclassing PsiTypeParameter is that it implements // the PsiClass interface. One of the (three possible)child elements that this class // holds is HaxeAnonymousType, which itself derives from HaxeClass (thus, PsiClass). // So, I'd prefer that HaxeTypePsiMixin implement the class interface. Then we // would have better balance between the child implementations (and less special code) // and we can cleanly ignore this class in the hierarchy. // // The third child type that we can hold is HaxeFunctionType, which is simply a // construct for holding (effectively) a typedef, described via the arrow notation: // type -> type -> return_type // This type doesn't really support a class, just gives a function pointer. So, now // we've got a mostly empty stub class as well... static Logger LOG = Logger.getInstance("#com.intellij.plugins.haxe.lang.psi.impl.HaxeTypeListPartPsiMixinImpl"); static { LOG.setLevel(Level.DEBUG); } // The child type that implements an interface for one of these three parameter types. // We can't assign this type in the constructor because the children aren't known // (to us) at construction time. We'll check it later when one of the interfaces // are hit. PsiClass myChildClass = null; HaxeTypeListPartPsiMixinImpl(ASTNode node) { super(node); } @NotNull private PsiClass getDelegate() { // We're going to try to cache our child. If the code changes, then this reference // may refer to the wrong class. In that case, it would be better to do the // lookup (resolveHaxeClass()), which has a caching algorithm of its own and // deals with naming changes accordingly. if (null == myChildClass) { PsiElement child = getFirstChild(); PsiElement target = null; ASTNode node = child.getNode(); if ( null != node ) { IElementType type = node.getElementType(); if (HaxeTokenTypes.TYPE_OR_ANONYMOUS.equals(type)) { target = child.getFirstChild(); IElementType targetType = target.getNode().getElementType(); if (HaxeTokenTypes.TYPE.equals(targetType)) { myChildClass = new HaxeClassDelegateForTypeChild((HaxeType)target); } else if (HaxeTokenTypes.ANONYMOUS_TYPE.equals(targetType)){ myChildClass = (HaxeAnonymousType) target; } else { LOG.debug("Target: " + target.toString()); LOG.assertTrue(false, "Unexpected token type for child of TYPE_OR_ANONYMOUS"); myChildClass = AbstractHaxePsiClass.createEmptyFacade(getProject()); } } else if (HaxeTokenTypes.FUNCTION_TYPE.equals(type)) { // FIXME: Temporary Hack to get around an unexpected PSI state #627. try { myChildClass = (HaxeAnonymousType) child; } catch(ClassCastException e) { HaxeDebugLogger.getLogger().warn("Unexpected PSI state. See issue #627"); myChildClass = AbstractHaxePsiClass.createEmptyFacade(getProject()); } } else { myChildClass = AbstractHaxePsiClass.createEmptyFacade(getProject()); } } else { // No child node? How can this be? LOG.assertTrue(false, "No child node found for TYPE_LIST_PART"); myChildClass = AbstractHaxePsiClass.createEmptyFacade(getProject()); } } return myChildClass; } // // PsiTypeParameter overrides // @Override public PsiTypeParameterListOwner getOwner() { final PsiElement parent = getParent(); if (parent == null) throw new PsiInvalidElementAccessException(this); return PsiTreeUtil.getParentOfType(this, PsiTypeParameterListOwner.class); } @Override public int getIndex() { int ret = 0; PsiElement element = getPrevSibling(); while (element != null) { if (element instanceof PsiTypeParameter) { ret++; } element = element.getPrevSibling(); } return ret; } // // PsiClass overrides // @Nullable @Override public String getQualifiedName() { return getDelegate().getQualifiedName(); } @Override public boolean isInterface() { return getDelegate().isInterface(); } @Override public boolean isAnnotationType() { return getDelegate().isAnnotationType(); } @Override public boolean isEnum() { return getDelegate().isEnum(); } @Override @NotNull public PsiField[] getFields() { return getDelegate().getFields(); } @Override @NotNull public PsiMethod[] getMethods() { return getDelegate().getMethods(); } @Override public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) { return getDelegate().findMethodBySignature(patternMethod, checkBases); } @Override @NotNull public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { return getDelegate().findMethodsBySignature(patternMethod, checkBases); } @Override public PsiField findFieldByName(String name, boolean checkBases) { return getDelegate().findFieldByName(name, checkBases); } @Override @NotNull public PsiMethod[] findMethodsByName(String name, boolean checkBases) { return getDelegate().findMethodsByName(name, checkBases); } @Override @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) { return getDelegate().findMethodsAndTheirSubstitutorsByName(name, checkBases); } @Override @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() { return getDelegate().getAllMethodsAndTheirSubstitutors(); } @Override public PsiClass findInnerClassByName(String name, boolean checkBases) { return getDelegate().findInnerClassByName(name, checkBases); } @Override public PsiTypeParameterList getTypeParameterList() { return getDelegate().getTypeParameterList(); } @Override public boolean hasTypeParameters() { return getDelegate().hasTypeParameters(); } @Override public PsiElement getScope() { return getDelegate().getScope(); } @Override public boolean isInheritorDeep(PsiClass baseClass, PsiClass classToByPass) { return getDelegate().isInheritorDeep(baseClass, classToByPass); } @Override public boolean isInheritor(@NotNull PsiClass baseClass, boolean checkDeep) { return getDelegate().isInheritor(baseClass, checkDeep); } @Override @Nullable public PsiIdentifier getNameIdentifier() { return getDelegate().getNameIdentifier(); } @Override public PsiElement setName(@NotNull String name) throws IncorrectOperationException { return getDelegate().setName(name); } @Override @NotNull public PsiMethod[] getConstructors() { return getDelegate().getConstructors(); } @Override public PsiDocComment getDocComment() { return getDelegate().getDocComment(); } @Override public boolean isDeprecated() { return getDelegate().isDeprecated(); } @Override @NotNull public PsiReferenceList getExtendsList() { return getDelegate().getExtendsList(); } @Override public PsiReferenceList getImplementsList() { return getDelegate().getImplementsList(); } @Override @NotNull public PsiClassType[] getExtendsListTypes() { return getDelegate().getExtendsListTypes(); } @Override @NotNull public PsiClassType[] getImplementsListTypes() { return getDelegate().getImplementsListTypes(); } @Override @NotNull public PsiClass[] getInnerClasses() { return getDelegate().getInnerClasses(); } @Override @NotNull public PsiField[] getAllFields() { return getDelegate().getAllFields(); } @Override @NotNull public PsiMethod[] getAllMethods() { return getDelegate().getAllMethods(); } @Override @NotNull public PsiClass[] getAllInnerClasses() { return getDelegate().getAllInnerClasses(); } @Override @NotNull public PsiClassInitializer[] getInitializers() { return getDelegate().getInitializers(); } @Override @NotNull public PsiTypeParameter[] getTypeParameters() { return getDelegate().getTypeParameters(); } @Override public PsiClass getSuperClass() { return getDelegate().getSuperClass(); } @Override public PsiClass[] getInterfaces() { return getDelegate().getInterfaces(); } @Override @NotNull public PsiClass[] getSupers() { return getDelegate().getSupers(); } @Override @NotNull public PsiClassType[] getSuperTypes() { return getDelegate().getSuperTypes(); } @Override public PsiClass getContainingClass() { return getDelegate().getContainingClass(); } @Override @NotNull public Collection<HierarchicalMethodSignature> getVisibleSignatures() { return getDelegate().getVisibleSignatures(); } @Override public HaxeModifierList getModifierList() { return (HaxeModifierList) getDelegate().getModifierList(); } @Override public boolean hasModifierProperty(@NotNull String name) { return getDelegate().hasModifierProperty(name); } @Override public PsiJavaToken getLBrace() { // Casting this is only doable because HaxeAstFactory // creates PsiJavaTokens. return (PsiJavaToken)getDelegate().getLBrace(); } @Override public PsiJavaToken getRBrace() { return (PsiJavaToken) getDelegate().getRBrace(); } // // PsiAnnotationOwner // @Override @NotNull public PsiAnnotation[] getAnnotations() { // Type parameters don't get modifiers. return PsiAnnotation.EMPTY_ARRAY; } @Override public PsiAnnotation findAnnotation(@NotNull @NonNls String qualifiedName) { // Type parameters don't get modifiers. return null; } @Override @NotNull public PsiAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) { throw new IncorrectOperationException(); } @Override @NotNull public PsiAnnotation[] getApplicableAnnotations() { return getAnnotations(); } // ////////////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////////////// // // HaxeTypeListPartForTypeChild // // ////////////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////////////// /** * Deals with type references that appear as children to HaxeTypeOrAnonymous * child elements. */ private class HaxeClassDelegateForTypeChild extends PsiTypeParameterImpl { private HaxeType myChildType = null; public HaxeClassDelegateForTypeChild(@NotNull HaxeType childType) { super(childType.getNode()); myChildType = childType; } @NotNull protected HaxeReference getDelegate() { return myChildType.getReferenceExpression(); } @Nullable protected HaxeClass getResolvedDelegate() { PsiElement elem = getDelegate().resolve(); return elem instanceof HaxeClass? (HaxeClass) elem : null; } // // PsiTypeParameter overrides // // PsiTypeParameter extends PsiClass instead of a reference. It just stubs // out most of the functionality. @Override @Nullable public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) { // XXX: If it turns out that we need this method, we need to find the // actual class implementation (getDelegate().resolveHaxeClass()) // and call that. LOG.warn("Unexpected call to findMethodBySignature()"); return null; } @Override @NotNull public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { LOG.warn("Unexpected call to findMethodsBySignature()"); return PsiMethod.EMPTY_ARRAY; } @Override public PsiField findFieldByName(String name, boolean checkBases) { LOG.warn("Unexpected call to findFieldByName()"); return null; } @Override @NotNull public PsiMethod[] findMethodsByName(String name, boolean checkBases) { LOG.warn("Unexpected call to findMethodsByName()"); return PsiMethod.EMPTY_ARRAY; } @Override @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) { LOG.warn("Unexpected call to findMethodsAndTheirSubstitutorsByName()"); return new ArrayList<Pair<PsiMethod,PsiSubstitutor>>(); } @Override @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() { LOG.warn("Unexpected call to getAllMethodsAndTheirSubstitutors"); return new ArrayList<Pair<PsiMethod,PsiSubstitutor>>(); } @Override public PsiClass findInnerClassByName(String name, boolean checkBases) { return null; // No named inner classes in Haxe. } @Override public PsiElement getScope() { /** * Returns the PSI member in which the class has been declared (for example, * the method containing the anonymous inner class, or the file containing a regular * class, or the class owning a type parameter). */ // As a TypeListPart, we are only children of extends, implements, and generic parameters. // In each of these cases, the class for which we are being declared (which may be // an anonymous type) is the scope. PsiElement parent = getParent(); while (parent != null) { IElementType parentType = parent.getNode().getElementType(); if (HaxeTokenTypes.ANONYMOUS_TYPE.equals(parentType) || (HaxeTokenTypes.CLASS_DECLARATION.equals(parentType)) || parent instanceof HaxeFile ) // HaxeFile is a catchall.. { break; } parent = parent.getParent(); } return parent; } @NotNull @Override public PsiIdentifier getNameIdentifier() { // For a HaxeType, the identifier is two children below. The first is // a reference. HaxeReferenceExpression ref = PsiTreeUtil.getRequiredChildOfType(this, HaxeReferenceExpression.class); if (ref.getFirstChild() instanceof HaxeReferenceExpression) { ref = UsefulPsiTreeUtil.getLastChild(ref, HaxeReferenceExpression.class, ref); } HaxeIdentifier id = PsiTreeUtil.getRequiredChildOfType(ref, HaxeIdentifier.class); return id; } @Override public boolean isInheritorDeep(PsiClass baseClass, PsiClass classToByPass) { HaxeClass resolved = getResolvedDelegate(); return null != resolved && resolved.isInheritorDeep(baseClass, classToByPass); } @Override public boolean isInheritor(@NotNull PsiClass baseClass, boolean checkDeep) { HaxeClass resolved = getResolvedDelegate(); return null != resolved && resolved.isInheritor(baseClass, checkDeep); } @Override @NotNull public PsiReferenceList getExtendsList() { // Haxe BNF doesn't allow for extends in this position. return new HaxeExtendsDeclarationImpl(new HaxeDummyASTNode("Empty Extends List", getProject())); } @Override public PsiReferenceList getImplementsList() { // Haxe BNF doesn't allow for implements in this position. return new HaxeImplementsDeclarationImpl(new HaxeDummyASTNode("Empty Implements List", getProject())); } @Override @NotNull public PsiClassType[] getExtendsListTypes() { return PsiClassType.EMPTY_ARRAY; } @Override @NotNull public PsiClassType[] getImplementsListTypes() { return PsiClassType.EMPTY_ARRAY; } @Override public PsiClass getSuperClass() { HaxeClass resolved = getResolvedDelegate(); return null == resolved ? null : resolved.getSuperClass(); } @Override public PsiClass[] getInterfaces() { HaxeClass resolved = getResolvedDelegate(); return null == resolved ? PsiClass.EMPTY_ARRAY : resolved.getInterfaces(); } @Override @NotNull public PsiClass[] getSupers() { HaxeClass resolved = getResolvedDelegate(); return null == resolved ? PsiClass.EMPTY_ARRAY : resolved.getSupers(); } @Override @NotNull public PsiClassType[] getSuperTypes() { HaxeClass resolved = getResolvedDelegate(); return null == resolved ? PsiClassType.EMPTY_ARRAY : resolved.getSuperTypes(); } @Override @NotNull public Collection<HierarchicalMethodSignature> getVisibleSignatures() { HaxeClass resolved = getResolvedDelegate(); return PsiSuperMethodImplUtil.getVisibleSignatures(resolved); } } }
/* * Buffer.java * * Copyright (c) 2013 Mike Strobel * * This source code is based on Mono.Cecil from Jb Evain, Copyright (c) Jb Evain; * and ILSpy/ICSharpCode from SharpDevelop, Copyright (c) AlphaSierraPapa. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. * A copy of the license can be found in the License.html file at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. */ package com.strobel.assembler.metadata; import com.strobel.core.VerifyArgument; import com.strobel.util.EmptyArrayCache; import java.nio.BufferUnderflowException; import java.util.Arrays; /** * @author Mike Strobel */ public class Buffer { private final static int DEFAULT_SIZE = 64; private byte[] _data; private int _length; private int _position; public Buffer() { _data = new byte[DEFAULT_SIZE]; _length = DEFAULT_SIZE; } public Buffer(final byte[] data) { _data = VerifyArgument.notNull(data, "data"); _length = data.length; } public Buffer(final int initialSize) { _data = new byte[initialSize]; _length = initialSize; } public int size() { return _length; } public void flip() { _length = _position; _position = 0; } public int position() { return _position; } public void position(final int position) { if (position > _length) { throw new BufferUnderflowException(); } _position = position; } public void advance(final int length) { if (_position + length > _length) { _position = _length; throw new BufferUnderflowException(); } _position += length; } public void reset() { reset(DEFAULT_SIZE); } public void reset(final int initialSize) { if (VerifyArgument.isNonNegative(initialSize, "initialSize") == 0) { _data = EmptyArrayCache.EMPTY_BYTE_ARRAY; } else if (initialSize > _data.length || initialSize < _data.length / 4) { _data = new byte[initialSize]; } _length = initialSize; _position = 0; } public byte[] array() { return _data; } public int read(final byte[] buffer, final int offset, final int length) { if (buffer == null) { throw new NullPointerException(); } if (offset < 0 || length < 0 || length > buffer.length - offset) { throw new IndexOutOfBoundsException(); } if (_position >= _length) { return -1; } final int available = _length - _position; final int actualLength = Math.min(length, available); if (actualLength <= 0) { return 0; } System.arraycopy(_data, _position, buffer, offset, actualLength); _position += actualLength; return actualLength; } public String readUtf8() { final int utfLength = readUnsignedShort(); final byte[] byteBuffer = new byte[utfLength]; final char[] charBuffer = new char[utfLength]; int ch, ch2, ch3; int count = 0; int charactersRead = 0; read(byteBuffer, 0, utfLength); while (count < utfLength) { ch = (int) byteBuffer[count] & 0xFF; if (ch > 127) { break; } count++; charBuffer[charactersRead++] = (char) ch; } while (count < utfLength) { ch = (int) byteBuffer[count] & 0xff; switch (ch & 0xE0) { case 0x00: case 0x10: case 0x20: case 0x30: case 0x40: case 0x50: case 0x60: case 0x70: /* 0xxxxxxx*/ count++; charBuffer[charactersRead++] = (char) ch; break; case 0xC0: /* 110x xxxx 10xx xxxx*/ count += 2; if (count > utfLength) { throw new IllegalStateException("malformed input: partial character at end"); } ch2 = (int) byteBuffer[count - 1]; if ((ch2 & 0xC0) != 0x80) { throw new IllegalStateException("malformed input around byte " + count); } charBuffer[charactersRead++] = (char) ((ch & 0x1F) << 6 | ch2 & 0x3F); break; case 0xE0: /* 1110 xxxx 10xx xxxx 10xx xxxx */ count += 3; if (count > utfLength) { throw new IllegalStateException("malformed input: partial character at end"); } ch2 = (int) byteBuffer[count - 2]; ch3 = (int) byteBuffer[count - 1]; if ((ch2 & 0xC0) != 0x80 || (ch3 & 0xC0) != 0x80) { throw new IllegalStateException("malformed input around byte " + (count - 1)); } charBuffer[charactersRead++] = (char) ((ch & 0x0F) << 12 | (ch2 & 0x3F) << 6 | (ch3 & 0x3F) << 0); break; default: /* 10xx xxxx, 1111 xxxx */ throw new IllegalStateException("malformed input around byte " + count); } } // The number of chars produced may be less than utfLength return new String(charBuffer, 0, charactersRead); } public byte readByte() { verifyReadableBytes(1); return _data[_position++]; } public int readUnsignedByte() { verifyReadableBytes(1); return _data[_position++] & 0xFF; } public short readShort() { verifyReadableBytes(2); return (short) ((readUnsignedByte() << 8) + (readUnsignedByte() << 0)); } public int readUnsignedShort() { verifyReadableBytes(2); return ((readUnsignedByte() << 8) + (readUnsignedByte() << 0)); } public int readInt() { verifyReadableBytes(4); return (readUnsignedByte() << 24) + (readUnsignedByte() << 16) + (readUnsignedByte() << 8) + (readUnsignedByte() << 0); } public long readLong() { verifyReadableBytes(8); return ((long)readUnsignedByte() << 56) + ((long)readUnsignedByte() << 48) + ((long)readUnsignedByte() << 40) + ((long)readUnsignedByte() << 32) + ((long)readUnsignedByte() << 24) + ((long)readUnsignedByte() << 16) + ((long)readUnsignedByte() << 8) + ((long)readUnsignedByte() << 0); } public float readFloat() { return Float.intBitsToFloat(readInt()); } public double readDouble() { return Double.longBitsToDouble(readLong()); } public Buffer writeByte(final int b) { ensureWriteableBytes(1); _data[_position++] = (byte) (b & 0xFF); return this; } public Buffer writeShort(final int s) { ensureWriteableBytes(2); _data[_position++] = (byte) ((s >>> 8) & 0xFF); _data[_position++] = (byte) (s & 0xFF); return this; } public Buffer writeInt(final int i) { ensureWriteableBytes(4); _data[_position++] = (byte) ((i >>> 24) & 0xFF); _data[_position++] = (byte) ((i >>> 16) & 0xFF); _data[_position++] = (byte) ((i >>> 8) & 0xFF); _data[_position++] = (byte) (i & 0xFF); return this; } public Buffer writeLong(final long l) { ensureWriteableBytes(8); int i = (int) (l >>> 32); _data[_position++] = (byte) ((i >>> 24) & 0xFF); _data[_position++] = (byte) ((i >>> 16) & 0xFF); _data[_position++] = (byte) ((i >>> 8) & 0xFF); _data[_position++] = (byte) (i & 0xFF); i = (int) l; _data[_position++] = (byte) ((i >>> 24) & 0xFF); _data[_position++] = (byte) ((i >>> 16) & 0xFF); _data[_position++] = (byte) ((i >>> 8) & 0xFF); _data[_position++] = (byte) (i & 0xFF); return this; } public Buffer writeFloat(final float f) { return writeInt(Float.floatToRawIntBits(f)); } public Buffer writeDouble(final double d) { return writeLong(Double.doubleToRawLongBits(d)); } @SuppressWarnings("ConstantConditions") public Buffer writeUtf8(final String s) { final int charLength = s.length(); ensureWriteableBytes(2 + charLength); // optimistic algorithm: instead of computing the byte length and then // serializing the string (which requires two loops), we assume the byte // length is equal to char length (which is the most frequent case), and // we start serializing the string right away. During the serialization, // if we find that this assumption is wrong, we continue with the // general method. _data[_position++] = (byte) (charLength >>> 8); _data[_position++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { char c = s.charAt(i); if (c >= '\001' && c <= '\177') { _data[_position++] = (byte) c; } else { int byteLength = i; for (int j = i; j < charLength; ++j) { c = s.charAt(j); if (c >= '\001' && c <= '\177') { byteLength++; } else if (c > '\u07FF') { byteLength += 3; } else { byteLength += 2; } } _data[_position] = (byte) (byteLength >>> 8); _data[_position + 1] = (byte) byteLength; ensureWriteableBytes(2 + byteLength); for (int j = i; j < charLength; ++j) { c = s.charAt(j); if (c >= '\001' && c <= '\177') { _data[_position++] = (byte) c; } else if (c > '\u07FF') { _data[_position++] = (byte) (0xE0 | c >> 12 & 0xF); _data[_position++] = (byte) (0x80 | c >> 6 & 0x3F); _data[_position++] = (byte) (0x80 | c & 0x3F); } else { _data[_position++] = (byte) (0xC0 | c >> 6 & 0x1F); _data[_position++] = (byte) (0x80 | c & 0x3F); } } break; } } return this; } public Buffer putByteArray(final byte[] b, final int offset, final int length) { ensureWriteableBytes(length); if (b != null) { System.arraycopy(b, offset, _data, _position, length); } _position += length; return this; } protected void verifyReadableBytes(final int size) { if (VerifyArgument.isNonNegative(size, "size") > 0 && _position + size > _length) { throw new BufferUnderflowException(); } } protected void ensureWriteableBytes(final int size) { final int minLength = _position + size; if (minLength > _data.length) { final int length1 = 2 * _data.length; final int length2 = _position + size; _data = Arrays.copyOf(_data, Math.max(length1, length2)); } _length = Math.max(minLength, _length); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.spoon.delegates; import java.util.ArrayList; import java.util.List; import org.apache.commons.vfs2.FileObject; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.LocationListener; import org.eclipse.swt.browser.OpenWindowListener; import org.eclipse.swt.browser.WindowEvent; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.widgets.Composite; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.Const; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.gui.SpoonInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.repository.ObjectRevision; import org.pentaho.di.repository.RepositoryOperation; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.repository.RepositorySecurityUI; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.spoon.SpoonBrowser; import org.pentaho.di.ui.spoon.TabItemInterface; import org.pentaho.di.ui.spoon.TabMapEntry; import org.pentaho.di.ui.spoon.TabMapEntry.ObjectType; import org.pentaho.di.ui.spoon.job.JobGraph; import org.pentaho.di.ui.spoon.trans.TransGraph; import org.pentaho.ui.util.Launch; import org.pentaho.ui.util.Launch.Status; import org.pentaho.xul.swt.tab.TabItem; import org.pentaho.xul.swt.tab.TabSet; public class SpoonTabsDelegate extends SpoonDelegate { private static Class<?> PKG = Spoon.class; // for i18n purposes, needed by Translator2!! /** * This contains a list of the tab map entries */ private List<TabMapEntry> tabMap; public SpoonTabsDelegate( Spoon spoon ) { super( spoon ); tabMap = new ArrayList<TabMapEntry>(); } public boolean tabClose( TabItem item ) throws KettleException { // Try to find the tab-item that's being closed. List<TabMapEntry> collection = new ArrayList<TabMapEntry>(); collection.addAll( tabMap ); boolean createPerms = !RepositorySecurityUI .verifyOperations( Spoon.getInstance().getShell(), Spoon.getInstance().getRepository(), false, RepositoryOperation.MODIFY_TRANSFORMATION, RepositoryOperation.MODIFY_JOB ); boolean close = true; for ( TabMapEntry entry : collection ) { if ( item.equals( entry.getTabItem() ) ) { TabItemInterface itemInterface = entry.getObject(); // Can we close this tab? Only allow users with create content perms to save if ( !itemInterface.canBeClosed() && createPerms ) { int reply = itemInterface.showChangedWarning(); if ( reply == SWT.YES ) { close = itemInterface.applyChanges(); } else { if ( reply == SWT.CANCEL ) { close = false; } else { close = true; } } } // Also clean up the log/history associated with this // transformation/job // if ( close ) { if ( entry.getObject() instanceof TransGraph ) { TransMeta transMeta = (TransMeta) entry.getObject().getManagedObject(); spoon.delegates.trans.closeTransformation( transMeta ); spoon.refreshTree(); // spoon.refreshCoreObjects(); } else if ( entry.getObject() instanceof JobGraph ) { JobMeta jobMeta = (JobMeta) entry.getObject().getManagedObject(); spoon.delegates.jobs.closeJob( jobMeta ); spoon.refreshTree(); // spoon.refreshCoreObjects(); } else if ( entry.getObject() instanceof SpoonBrowser ) { spoon.closeSpoonBrowser(); spoon.refreshTree(); } else if ( entry.getObject() instanceof Composite ) { Composite comp = (Composite) entry.getObject(); if ( comp != null && !comp.isDisposed() ) { comp.dispose(); } } } break; } } return close; } public void removeTab( TabMapEntry tabMapEntry ) { for ( TabMapEntry entry : getTabs() ) { if ( tabMapEntry.equals( entry ) ) { tabMap.remove( tabMapEntry ); } } if ( !tabMapEntry.getTabItem().isDisposed() ) { tabMapEntry.getTabItem().dispose(); } } public List<TabMapEntry> getTabs() { List<TabMapEntry> list = new ArrayList<TabMapEntry>(); list.addAll( tabMap ); return list; } public TabMapEntry getTab( TabItem tabItem ) { for ( TabMapEntry tabMapEntry : tabMap ) { if ( tabMapEntry.getTabItem().equals( tabItem ) ) { return tabMapEntry; } } return null; } public EngineMetaInterface getActiveMeta() { TabSet tabfolder = spoon.tabfolder; if ( tabfolder == null ) { return null; } TabItem tabItem = tabfolder.getSelected(); if ( tabItem == null ) { return null; } // What transformation is in the active tab? // TransLog, TransGraph & TransHist contain the same transformation // TabMapEntry mapEntry = getTab( tabfolder.getSelected() ); EngineMetaInterface meta = null; if ( mapEntry != null ) { if ( mapEntry.getObject() instanceof TransGraph ) { meta = ( mapEntry.getObject() ).getMeta(); } if ( mapEntry.getObject() instanceof JobGraph ) { meta = ( mapEntry.getObject() ).getMeta(); } } return meta; } public String makeSlaveTabName( SlaveServer slaveServer ) { return "Slave server: " + slaveServer.getName(); } public boolean addSpoonBrowser( String name, String urlString ) { return addSpoonBrowser( name, urlString, true, null ); } public boolean addSpoonBrowser( String name, String urlString, LocationListener listener ) { boolean ok = addSpoonBrowser( name, urlString, true, listener ); return ok; } public boolean addSpoonBrowser( String name, String urlString, boolean isURL, LocationListener listener ) { TabSet tabfolder = spoon.tabfolder; try { // OK, now we have the HTML, create a new browset tab. // See if there already is a tab for this browser // If no, add it // If yes, select that tab // TabMapEntry tabMapEntry = findTabMapEntry( name, ObjectType.BROWSER ); if ( tabMapEntry == null ) { CTabFolder cTabFolder = tabfolder.getSwtTabset(); final SpoonBrowser browser = new SpoonBrowser( cTabFolder, spoon, urlString, isURL, true, listener ); browser.getBrowser().addOpenWindowListener( new OpenWindowListener() { @Override public void open( WindowEvent event ) { if ( event.required ) { event.browser = browser.getBrowser(); } } } ); TabItem tabItem = new TabItem( tabfolder, name, name ); tabItem.setImage( GUIResource.getInstance().getImageLogoSmall() ); tabItem.setControl( browser.getComposite() ); tabMapEntry = new TabMapEntry( tabItem, isURL ? urlString : null, name, null, null, browser, ObjectType.BROWSER ); tabMap.add( tabMapEntry ); } int idx = tabfolder.indexOf( tabMapEntry.getTabItem() ); // keep the focus on the graph tabfolder.setSelected( idx ); return true; } catch ( Throwable e ) { boolean ok = false; if ( isURL ) { // Retry to show the welcome page in an external browser. // Status status = Launch.openURL( urlString ); ok = status.equals( Status.Success ); } if ( !ok ) { // Log an error // log.logError( "Unable to open browser tab", e ); return false; } else { return true; } } } public TabMapEntry findTabMapEntry( String tabItemText, ObjectType objectType ) { for ( TabMapEntry entry : tabMap ) { if ( entry.getTabItem().isDisposed() ) { continue; } if ( objectType == entry.getObjectType() && entry.getTabItem().getText().equalsIgnoreCase( tabItemText ) ) { return entry; } } return null; } public TabMapEntry findTabMapEntry( Object managedObject ) { for ( TabMapEntry entry : tabMap ) { if ( entry.getTabItem().isDisposed() ) { continue; } Object entryManagedObj = entry.getObject().getManagedObject(); // make sure they are the same class before comparing them if ( entryManagedObj != null && managedObject != null ) { if ( entryManagedObj.getClass().equals( managedObject.getClass() ) ) { if ( entryManagedObj.equals( managedObject ) ) { return entry; } } } } return null; } /** * Finds the tab for the transformation that matches the metadata provided (either the file must be the same or the * repository id). * * @param trans * Transformation metadata to look for * @return Tab with transformation open whose metadata matches {@code trans} or {@code null} if no tab exists. * @throws KettleFileException * If there is a problem loading the file object for an open transformation with an invalid a filename. */ public TabMapEntry findTabForTransformation( TransMeta trans ) throws KettleFileException { // File for the transformation we're looking for. It will be loaded upon first request. FileObject transFile = null; for ( TabMapEntry entry : tabMap ) { if ( entry == null || entry.getTabItem().isDisposed() ) { continue; } if ( trans.getFilename() != null && entry.getFilename() != null ) { // If the entry has a file name it is the same as trans iff. they originated from the same files FileObject entryFile = KettleVFS.getFileObject( entry.getFilename() ); if ( transFile == null ) { transFile = KettleVFS.getFileObject( trans.getFilename() ); } if ( entryFile.equals( transFile ) ) { return entry; } } else if ( trans.getObjectId() != null && entry.getObject() != null ) { EngineMetaInterface meta = entry.getObject().getMeta(); if ( meta != null && trans.getObjectId().equals( meta.getObjectId() ) ) { // If the transformation has an object id and the entry shares the same id they are the same return entry; } } } // No tabs for the transformation exist and are not disposed return null; } /** * Rename the tabs */ public void renameTabs() { List<TabMapEntry> list = new ArrayList<TabMapEntry>( tabMap ); for ( TabMapEntry entry : list ) { if ( entry.getTabItem().isDisposed() ) { // this should not be in the map, get rid of it. tabMap.remove( entry.getObjectName() ); continue; } // TabItem before = entry.getTabItem(); // PDI-1683: need to get the String here, otherwise using only the "before" instance below, the reference gets // changed and result is always the same // String beforeText=before.getText(); // Object managedObject = entry.getObject().getManagedObject(); if ( managedObject != null ) { if ( entry.getObject() instanceof TransGraph ) { TransMeta transMeta = (TransMeta) managedObject; String tabText = makeTabName( transMeta, entry.isShowingLocation() ); entry.getTabItem().setText( tabText ); String toolTipText = BaseMessages.getString( PKG, "Spoon.TabTrans.Tooltip", tabText ); if ( Const.isWindows() && !Const.isEmpty( transMeta.getFilename() ) ) { toolTipText += Const.CR + Const.CR + transMeta.getFilename(); } entry.getTabItem().setToolTipText( toolTipText ); } else if ( entry.getObject() instanceof JobGraph ) { JobMeta jobMeta = (JobMeta) managedObject; entry.getTabItem().setText( makeTabName( jobMeta, entry.isShowingLocation() ) ); String toolTipText = BaseMessages.getString( PKG, "Spoon.TabJob.Tooltip", makeTabName( jobMeta, entry.isShowingLocation() ) ); if ( Const.isWindows() && !Const.isEmpty( jobMeta.getFilename() ) ) { toolTipText += Const.CR + Const.CR + jobMeta.getFilename(); } entry.getTabItem().setToolTipText( toolTipText ); } } /* * String after = entry.getTabItem().getText(); * * if (!beforeText.equals(after)) // PDI-1683, could be improved to rename all the time { * entry.setObjectName(after); * * // Also change the transformation map if (entry.getObject() instanceof TransGraph) { * spoon.delegates.trans.removeTransformation(beforeText); spoon.delegates.trans.addTransformation(after, * (TransMeta) entry.getObject().getManagedObject()); } // Also change the job map if (entry.getObject() * instanceof JobGraph) { spoon.delegates.jobs.removeJob(beforeText); spoon.delegates.jobs.addJob(after, (JobMeta) * entry.getObject().getManagedObject()); } } */ } spoon.setShellText(); } public void addTab( TabMapEntry entry ) { tabMap.add( entry ); } public String makeTabName( EngineMetaInterface transMeta, boolean showLocation ) { if ( Const.isEmpty( transMeta.getName() ) && Const.isEmpty( transMeta.getFilename() ) ) { return Spoon.STRING_TRANS_NO_NAME; } if ( Const.isEmpty( transMeta.getName() ) || spoon.delegates.trans.isDefaultTransformationName( transMeta.getName() ) ) { transMeta.nameFromFilename(); } String name = ""; if ( showLocation ) { if ( !Const.isEmpty( transMeta.getFilename() ) ) { // Regular file... // name += transMeta.getFilename() + " : "; } else { // Repository object... // name += transMeta.getRepositoryDirectory().getPath() + " : "; } } name += transMeta.getName(); if ( showLocation ) { ObjectRevision version = transMeta.getObjectRevision(); if ( version != null ) { name += " : r" + version.getName(); } } return name; } public void tabSelected( TabItem item ) { ArrayList<TabMapEntry> collection = new ArrayList<TabMapEntry>( tabMap ); // See which core objects to show // for ( TabMapEntry entry : collection ) { boolean isTrans = ( entry.getObject() instanceof TransGraph ); if ( item.equals( entry.getTabItem() ) ) { if ( isTrans || entry.getObject() instanceof JobGraph ) { EngineMetaInterface meta = entry.getObject().getMeta(); if ( meta != null ) { meta.setInternalKettleVariables(); } if ( spoon.getCoreObjectsState() != SpoonInterface.STATE_CORE_OBJECTS_SPOON ) { spoon.refreshCoreObjects(); } } if ( entry.getObject() instanceof JobGraph ) { ( (JobGraph) entry.getObject() ).setFocus(); } else if ( entry.getObject() instanceof TransGraph ) { ( (TransGraph) entry.getObject() ).setFocus(); } break; } } // Also refresh the tree spoon.refreshTree(); spoon.setShellText(); // calls also enableMenus() and markTabsChanged() } /* * private void setEnabled(String id,boolean enable) { spoon.getToolbar().getButtonById(id).setEnable(enable); } */ }
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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.jasig.portal.url; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import javax.portlet.PortletMode; import javax.portlet.WindowState; import javax.servlet.http.HttpServletRequest; import javax.xml.xpath.XPathExpression; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.jasig.portal.IUserPreferencesManager; import org.jasig.portal.layout.IUserLayout; import org.jasig.portal.layout.IUserLayoutManager; import org.jasig.portal.portlet.PortletUtils; import org.jasig.portal.portlet.om.IPortletEntity; import org.jasig.portal.portlet.om.IPortletWindow; import org.jasig.portal.portlet.om.IPortletWindowId; import org.jasig.portal.portlet.registry.IPortletWindowRegistry; import org.jasig.portal.portlet.rendering.IPortletRenderer; import org.jasig.portal.user.IUserInstance; import org.jasig.portal.user.IUserInstanceManager; import org.jasig.portal.utils.Tuple; import org.jasig.portal.utils.web.PortalWebUtils; import org.jasig.portal.xml.xpath.XPathOperations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.util.UrlPathHelper; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * {@link IPortalUrlProvider} and {@link IUrlSyntaxProvider} implementation * that uses a consistent human readable URL format. * * @author Eric Dalquist * @version $Revision$ */ @Component("portalUrlProvider") public class UrlSyntaxProviderImpl implements IUrlSyntaxProvider { static final String SEPARATOR = "_"; static final String PORTAL_PARAM_PREFIX = "u" + SEPARATOR; static final String PORTLET_CONTROL_PREFIX = "pC"; static final String PORTLET_PARAM_PREFIX = "pP" + SEPARATOR; static final String PORTLET_PUBLIC_RENDER_PARAM_PREFIX = "pG" + SEPARATOR; static final String PARAM_TARGET_PORTLET = PORTLET_CONTROL_PREFIX + "t"; static final String PARAM_ADDITIONAL_PORTLET = PORTLET_CONTROL_PREFIX + "a"; static final String PARAM_DELEGATE_PARENT = PORTLET_CONTROL_PREFIX + "d"; static final String PARAM_RESOURCE_ID = PORTLET_CONTROL_PREFIX + "r"; static final String PARAM_CACHEABILITY = PORTLET_CONTROL_PREFIX + "c"; static final String PARAM_WINDOW_STATE = PORTLET_CONTROL_PREFIX + "s"; static final String PARAM_PORTLET_MODE = PORTLET_CONTROL_PREFIX + "m"; static final String PARAM_COPY_PARAMETERS = PORTLET_CONTROL_PREFIX + "p"; static final Set<String> LEGACY_URL_PATHS = ImmutableSet.of( "/render.userLayoutRootNode.uP", "/tag.idempotent.render.userLayoutRootNode.uP"); static final String LEGACY_PARAM_PORTLET_FNAME = "uP_fname"; static final String LEGACY_PARAM_PORTLET_REQUEST_TYPE = "pltc_type"; static final String LEGACY_PARAM_PORTLET_STATE = "pltc_state"; static final String LEGACY_PARAM_PORTLET_MODE = "pltc_mode"; static final String LEGACY_PARAM_PORTLET_PARAM_PREFX = "pltp_"; static final String LEGACY_PARAM_LAYOUT_ROOT = "root"; static final String LEGACY_PARAM_LAYOUT_ROOT_VALUE = "uP_root"; static final String LEGACY_PARAM_LAYOUT_STRUCT_PARAM = "uP_sparam"; static final String LEGACY_PARAM_LAYOUT_TAB_ID = "activeTab"; static final String SLASH = "/"; static final String PORTLET_PATH_PREFIX = "p"; static final String FOLDER_PATH_PREFIX = "f"; static final String REQUEST_TYPE_SUFFIX = ".uP"; private static final Pattern SLASH_PATTERN = Pattern.compile(SLASH); private static final String PORTAL_CANONICAL_URL = UrlSyntaxProviderImpl.class.getName() + ".PORTAL_CANONICAL_URL"; private static final String PORTAL_REQUEST_INFO_ATTR = UrlSyntaxProviderImpl.class.getName() + ".PORTAL_REQUEST_INFO"; private static final String PORTAL_REQUEST_PARSING_IN_PROGRESS_ATTR = UrlSyntaxProviderImpl.class.getName() + ".PORTAL_REQUEST_PARSING_IN_PROGRESS"; /** * Utility enum used for parsing parameters that can appear multiple times on one URL and may or may not * be suffixed with the portlet's window id */ private enum SuffixedPortletParameter { RESOURCE_ID(UrlSyntaxProviderImpl.PARAM_RESOURCE_ID, UrlType.RESOURCE) { @Override public void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings) { portletRequestInfo.setResourceId(values.get(0)); } }, CACHEABILITY(UrlSyntaxProviderImpl.PARAM_CACHEABILITY, UrlType.RESOURCE){ @Override public void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings) { portletRequestInfo.setCacheability(values.get(0)); } }, DELEGATE_PARENT(UrlSyntaxProviderImpl.PARAM_DELEGATE_PARENT, UrlType.RENDER, UrlType.ACTION, UrlType.RESOURCE){ @Override public void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings) { try { final IPortletWindowId delegateParentWindowId = portletWindowRegistry.getPortletWindowId(request, values.get(0)); portletRequestInfo.setDelegateParentWindowId(delegateParentWindowId); final IPortletWindowId delegateWindowId = portletRequestInfo.getPortletWindowId(); delegateIdMappings.put(delegateParentWindowId, delegateWindowId); } catch (IllegalArgumentException e) { this.logger.warn("Failed to parse delegate portlet window ID '" + values.get(0) + "', the delegation window parameter will be ignored", e); } } }, WINDOW_STATE(UrlSyntaxProviderImpl.PARAM_WINDOW_STATE, UrlType.RENDER, UrlType.ACTION){ @Override public void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings) { portletRequestInfo.setWindowState(PortletUtils.getWindowState(values.get(0))); } }, PORTLET_MODE(UrlSyntaxProviderImpl.PARAM_PORTLET_MODE, UrlType.RENDER, UrlType.ACTION){ @Override public void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings) { portletRequestInfo.setPortletMode(PortletUtils.getPortletMode(values.get(0))); } }, COPY_PARAMETERS(UrlSyntaxProviderImpl.PARAM_COPY_PARAMETERS, UrlType.RENDER){ @Override public void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings) { final Map<String, List<String>> portletParameters = portletRequestInfo.getPortletParameters(); final IPortletWindowId portletRequestInfoWindowId = portletRequestInfo.getPortletWindowId(); final IPortletWindow portletWindow = portletWindowRegistry.getPortletWindow(request, portletRequestInfoWindowId); final Map<String, String[]> renderParameters = portletWindow.getRenderParameters(); ParameterMap.putAllList(portletParameters, renderParameters); } }; protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private final String parameterPrefix; private final Set<UrlType> validUrlTypes; private SuffixedPortletParameter(String parameterPrefix, UrlType validUrlType, UrlType... validUrlTypes) { this.parameterPrefix = parameterPrefix; this.validUrlTypes = Sets.immutableEnumSet(validUrlType, validUrlTypes); } /** * @return The {@link UrlType}s this parameter is valid on */ public Set<UrlType> getValidUrlTypes() { return this.validUrlTypes; } /** * @return The parameter prefix */ public String getParameterPrefix() { return this.parameterPrefix; } /** * Update the portlet request info based on the values for the parameter */ public abstract void updateRequestInfo(HttpServletRequest request, IPortletWindowRegistry portletWindowRegistry, PortletRequestInfoImpl portletRequestInfo, List<String> values, Map<IPortletWindowId, IPortletWindowId> delegateIdMappings); } /** * Enum used in getPortalRequestInfo to keep track of the parser state when reading the URL string. * IMPORTANT, if you add a new parse step the SWITCH block in getPortalRequestInfo MUST be updated */ private enum ParseStep { FOLDER, PORTLET, STATE, TYPE, COMPLETE; } protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * WindowStates that are communicated as part of the path */ private static final Set<WindowState> PATH_WINDOW_STATES = new LinkedHashSet<WindowState>(Arrays.asList(WindowState.MAXIMIZED, IPortletRenderer.DETACHED, IPortletRenderer.EXCLUSIVE)); private final UrlPathHelper urlPathHelper = new UrlPathHelper(); private Set<UrlState> statelessUrlStates = EnumSet.of(UrlState.DETACHED, UrlState.EXCLUSIVE); private String defaultEncoding = "UTF-8"; private IPortletWindowRegistry portletWindowRegistry; private IPortalRequestUtils portalRequestUtils; private IUrlNodeSyntaxHelperRegistry urlNodeSyntaxHelperRegistry; private IPortalUrlProvider portalUrlProvider; private IUserInstanceManager userInstanceManager; private XPathOperations xpathOperations; @Autowired public void setUserInstanceManager(IUserInstanceManager userInstanceManager) { this.userInstanceManager = userInstanceManager; } @Autowired public void setXpathOperations(XPathOperations xpathOperations) { this.xpathOperations = xpathOperations; } @Autowired public void setPortalUrlProvider(IPortalUrlProvider portalUrlProvider) { this.portalUrlProvider = portalUrlProvider; } /** * @param defaultEncoding the defaultEncoding to set */ public void setDefaultEncoding(String defaultEncoding) { this.defaultEncoding = defaultEncoding; } /** * @param portletWindowRegistry the portletWindowRegistry to set */ @Autowired public void setPortletWindowRegistry(IPortletWindowRegistry portletWindowRegistry) { this.portletWindowRegistry = portletWindowRegistry; } /** * @param portalRequestUtils the portalRequestUtils to set */ @Autowired public void setPortalRequestUtils(IPortalRequestUtils portalRequestUtils) { this.portalRequestUtils = portalRequestUtils; } @Autowired public void setUrlNodeSyntaxHelperRegistry(IUrlNodeSyntaxHelperRegistry urlNodeSyntaxHelperRegistry) { this.urlNodeSyntaxHelperRegistry = urlNodeSyntaxHelperRegistry; } /* (non-Javadoc) * @see org.jasig.portal.url.IPortalUrlProvider#getPortalRequestInfo(javax.servlet.http.HttpServletRequest) */ @Override public IPortalRequestInfo getPortalRequestInfo(HttpServletRequest request) { request = this.portalRequestUtils.getOriginalPortalRequest(request); final IPortalRequestInfo cachedPortalRequestInfo = (IPortalRequestInfo)request.getAttribute(PORTAL_REQUEST_INFO_ATTR); if (cachedPortalRequestInfo != null) { if(logger.isDebugEnabled()) { logger.debug("short-circuit: found portalRequestInfo within request attributes"); } return cachedPortalRequestInfo; } synchronized (PortalWebUtils.getRequestAttributeMutex(request)) { // set a flag to say this request is currently being parsed final Boolean inProgressAttr = (Boolean) request.getAttribute(PORTAL_REQUEST_PARSING_IN_PROGRESS_ATTR); if(inProgressAttr != null && inProgressAttr) { if(logger.isDebugEnabled()) { logger.warn("Portal request info parsing already in progress, returning null"); } return null; } request.setAttribute(PORTAL_REQUEST_PARSING_IN_PROGRESS_ATTR, Boolean.TRUE); } try { //Clone the parameter map so data can be removed from it as it is parsed to help determine what to do with non-namespaced parameters @SuppressWarnings("unchecked") final Map<String, String[]> parameterMap = new ParameterMap(request.getParameterMap()); final String requestPath = this.urlPathHelper.getPathWithinApplication(request); if (LEGACY_URL_PATHS.contains(requestPath)) { return parseLegacyPortalUrl(request, parameterMap); } final IUrlNodeSyntaxHelper urlNodeSyntaxHelper = this.urlNodeSyntaxHelperRegistry.getCurrentUrlNodeSyntaxHelper(request); final PortalRequestInfoImpl portalRequestInfo = new PortalRequestInfoImpl(); IPortletWindowId targetedPortletWindowId = null; PortletRequestInfoImpl targetedPortletRequestInfo = null; final String[] requestPathParts = SLASH_PATTERN.split(requestPath); UrlState requestedUrlState = null; ParseStep parseStep = ParseStep.FOLDER; for (int pathPartIndex = 0; pathPartIndex < requestPathParts.length; pathPartIndex++) { String pathPart = requestPathParts[pathPartIndex]; if (StringUtils.isEmpty(pathPart)) { continue; } switch (parseStep) { case FOLDER: { parseStep = ParseStep.PORTLET; if (FOLDER_PATH_PREFIX.equals(pathPart)) { //Skip adding the prefix to the folders deque pathPartIndex++; final LinkedList<String> folders = new LinkedList<String>(); for (;pathPartIndex < requestPathParts.length; pathPartIndex++) { pathPart = requestPathParts[pathPartIndex]; //Found the portlet part of the path, step back one and finish folder parsing if (PORTLET_PATH_PREFIX.equals(pathPart)) { pathPartIndex--; break; } //Found the end of the path, step back one, check for state and finish folder parsing else if (pathPart.endsWith(REQUEST_TYPE_SUFFIX)) { pathPartIndex--; pathPart = requestPathParts[pathPartIndex]; //If a state was added to the folder list remove it and step back one so other code can handle it if (UrlState.valueOfIngoreCase(pathPart, null) != null) { folders.removeLast(); pathPartIndex--; } break; } folders.add(pathPart); } if (folders.size() > 0) { final String targetedLayoutNodeId = urlNodeSyntaxHelper.getLayoutNodeForFolderNames(request, folders); portalRequestInfo.setTargetedLayoutNodeId(targetedLayoutNodeId); } break; } } case PORTLET: { parseStep = ParseStep.STATE; final String targetedLayoutNodeId = portalRequestInfo.getTargetedLayoutNodeId(); if (PORTLET_PATH_PREFIX.equals(pathPart)) { if (++pathPartIndex < requestPathParts.length) { pathPart = requestPathParts[pathPartIndex]; targetedPortletWindowId = urlNodeSyntaxHelper.getPortletForFolderName(request, targetedLayoutNodeId, pathPart); } break; } //See if a portlet was targeted by parameter final String[] targetedPortletIds = parameterMap.remove(PARAM_TARGET_PORTLET); if (targetedPortletIds != null && targetedPortletIds.length > 0) { final String targetedPortletString = targetedPortletIds[0]; targetedPortletWindowId = urlNodeSyntaxHelper.getPortletForFolderName(request, targetedLayoutNodeId, targetedPortletString); } } case STATE: { parseStep = ParseStep.TYPE; //States other than the default only make sense if a portlet is being targeted if (targetedPortletWindowId == null) { break; } requestedUrlState = UrlState.valueOfIngoreCase(pathPart, null); //Set the URL state if (requestedUrlState != null) { portalRequestInfo.setUrlState(requestedUrlState); //If the request is stateless if (statelessUrlStates.contains(requestedUrlState)) { final IPortletWindow statelessPortletWindow = this.portletWindowRegistry.getOrCreateStatelessPortletWindow(request, targetedPortletWindowId); targetedPortletWindowId = statelessPortletWindow.getPortletWindowId(); } //Create the portlet request info targetedPortletRequestInfo = portalRequestInfo.getPortletRequestInfo(targetedPortletWindowId); portalRequestInfo.setTargetedPortletWindowId(targetedPortletWindowId); //Set window state based on URL State first then look for the window state parameter switch (requestedUrlState) { case MAX: { targetedPortletRequestInfo.setWindowState(WindowState.MAXIMIZED); } break; case DETACHED: { targetedPortletRequestInfo.setWindowState(IPortletRenderer.DETACHED); } break; case EXCLUSIVE: { targetedPortletRequestInfo.setWindowState(IPortletRenderer.EXCLUSIVE); } break; } break; } } case TYPE: { parseStep = ParseStep.COMPLETE; if (pathPartIndex == requestPathParts.length - 1 && pathPart.endsWith(REQUEST_TYPE_SUFFIX) && pathPart.length() > REQUEST_TYPE_SUFFIX.length()) { final String urlTypePart = pathPart.substring(0, pathPart.length() - REQUEST_TYPE_SUFFIX.length()); final UrlType urlType; //Handle inline resourceIds, look for a . in the request type string and use the suffix as the urlType final int lastPeriod = urlTypePart.lastIndexOf('.'); if (lastPeriod >= 0 && lastPeriod < urlTypePart.length()) { final String urlTypePartSuffix = urlTypePart.substring(lastPeriod + 1); urlType = UrlType.valueOfIngoreCase(urlTypePartSuffix, null); if (urlType == UrlType.RESOURCE && targetedPortletRequestInfo != null) { final String resourceId = urlTypePart.substring(0, lastPeriod); targetedPortletRequestInfo.setResourceId(resourceId); } } else { urlType = UrlType.valueOfIngoreCase(urlTypePart, null); } if (urlType != null) { portalRequestInfo.setUrlType(urlType); break; } } } } } //If a targeted portlet window ID is found but no targeted portlet request info has been retrieved yet, set it up if (targetedPortletWindowId != null && targetedPortletRequestInfo == null) { targetedPortletRequestInfo = portalRequestInfo.getPortletRequestInfo(targetedPortletWindowId); portalRequestInfo.setTargetedPortletWindowId(targetedPortletWindowId); } //Get the set of portlet window ids that also have parameters on the url final String[] additionalPortletIdArray = parameterMap.remove(PARAM_ADDITIONAL_PORTLET); final Set<String> additionalPortletIds = Sets.newHashSet(additionalPortletIdArray != null ? additionalPortletIdArray : new String[0]); //Used if there is delegation to capture form-submit and other non-prefixed parameters //Map of parent id to delegate id final Map<IPortletWindowId, IPortletWindowId> delegateIdMappings = new LinkedHashMap<IPortletWindowId, IPortletWindowId>(0); //Parse all remaining parameters from the request final Set<Entry<String, String[]>> parameterEntrySet = parameterMap.entrySet(); for (final Iterator<Entry<String, String[]>> parameterEntryItr = parameterEntrySet.iterator(); parameterEntryItr.hasNext(); ) { final Entry<String, String[]> parameterEntry = parameterEntryItr.next(); final String name = parameterEntry.getKey(); final List<String> values = Arrays.asList(parameterEntry.getValue()); /* NOTE: continues are being used to allow fall-through behavior like a switch statement would provide */ //Portal Parameters, just need to remove the prefix if (name.startsWith(PORTAL_PARAM_PREFIX)) { final Map<String, List<String>> portalParameters = portalRequestInfo.getPortalParameters(); portalParameters.put(this.safeSubstringAfter(PORTAL_PARAM_PREFIX, name), values); parameterEntryItr.remove(); continue; } //Generic portlet parameters, have to remove the prefix and see if there was a portlet windowId between the prefix and parameter name if (name.startsWith(PORTLET_PARAM_PREFIX)) { final Tuple<String, IPortletWindowId> portletParameterParts = this.parsePortletParameterName(request, name, additionalPortletIds); final IPortletWindowId portletWindowId = portletParameterParts.second; final String paramName = portletParameterParts.first; //Get the portlet parameter map to add the parameter to final Map<String, List<String>> portletParameters; if (portletWindowId == null) { if (targetedPortletRequestInfo == null) { this.logger.warn("Parameter " + name + " is for the targeted portlet but no portlet is targeted by the request. The parameter will be ignored. Value: " + values); parameterEntryItr.remove(); break; } portletParameters = targetedPortletRequestInfo.getPortletParameters(); } else { final PortletRequestInfoImpl portletRequestInfoImpl = portalRequestInfo.getPortletRequestInfo(portletWindowId); portletParameters = portletRequestInfoImpl.getPortletParameters(); } portletParameters.put(paramName, values); parameterEntryItr.remove(); continue; } //Portlet control parameters are either used directly or as a prefix to a windowId. Use the SuffixedPortletParameter to simplify their parsing for (final SuffixedPortletParameter suffixedPortletParameter : SuffixedPortletParameter.values()) { final String parameterPrefix = suffixedPortletParameter.getParameterPrefix(); //Skip to the next parameter prefix if the current doesn't match if (!name.startsWith(parameterPrefix)) { continue; } //All of these parameters require at least one value if (values.isEmpty()) { this.logger.warn("Ignoring parameter " + name + " as it must have a value. Value: " + values); break; } //Verify the parameter is being used on the correct type of URL final Set<UrlType> validUrlTypes = suffixedPortletParameter.getValidUrlTypes(); if (!validUrlTypes.contains(portalRequestInfo.getUrlType())) { this.logger.warn("Ignoring parameter " + name + " as it is only valid for " + validUrlTypes + " requests and this is a " + portalRequestInfo.getUrlType() + " request. Value: " + values); break; } //Determine the portlet window and request info the parameter targets final IPortletWindowId portletWindowId = this.parsePortletWindowIdSuffix(request, parameterPrefix, additionalPortletIds, name); final PortletRequestInfoImpl portletRequestInfo = getTargetedPortletRequestInfo(portalRequestInfo, targetedPortletRequestInfo, portletWindowId); if (portletRequestInfo == null) { this.logger.warn("Parameter " + name + " is for the targeted portlet but no portlet is targeted by the request. The parameter will be ignored. Value: " + values); break; } parameterEntryItr.remove(); //Use the enum helper to store the parameter values on the request info suffixedPortletParameter.updateRequestInfo(request, portletWindowRegistry, portletRequestInfo, values, delegateIdMappings); break; } } //Any non-namespaced parameters still need processing? if (!parameterMap.isEmpty()) { //If the parameter was not ignored by a previous parser add it to whatever was targeted (portlet or portal) final Map<String, List<String>> parameters; if (!delegateIdMappings.isEmpty()) { //Resolve the last portlet window in the chain of delegation PortletRequestInfoImpl delegatePortletRequestInfo = null; for (final IPortletWindowId delegatePortletWindowId : delegateIdMappings.values()) { if (!delegateIdMappings.containsKey(delegatePortletWindowId)) { delegatePortletRequestInfo = portalRequestInfo.getPortletRequestInfo(delegatePortletWindowId); break; } } if (delegatePortletRequestInfo != null) { parameters = delegatePortletRequestInfo.getPortletParameters(); } else { this.logger.warn("No root delegate portlet could be resolved, non-namespaced parameters will be sent to the targeted portlet. THIS SHOULD NEVER HAPPEN. Delegate parent/child mapping: " + delegateIdMappings); if (targetedPortletRequestInfo != null) { parameters = targetedPortletRequestInfo.getPortletParameters(); } else { parameters = portalRequestInfo.getPortalParameters(); } } } else if (targetedPortletRequestInfo != null) { parameters = targetedPortletRequestInfo.getPortletParameters(); } else { parameters = portalRequestInfo.getPortalParameters(); } ParameterMap.putAllList(parameters, parameterMap); } //If a portlet is targeted but no layout node is targeted must be maximized if (targetedPortletRequestInfo != null && portalRequestInfo.getTargetedLayoutNodeId() == null && (requestedUrlState == null || requestedUrlState == UrlState.NORMAL)) { portalRequestInfo.setUrlState(UrlState.MAX); targetedPortletRequestInfo.setWindowState(WindowState.MAXIMIZED); } //Make the request info object read-only, once parsed the request info should be static portalRequestInfo.makeReadOnly(); request.setAttribute(PORTAL_REQUEST_INFO_ATTR, portalRequestInfo); if(logger.isDebugEnabled()) { logger.debug("finished building requestInfo: " + portalRequestInfo); } return portalRequestInfo; } finally { request.removeAttribute(PORTAL_REQUEST_PARSING_IN_PROGRESS_ATTR); } } protected IPortalRequestInfo parseLegacyPortalUrl(HttpServletRequest request, Map<String, String[]> parameterMap) { final PortalRequestInfoImpl portalRequestInfo = new PortalRequestInfoImpl(); final String[] fname = parameterMap.remove(LEGACY_PARAM_PORTLET_FNAME); if (fname != null && fname.length > 0) { final IPortletWindow portletWindow = this.portletWindowRegistry.getOrCreateDefaultPortletWindowByFname(request, fname[0]); if (portletWindow != null) { logger.debug("Legacy fname parameter {} resolved to {}", fname[0], portletWindow); final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId(); portalRequestInfo.setTargetedPortletWindowId(portletWindowId); final PortletRequestInfoImpl portletRequestInfo = portalRequestInfo.getPortletRequestInfo(portletWindowId); //Check the portlet request type final String[] type = parameterMap.remove(LEGACY_PARAM_PORTLET_REQUEST_TYPE); if (type != null && type.length > 0 && "ACTION".equals(type[0])) { portalRequestInfo.setUrlType(UrlType.ACTION); } //Set the window state final String[] state = parameterMap.remove(LEGACY_PARAM_PORTLET_STATE); if (state != null && state.length > 0) { final WindowState windowState = PortletUtils.getWindowState(state[0]); //If this isn't an action request only allow PATH communicated WindowStates as none of the other options make sense if (portalRequestInfo.getUrlType() == UrlType.ACTION || PATH_WINDOW_STATES.contains(windowState)) { portletRequestInfo.setWindowState(windowState); } } //If no window state was set assume MAXIMIZED if (portletRequestInfo.getWindowState() == null) { portletRequestInfo.setWindowState(WindowState.MAXIMIZED); } //Set the portlet mode final String[] mode = parameterMap.remove(LEGACY_PARAM_PORTLET_MODE); if (mode != null && mode.length > 0) { final PortletMode portletMode = PortletUtils.getPortletMode(mode[0]); portletRequestInfo.setPortletMode(portletMode); } //Set the parameters final Map<String, List<String>> portletParameters = portletRequestInfo.getPortletParameters(); for (final Map.Entry<String, String[]> parameterEntry : parameterMap.entrySet()) { final String prefixedName = parameterEntry.getKey(); //If the parameter starts with the portlet param prefix if (prefixedName.startsWith(LEGACY_PARAM_PORTLET_PARAM_PREFX)) { final String name = prefixedName.substring(LEGACY_PARAM_PORTLET_PARAM_PREFX.length()); portletParameters.put(name, Arrays.asList(parameterEntry.getValue())); } } //Set the url state based on the window state final UrlState urlState = this.determineUrlState(portletWindow, portletRequestInfo.getWindowState()); portalRequestInfo.setUrlState(urlState); } else { logger.debug("Could not find portlet for legacy fname fname parameter {}", fname[0]); } } //Check root=uP_root final String[] root = parameterMap.remove(LEGACY_PARAM_LAYOUT_ROOT); if (root != null && root.length > 0) { if (LEGACY_PARAM_LAYOUT_ROOT_VALUE.equals(root[0])) { //Check uP_sparam=activeTab final String[] structParam = parameterMap.remove(LEGACY_PARAM_LAYOUT_STRUCT_PARAM); if (structParam != null && structParam.length > 0) { if (LEGACY_PARAM_LAYOUT_TAB_ID.equals(structParam[0])) { //Get the active tab id final String[] activeTabId = parameterMap.remove(LEGACY_PARAM_LAYOUT_TAB_ID); if (activeTabId != null && activeTabId.length > 0) { //Get the user's layout and do xpath for tab at index=activeTabId[0] final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request); final IUserPreferencesManager preferencesManager = userInstance.getPreferencesManager(); final IUserLayoutManager userLayoutManager = preferencesManager.getUserLayoutManager(); final IUserLayout userLayout = userLayoutManager.getUserLayout(); final String nodeId = this.xpathOperations.doWithExpression( "/layout/folder/folder[@type='regular' and @hidden='false'][position() = $activeTabId]/@ID", Collections.singletonMap("activeTabId", activeTabId[0]), new Function<XPathExpression, String>() { @Override public String apply(XPathExpression xPathExpression) { return userLayout.findNodeId(xPathExpression); } }); //Found nodeId for activeTabId if (nodeId != null) { logger.debug("Found layout node {} for legacy activeTabId parameter {}", nodeId, activeTabId[0]); portalRequestInfo.setTargetedLayoutNodeId(nodeId); } else { logger.debug("No layoout node found for legacy activeTabId parameter {}", activeTabId[0]); } } } } } } return portalRequestInfo; } /** * If the targetedPortletWindowId is not null {@link #getPortletRequestInfo(IPortalRequestInfo, Map, IPortletWindowId)} is called and that * value is returned. If targetedPortletWindowId is null targetedPortletRequestInfo is returned. */ protected PortletRequestInfoImpl getTargetedPortletRequestInfo( final PortalRequestInfoImpl portalRequestInfo, final PortletRequestInfoImpl targetedPortletRequestInfo, final IPortletWindowId targetedPortletWindowId) { if (targetedPortletWindowId == null) { return targetedPortletRequestInfo; } return portalRequestInfo.getPortletRequestInfo(targetedPortletWindowId); } /** * Parse the parameter name and the optional portlet window id from a fully qualified query parameter. */ protected Tuple<String, IPortletWindowId> parsePortletParameterName(HttpServletRequest request, String name, Set<String> additionalPortletIds) { //Look for a 2nd separator which might indicate a portlet window id for (final String additionalPortletId : additionalPortletIds) { final int windowIdIdx = name.indexOf(additionalPortletId); if (windowIdIdx == -1) { continue; } final String paramName = name.substring(PORTLET_PARAM_PREFIX.length() + additionalPortletId.length() + SEPARATOR.length()); final IPortletWindowId portletWindowId = this.portletWindowRegistry.getPortletWindowId(request, additionalPortletId); return new Tuple<String, IPortletWindowId>(paramName, portletWindowId); } final String paramName = this.safeSubstringAfter(PORTLET_PARAM_PREFIX, name); return new Tuple<String, IPortletWindowId>(paramName, null); } /** * Determines if the parameter name contains a {@link IPortletWindowId} after the prefix. The id must also be contained in the Set * of additionalPortletIds. If no id is found in the parameter name null is returned. */ protected IPortletWindowId parsePortletWindowIdSuffix(HttpServletRequest request, final String prefix, final Set<String> additionalPortletIds, final String name) { //See if the parameter name has an additional separator final int windowIdStartIdx = name.indexOf(SEPARATOR, prefix.length()); if (windowIdStartIdx < (prefix.length() + SEPARATOR.length()) - 1) { return null; } //Extract the windowId string and see if it was listed as an additional windowId final String portletWindowIdStr = name.substring(windowIdStartIdx + SEPARATOR.length()); if (additionalPortletIds.contains(portletWindowIdStr)) { try { return this.portletWindowRegistry.getPortletWindowId(request, portletWindowIdStr); } catch (IllegalArgumentException e) { this.logger.warn("Failed to parse portlet window id: " + portletWindowIdStr + " null will be returned", e); } } return null; } protected String safeSubstringAfter(String prefix, String fullName) { if (prefix.length() >= fullName.length()) { return ""; } return fullName.substring(prefix.length()); } @Override public String getCanonicalUrl(HttpServletRequest request) { request = this.portalRequestUtils.getOriginalPortalRequest(request); final String cachedCanonicalUrl = (String)request.getAttribute(PORTAL_CANONICAL_URL); if (cachedCanonicalUrl != null) { if(logger.isDebugEnabled()) { logger.debug("short-circuit: found canonicalUrl within request attributes"); } return cachedCanonicalUrl; } final IPortalRequestInfo portalRequestInfo = this.getPortalRequestInfo(request); final UrlType urlType = portalRequestInfo.getUrlType(); final IPortletWindowId targetedPortletWindowId = portalRequestInfo.getTargetedPortletWindowId(); final String targetedLayoutNodeId = portalRequestInfo.getTargetedLayoutNodeId(); //Create a portal url builder with the appropriate target final IPortalUrlBuilder portalUrlBuilder; if (targetedPortletWindowId != null) { portalUrlBuilder = this.portalUrlProvider.getPortalUrlBuilderByPortletWindow(request, targetedPortletWindowId, urlType); } else if (targetedLayoutNodeId != null) { portalUrlBuilder = this.portalUrlProvider.getPortalUrlBuilderByLayoutNode(request, targetedLayoutNodeId, urlType); } else { portalUrlBuilder = this.portalUrlProvider.getDefaultUrl(request); } //Copy over portal parameters final Map<String, List<String>> portalParameters = portalRequestInfo.getPortalParameters(); portalUrlBuilder.setParameters(portalParameters); //Copy data for each portlet for (final IPortletRequestInfo portletRequestInfo : portalRequestInfo.getPortletRequestInfoMap().values()) { final IPortletWindowId portletWindowId = portletRequestInfo.getPortletWindowId(); final IPortletUrlBuilder portletUrlBuilder = portalUrlBuilder.getPortletUrlBuilder(portletWindowId); //Parameters final Map<String, List<String>> portletParameters = portletRequestInfo.getPortletParameters(); portletUrlBuilder.setParameters(portletParameters); switch (urlType) { case RESOURCE: { //cacheability and resourceId for resource requests portletUrlBuilder.setCacheability(portletRequestInfo.getCacheability()); portletUrlBuilder.setResourceId(portletRequestInfo.getResourceId()); } case RENDER: case ACTION: { //state & mode for all requests portletUrlBuilder.setWindowState(portletRequestInfo.getWindowState()); portletUrlBuilder.setPortletMode(portletRequestInfo.getPortletMode()); break; } } } return portalUrlBuilder.getUrlString(); } @Override public String generateUrl(HttpServletRequest request, IPortalActionUrlBuilder portalActionUrlBuilder) { final String redirectLocation = portalActionUrlBuilder.getRedirectLocation(); //If no redirect location just generate the portal url if (redirectLocation == null) { return this.generateUrl(request, (IPortalUrlBuilder)portalActionUrlBuilder); } final String renderUrlParamName = portalActionUrlBuilder.getRenderUrlParamName(); //If no render param name just return the redirect url if (renderUrlParamName == null) { return redirectLocation; } //Need to stick the generated portal url onto the redirect url final StringBuilder redirectLocationBuilder = new StringBuilder(redirectLocation); final int queryParamStartIndex = redirectLocationBuilder.indexOf("?"); //Already has parameters, add the new one correctly if (queryParamStartIndex > -1) { redirectLocationBuilder.append('&'); } //No parameters, add parm seperator else { redirectLocationBuilder.append('?'); } //Generate the portal url final String portalRenderUrl = this.generateUrl(request, (IPortalUrlBuilder)portalActionUrlBuilder); //Encode the render param name and the render url final String encoding = this.getEncoding(request); final String encodedRenderUrlParamName; final String encodedPortalRenderUrl; try { encodedRenderUrlParamName = URLEncoder.encode(renderUrlParamName, encoding); encodedPortalRenderUrl = URLEncoder.encode(portalRenderUrl, encoding); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Encoding '" + encoding + "' is not supported.", e); } return redirectLocationBuilder.append(encodedRenderUrlParamName).append("=").append(encodedPortalRenderUrl).toString(); } @Override public String generateUrl(HttpServletRequest request, IPortalUrlBuilder portalUrlBuilder) { Validate.notNull(request, "HttpServletRequest was null"); Validate.notNull(portalUrlBuilder, "IPortalPortletUrl was null"); //Convert the callback request to the portal request request = this.portalRequestUtils.getOriginalPortalRequest(request); final IUrlNodeSyntaxHelper urlNodeSyntaxHelper = this.urlNodeSyntaxHelperRegistry.getCurrentUrlNodeSyntaxHelper(request); //Get the encoding and create a new URL string builder final String encoding = this.getEncoding(request); final UrlStringBuilder url = new UrlStringBuilder(encoding); //Add the portal's context path final String contextPath = this.getCleanedContextPath(request); if (contextPath.length() > 0) { url.setPath(contextPath); } final Map<IPortletWindowId, IPortletUrlBuilder> portletUrlBuilders = portalUrlBuilder.getPortletUrlBuilders(); //Build folder path based on targeted portlet or targeted folder final IPortletWindowId targetedPortletWindowId = portalUrlBuilder.getTargetPortletWindowId(); final UrlType urlType = portalUrlBuilder.getUrlType(); final UrlState urlState; final String resourceId; if (targetedPortletWindowId != null) { final IPortletWindow portletWindow = this.portletWindowRegistry.getPortletWindow(request, targetedPortletWindowId); final IPortletEntity portletEntity = portletWindow.getPortletEntity(); //Add folder information if available: /f/tabId final String channelSubscribeId = portletEntity.getLayoutNodeId(); final List<String> folderNames = urlNodeSyntaxHelper.getFolderNamesForLayoutNode(request, channelSubscribeId); if (!folderNames.isEmpty()) { url.addPath(FOLDER_PATH_PREFIX); for (final String folderName : folderNames) { url.addPath(folderName); } } final IPortletUrlBuilder targetedPortletUrlBuilder = portletUrlBuilders.get(targetedPortletWindowId); //Determine the resourceId for resource requests if (urlType == UrlType.RESOURCE && targetedPortletUrlBuilder != null) { resourceId = targetedPortletUrlBuilder.getResourceId(); } else { resourceId = null; } //Resource requests will never have a requested window state urlState = this.determineUrlState(portletWindow, targetedPortletUrlBuilder); final String targetedPortletString = urlNodeSyntaxHelper.getFolderNameForPortlet(request, targetedPortletWindowId); //If a non-normal render url or an action/resource url stick the portlet info in the path if ((urlType == UrlType.RENDER && urlState != UrlState.NORMAL) || urlType == UrlType.ACTION || urlType == UrlType.RESOURCE) { url.addPath(PORTLET_PATH_PREFIX); url.addPath(targetedPortletString); } //For normal render requests (generally multiple portlets on a page) add the targeted portlet as a parameter else { url.addParameter(PARAM_TARGET_PORTLET, targetedPortletString); } } else { final String targetFolderId = portalUrlBuilder.getTargetFolderId(); final List<String> folderNames = urlNodeSyntaxHelper.getFolderNamesForLayoutNode(request, targetFolderId); if (folderNames != null && !folderNames.isEmpty()) { url.addPath(FOLDER_PATH_PREFIX); for (final String folderName : folderNames) { url.addPath(folderName); } } urlState = UrlState.NORMAL; resourceId = null; } //Add the state of the URL url.addPath(urlState.toLowercaseString()); //File part specifying the type of URL, resource URLs include the resourceId if (urlType == UrlType.RESOURCE && resourceId != null) { url.addPath(resourceId + "." + urlType.toLowercaseString() + REQUEST_TYPE_SUFFIX); } else { url.addPath(urlType.toLowercaseString() + REQUEST_TYPE_SUFFIX); } //Add all portal parameters final Map<String, String[]> portalParameters = portalUrlBuilder.getParameters(); url.addParametersArray(PORTAL_PARAM_PREFIX, portalParameters); //Is this URL stateless final boolean statelessUrl = statelessUrlStates.contains(urlState); //Add parameters for every portlet URL for (final IPortletUrlBuilder portletUrlBuilder : portletUrlBuilders.values()) { this.addPortletUrlData(request, url, urlType, portletUrlBuilder, targetedPortletWindowId, statelessUrl); } if (logger.isDebugEnabled()) { logger.debug("Generated '" + url + "' from '" + portalUrlBuilder); } return url.toString(); } /** * Add the provided portlet url builder data to the url string builder */ protected void addPortletUrlData( final HttpServletRequest request, final UrlStringBuilder url, final UrlType urlType, final IPortletUrlBuilder portletUrlBuilder, final IPortletWindowId targetedPortletWindowId, final boolean statelessUrl) { final IPortletWindowId portletWindowId = portletUrlBuilder.getPortletWindowId(); final boolean targeted = portletWindowId.equals(targetedPortletWindowId); IPortletWindow portletWindow = null; //The targeted portlet doesn't need namespaced parameters final String prefixedPortletWindowId; final String suffixedPortletWindowId; if (targeted) { prefixedPortletWindowId = ""; suffixedPortletWindowId = ""; } else { final String portletWindowIdStr = portletWindowId.toString(); prefixedPortletWindowId = SEPARATOR + portletWindowIdStr; suffixedPortletWindowId = portletWindowIdStr + SEPARATOR; url.addParameter(PARAM_ADDITIONAL_PORTLET, portletWindowIdStr); //targeted portlets can never be delegates (it is always the top most parent that is targeted) portletWindow = this.portletWindowRegistry.getPortletWindow(request, portletWindowId); final IPortletWindowId delegationParentId = portletWindow.getDelegationParentId(); if (delegationParentId != null) { url.addParameter(PARAM_DELEGATE_PARENT + prefixedPortletWindowId, delegationParentId.getStringId()); } } switch (urlType) { case RESOURCE: { final String cacheability = portletUrlBuilder.getCacheability(); if(cacheability != null) { url.addParameter(PARAM_CACHEABILITY + prefixedPortletWindowId, cacheability); } break; } default: { //Add requested portlet mode final PortletMode portletMode = portletUrlBuilder.getPortletMode(); if (portletMode != null) { url.addParameter(PARAM_PORTLET_MODE + prefixedPortletWindowId, portletMode.toString()); } else if (targeted && statelessUrl) { portletWindow = portletWindow != null ? portletWindow : this.portletWindowRegistry.getPortletWindow(request, portletWindowId); final PortletMode currentPortletMode = portletWindow.getPortletMode(); url.addParameter(PARAM_PORTLET_MODE + prefixedPortletWindowId, currentPortletMode.toString()); } //Add requested window state if it isn't included on the path final WindowState windowState = portletUrlBuilder.getWindowState(); if (windowState != null && (!targeted || !PATH_WINDOW_STATES.contains(windowState))) { url.addParameter(PARAM_WINDOW_STATE + prefixedPortletWindowId, windowState.toString()); } break; } } if (portletUrlBuilder.getCopyCurrentRenderParameters()) { url.addParameter(PARAM_COPY_PARAMETERS + suffixedPortletWindowId); } final Map<String, String[]> parameters = portletUrlBuilder.getParameters(); if (!parameters.isEmpty()) { url.addParametersArray(PORTLET_PARAM_PREFIX + suffixedPortletWindowId, parameters); } } /** * Determine the {@link UrlState} to use for the targeted portlet window */ protected UrlState determineUrlState(final IPortletWindow portletWindow, final IPortletUrlBuilder targetedPortletUrlBuilder) { final WindowState requestedWindowState; if (targetedPortletUrlBuilder == null) { requestedWindowState = null; } else { requestedWindowState = targetedPortletUrlBuilder.getWindowState(); } return determineUrlState(portletWindow, requestedWindowState); } /** * Determine the {@link UrlState} to use for the targeted portlet window */ protected UrlState determineUrlState(final IPortletWindow portletWindow, final WindowState requestedWindowState) { //Determine the UrlState based on the WindowState of the targeted portlet final WindowState currentWindowState = portletWindow.getWindowState(); final WindowState urlWindowState = requestedWindowState != null ? requestedWindowState : currentWindowState; if (WindowState.MAXIMIZED.equals(urlWindowState)) { return UrlState.MAX; } if (IPortletRenderer.DETACHED.equals(urlWindowState)) { return UrlState.DETACHED; } if (IPortletRenderer.EXCLUSIVE.equals(urlWindowState)) { return UrlState.EXCLUSIVE; } if (!WindowState.NORMAL.equals(urlWindowState) && !WindowState.MINIMIZED.equals(urlWindowState)) { this.logger.warn("Unknown WindowState '" + urlWindowState + "' specified for portlet window " + portletWindow + ", defaulting to UrlState.NORMAL"); } return UrlState.NORMAL; } /** * Tries to determine the encoded from the request, if not available falls back to configured default. * * @param request The current request. * @return The encoding to use. */ protected String getEncoding(HttpServletRequest request) { final String encoding = request.getCharacterEncoding(); if (encoding != null) { return encoding; } return this.defaultEncoding; } protected String getCleanedContextPath(HttpServletRequest request) { String contextPath = request.getContextPath(); if (contextPath.length() == 0) { return ""; } //Make sure the context path doesn't start with a / if (contextPath.charAt(0) == '/') { contextPath = contextPath.substring(1); } //Make sure the URL ends with a / if (contextPath.charAt(contextPath.length() - 1) == '/') { contextPath = contextPath.substring(0, contextPath.length() - 1); } return contextPath; } }
/* * Copyright 2015 The UIMaster Project * * The UIMaster Project 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.shaolin.uimaster.page; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.shaolin.bmdp.json.JSONObject; import org.shaolin.bmdp.runtime.Registry; import org.shaolin.bmdp.runtime.Registry.RunningMode; import org.shaolin.bmdp.runtime.security.UserContext; import org.shaolin.bmdp.runtime.spi.IConstantService; import org.shaolin.bmdp.runtime.spi.IServerServiceManager; import org.shaolin.bmdp.utils.HttpSender; import org.shaolin.uimaster.page.flow.WebflowConstants; public final class WebConfig { private static final String UIMASTER = "/uimaster"; public static final String DEFAULT_LOGIN_PATH = "/login.do"; public static final String DEFAULT_ACTION_PATH = "/webflow.do"; public static final String DEFAULT_INDEX_PAGE = "/jsp/index.jsp"; public static final String DEFAULT_LOGIN_PAGE = "/jsp/login.jsp"; public static final String DEFAULT_ILOGIN_PAGE = "/jsp/ilogin.jsp"; public static final String DEFAULT_MAIN_PAGE = "/jsp/main.jsp"; public static final String DEFAULT_ERROR_PAGE = "/jsp/common/Failure.jsp"; public static final String DEFAULT_TIMEOUT_PAGE = "/jsp/common/sessionTimeout.jsp"; public static final String APP_ROOT_VAR = "$APPROOT"; public static final String APP_RESOURCE_PATH = "_appstore"; public static final String KEY_REQUEST_UIENTITY = "_UIEntity"; private static String servletContextPath = ""; public static final String WebContextRoot = UIMASTER; // make sure cleaning the js cache after restart server in every time. private static int jsversion = (int)(Math.random() * 1000); private static WebConfigSpringInstance instance; public WebConfig() { } public static void setSpringInstance(final WebConfigSpringInstance instance0) { instance = instance0; } public static boolean isProductMode() { return Registry.getAppRunningMode() == RunningMode.Production; } public static boolean isCustomizedMode() { return instance.isCustomizedMode(); } public static void updateJsVersion(int version) { WebConfig.jsversion = version; } public static int getJsVersion() { return WebConfig.jsversion; } public static String getHiddenValueMask() { return instance.getHiddenValueMask(); } public static Hashtable<?, ?> getInitialContext() { Map<String, String> items = Registry.getInstance().getNodeItems( "/System/jndi"); // TODO: doing values replacement. return new Hashtable(items); } public static String getUserLocale(HttpServletRequest request) { // read from session HttpSession session = request.getSession(); String locale = (String) session.getAttribute(WebflowConstants.USER_LOCALE_KEY); if (locale != null) { return locale; } // read from cookie Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0, n = cookies.length; i < n; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equals(WebflowConstants.USER_LOCALE_KEY)) { locale = cookie.getValue(); if (locale != null) { session.setAttribute(WebflowConstants.USER_LOCALE_KEY, locale); return locale; } } } } return null; } public static void setServletContextPath(String servletContextPath) { WebConfig.servletContextPath = servletContextPath; } public static String getRealPath(String relativePath) { return WebConfig.getResourcePath() + relativePath; } public static String getUploadFileRoot() { return instance.getUploadServer(); } public static String getWebRoot() { return UIMASTER; } public static String getWebContextRoot() { return getWebRoot(); } public static String getWebSocketServer() { return instance.getWebsocketServer(); } public static String getJsWebSocketServer() { return instance.getJsWebsocketServer(); } /** * Andriod or IOS app context root. * * @return */ public static String getAppContextRoot(HttpServletRequest request) { String path = request.getParameter(WebConfig.APP_RESOURCE_PATH); return path != null ? ("file://" + path + "/uimaster") : "file:///storage/sdcard/uimaster"; } public static String getResourceContextRoot() { return instance.getResourceServer(); } public static String getAppResourceContextRoot(HttpServletRequest request) { String path = request.getParameter(WebConfig.APP_RESOURCE_PATH); return path != null ? ("file://" + path + "/uimaster") : "file:///storage/sdcard/uimaster"; } public static String getAppImageContextRoot(HttpServletRequest request) { if (UserContext.isAppClient()) { return instance.getResourceServer(); } return getResourceContextRoot(); } public static String getResourcePath() { return instance.getResourcePath(); } public static String getTempResourcePath() { return instance.getResourcePath() + "/temp"; } public static void setResourcePath(String path) { if (instance.getResourcePath() == null || instance.getResourcePath().trim().length() == 0) { instance.setResourcePath(path); } } public static String getCssRootPath() { return instance.getCssRootPath(); } public static String getJsRootPath() { return instance.getJsRootPath(); } public static String getAjaxServiceURI() { if (UserContext.isAppClient()) { return instance.getAjaxServiceURL() + "?_appclient=" + UserContext.getAppClientType(); } return instance.getAjaxServiceURL(); } public static String getFrameWrap() { return instance.getFrameWrap(); } public static String getActionPath() { return instance.getActionPath(); } public static String getLoginPath() { return instance.getLoginPath(); } public static String getIndexPage() { return instance.getIndexPage(); } public static String getLoginPage() { return instance.getLoginPage(); } public static String getILoginPage() { return instance.getIloginPage(); } public static String getMainPage() { return instance.getMainPage(); } public static String getErrorPage() { return instance.getErrorPage(); } public static String getNoPermissionPage() { return instance.getNopermissionPage(); } public static String getTimeoutPage() { return instance.getTimeoutPage(); } public static String getTimeStamp() { return String.valueOf(WebConfig.getJsVersion()); } public static boolean hasAjaxErrorHandler() { return "true".equals(instance.getHasAjaxErrorHandler()); } public static boolean isHttps() { return instance.isHTTPs(); } public static boolean isJAAS() { return instance.isJAAS(); } public static String isSyncLoadingJs(String url) { if (UserContext.isAppClient()) { return ""; } String[] list = instance.getSyncLoadJs(); for (String js : list) { if (url.indexOf(js) != -1) { return ""; } } return "async"; } public static boolean isFormatHTML() { return instance.isFormatHTML(); } public static boolean enableHotDeploy() { return instance.isHotdeployeable(); } public static boolean skipBackButton(String pageName) { return instance.getSkipBackButtonPages().contains(pageName); } /** * Import one css. * @param entityName * @return */ public static String getImportCSS(String entityName) { String name = entityName.replace('.', '/');//firefox only support '/' return getResourceContextRoot() + "/css/" + name + ".css"; } public static String getImportMobCSS(String entityName) { String name = entityName.replace('.', '/');//firefox only support '/' File f = new File(WebConfig.getRealPath("/css/" + name + "_mob.css")); if (f.exists()) { return getResourceContextRoot() + "/css/" + name + "_mob.css"; } return getResourceContextRoot() + "/css/" + name + ".css"; } public static String getImportAppMobCSS(String entityName) { String name = entityName.replace('.', '/');//firefox only support '/' File f = new File(WebConfig.getRealPath("/css/" + name + "_mob.css")); if (f.exists()) { return "$APPROOT/css/" + name + "_mob.css"; } return "$APPROOT/css/" + name + ".css"; } /** * Import one js. * @param entityName * @return */ public static String getImportJS(String entityName) { String name = entityName.replace('.', '/');//firefox only support '/' return getResourceContextRoot() + "/js/" + name + ".js"; } public static String getImportAppJS(String entityName) { String name = entityName.replace('.', '/');//firefox only support '/' return "$APPROOT/js/" + name + ".js"; } public static String replaceAppCssWebContext(HttpServletRequest request, final String str) { if (str.indexOf(APP_ROOT_VAR) != -1) { return str.replace(APP_ROOT_VAR, WebConfig.getAppContextRoot(request)); } return str; } public static String replaceAppJsWebContext(HttpServletRequest request, final String str) { if (str.indexOf(APP_ROOT_VAR) != -1) { return str.replace(APP_ROOT_VAR, WebConfig.getAppContextRoot(request)); } return str; } public static String replaceCssWebContext(String str) { return str; } public static String replaceJsWebContext(String str) { return str; } public static String replaceWebContext(String str) { return str; } public static String[] getCommonCss() { return instance.getCommoncss(); } public static String[] getCommonJs() { return instance.getCommonjs(); } public static String[] getCommonMobCss() { return instance.getCommonMobcss(); } public static String[] getCommonMobJs() { return instance.getCommonMobjs(); } public static String[] getCommonMobAppCss() { return instance.getCommonMobAppcss(); } public static String[] getCommonMobAppJs() { return instance.getCommonMobAppjs(); } public static boolean skipCommonJs(String pageName) { return instance.getSkipCommonJsPages().contains(pageName); } public static boolean skipCommonCss(String pageName) { return instance.getSkipCommonCssPages().contains(pageName); } public static String[] getSingleCommonJS(final String entityName) { String pack = entityName.substring(0, entityName.lastIndexOf('.')).replace('.', '_'); String entityName0 = entityName.replace('.', '_'); Map<String, String[]> singleCommonJs = instance.getSingleCommonJs(); Set<String> keys = singleCommonJs.keySet(); List<String> results = new ArrayList<String>(); for (String key : keys) { if (key.startsWith("*")) { String keyA = key.substring(1, 2); if (keyA.endsWith(".*")) { keyA = keyA.substring(0, keyA.length() - 2); if (pack.indexOf(keyA) != -1) { String[] vs = singleCommonJs.get(key); for (String v: vs) { results.add(v); } } } else { if (pack.lastIndexOf(keyA) != -1) { String[] vs = singleCommonJs.get(key); for (String v: vs) { results.add(v); } } } } else if (key.endsWith(".*")) { String keyPack = key.substring(0, key.length() - 2); if (pack.startsWith(keyPack)) { String[] vs = singleCommonJs.get(key); for (String v: vs) { results.add(v); } } } else if (key.equals(entityName0)) { String[] vs = singleCommonJs.get(entityName0); for (String v: vs) { results.add(v); } } } // keep the load sequence. for (String key : keys) { if (key.equals(pack)) { results.add(key); } } return results.toArray(new String[results.size()]); } public static String[] getSingleCommonAppJS(final String entityName) { String pack = entityName.substring(0, entityName.lastIndexOf('.')).replace('.', '_'); String entityName0 = entityName.replace('.', '_'); Map<String, String[]> singleCommonAppJs = instance.getSingleCommonAppJs(); Set<String> keys = singleCommonAppJs.keySet(); List<String> results = new ArrayList<String>(); for (String key : keys) { if (key.startsWith("*")) { String keyA = key.substring(1, 2); if (keyA.endsWith(".*")) { keyA = keyA.substring(0, keyA.length() - 2); if (pack.indexOf(keyA) != -1) { String[] vs = singleCommonAppJs.get(key); for (String v: vs) { results.add(v); } } } else { if (pack.lastIndexOf(keyA) != -1) { String[] vs = singleCommonAppJs.get(key); for (String v: vs) { results.add(v); } } } } else if (key.endsWith(".*")) { String keyPack = key.substring(0, key.length() - 2); if (pack.startsWith(keyPack)) { String[] vs = singleCommonAppJs.get(key); for (String v: vs) { results.add(v); } } } else if (key.equals(entityName0)) { String[] vs = singleCommonAppJs.get(entityName0); for (String v: vs) { results.add(v); } } } // keep the load sequence. for (String key : keys) { if (key.equals(pack)) { results.add(key); } } return results.toArray(new String[results.size()]); } public static String[] getSingleCommonCSS(String entityName) { String pack = entityName.substring(0, entityName.lastIndexOf('.')).replace('.', '_'); String entityName0 = entityName.replace('.', '_'); Map<String, String[]> singleCommonCss = instance.getSingleCommonCss(); Set<String> keys = singleCommonCss.keySet(); List<String> results = new ArrayList<String>(); for (String key : keys) { if (key.endsWith(".*")) { String keyPack = key.substring(0, key.length() - 2); if (pack.startsWith(keyPack)) { String[] vs = singleCommonCss.get(key); for (String v: vs) { results.add(v); } } } else if (key.equals(entityName0)) { String[] vs = singleCommonCss.get(entityName0); for (String v: vs) { results.add(v); } } } // keep the load sequence. for (String key : keys) { if (key.equals(pack)) { results.add(key); } } return results.toArray(new String[results.size()]); } public static String[] getSingleCommonAppCSS(String entityName) { String pack = entityName.substring(0, entityName.lastIndexOf('.')).replace('.', '_'); String entityName0 = entityName.replace('.', '_'); Map<String, String[]> singleCommonAppCss = instance.getSingleCommonAppCss(); Set<String> keys = singleCommonAppCss.keySet(); List<String> results = new ArrayList<String>(); for (String key : keys) { if (key.endsWith(".*")) { String keyPack = key.substring(0, key.length() - 2); if (pack.startsWith(keyPack)) { String[] vs = singleCommonAppCss.get(key); for (String v: vs) { results.add(v); } } } else if (key.equals(entityName0)) { String[] vs = singleCommonAppCss.get(entityName0); for (String v: vs) { results.add(v); } } } // keep the load sequence. for (String key : keys) { if (key.equals(pack)) { results.add(key); } } return results.toArray(new String[results.size()]); } /** * get css root path * * @param entityName * the ui entity name * * @return css root path * */ public static String getJspUrl(String entityName) { return getJspUrl(entityName, ""); } /** * suffix: UIENTITY_JSP_SUFFIX,ODMAPPER_JSP_SUFFIX,UIPAGE_HTML_JSP_SUFFIX */ public static String getJspUrl(String entityName, String componentType) { return ""; } public static String getSystemUISkin(String componentTypeName) { return null; } public static String getDefaultJspName(String entityName) { int index = entityName.indexOf(".uientity."); if (index != -1) { return entityName.substring(0, index) + ".uientityhtml." + entityName.substring(index + 10); } index = entityName.indexOf(".uipage."); if (index != -1) { return entityName.substring(0, index) + ".uipagehtml." + entityName.substring(index + 8); } index = entityName.indexOf(".od."); if (index != -1) { return entityName.substring(0, index) + ".odhtml." + entityName.substring(index + 4); } return entityName + "HTML"; } /** * Determine whether entity name and pattern is matched Currently use java * package like styles, support ** for all package Maybe we will use regular * expression pattern sometime later */ private static boolean matchPattern(String entityName, String pattern) { boolean matched = false; if (entityName.equals(pattern)) { matched = true; } else if (pattern.endsWith(".**")) { String packageName = pattern.substring(0, pattern.length() - 3); if (entityName.startsWith(packageName)) { matched = true; } } return matched; } private static String convertJSPath(String input) { int curIndex = input.indexOf('.'); if (curIndex == -1) { return input + ".js"; } int nextIndex = input.indexOf('.', curIndex + 1); if (nextIndex == -1) { return input; } StringBuffer sb = new StringBuffer(input.substring(0, curIndex)); do { sb.append('/'); sb.append(input.substring(curIndex + 1, nextIndex)); curIndex = nextIndex; nextIndex = input.indexOf('.', curIndex + 1); } while (nextIndex != -1); sb.append(input.substring(curIndex)); return new String(sb); } private static HttpSender sender = new HttpSender(); public static final String IP_Service = "http://ip.taobao.com/service/getIpInfo.php?ip="; /** * Only for web user! App user will use SDK api. * * @param request * @return */ public static double[] getUserLocation(String ipAddress) throws Exception{ StringBuffer sb = new StringBuffer(); sb.append(instance.getIpLocationURL()).append("?key="); sb.append(instance.getMapwebkey()); sb.append("&output=JSON").append("&ip=").append(ipAddress); JSONObject json1 = new JSONObject(sender.get(sb.toString())); if (json1.has("rectangle")) { String value = json1.getString("rectangle"); String[] items = value.split(";"); if (items.length ==2) { String[] righttop = items[0].split(","); String[] leftbottom = items[1].split(","); double longti = (Double.parseDouble(leftbottom[0]) - Double.parseDouble(righttop[0]))/2 + Double.parseDouble(righttop[0]); double lati = (Double.parseDouble(leftbottom[1]) - Double.parseDouble(righttop[1]))/2 + Double.parseDouble(righttop[1]); return new double[]{longti, lati}; } } return null; } /** * @param encoding * @return * @throws UnsupportedEncodingException */ public static String getUserCityInfo(String ipAddress) throws Exception { String jsonStr = sender.get(IP_Service + ipAddress); JSONObject json = new JSONObject(jsonStr); if (json.has("code") && json.getInt("code") == 0) { String regionId = json.getJSONObject("data").getString("region_id"); String cityId = json.getJSONObject("data").getString("city_id"); if (regionId != null && regionId.trim().length() > 0) { IConstantService cs = IServerServiceManager.INSTANCE.getConstantService(); String entityName = cs.getChildren("CityList", Integer.parseInt(regionId)).getEntityName(); return entityName +","+cityId; } } return null; } public static ThreadPoolExecutor getServletThreadPool(RejectedExecutionHandler handler) { Registry instance = Registry.getInstance(); int maxMsgsQueue = instance.getValue("/System/webConstant/AsyncServlet/maxMsgsQueue", 1000); int minThreadNum = instance.getValue("/System/webConstant/AsyncServlet/minThreadNum", Runtime.getRuntime().availableProcessors()); int maxThreadNum = instance.getValue("/System/webConstant/AsyncServlet/maxThreadNum", Runtime.getRuntime().availableProcessors()); return createThreadPool("ServletRequest", maxMsgsQueue, minThreadNum, maxThreadNum, handler); } public static ThreadPoolExecutor getAjaxThreadPool(RejectedExecutionHandler handler) { Registry instance = Registry.getInstance(); int maxMsgsQueue = instance.getValue("/System/webConstant/AsyncAjax/maxMsgsQueue", 5000); int minThreadNum = instance.getValue("/System/webConstant/AsyncAjax/minThreadNum", Runtime.getRuntime().availableProcessors()); int maxThreadNum = instance.getValue("/System/webConstant/AsyncAjax/maxThreadNum", Runtime.getRuntime().availableProcessors()); return createThreadPool("AjaxRequest", maxMsgsQueue, minThreadNum, maxThreadNum, handler); } public static ThreadPoolExecutor createThreadPool(String threadPoolName, int maxMsgsQueue, int minThreadNum, int maxThreadNum, RejectedExecutionHandler handler) { ThreadPoolExecutor workerPool_; if (maxMsgsQueue <= 0) { workerPool_ = new ThreadPoolExecutor(minThreadNum, maxThreadNum, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new DefaultThreadFactory(threadPoolName + "-worker")); } else { BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(maxMsgsQueue); workerPool_ = new ThreadPoolExecutor(minThreadNum, maxThreadNum, 0L, TimeUnit.MILLISECONDS, queue, new DefaultThreadFactory(threadPoolName + "-worker"), handler); } return workerPool_; } public static final class DefaultThreadFactory implements ThreadFactory { final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix; DefaultThreadFactory(String prefix) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = prefix + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } }
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package javacc; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; /** Position in buffer. */ public int bufpos = -1; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; protected int tabSize = 8; protected void setTabSize(int i) { tabSize = i; } protected int getTabSize(int i) { return tabSize; } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=fff5712c71425d35e64bfdebed26e292 (do not edit this line) */
/* * Copyright (c) 2020, The OpenThread Commissioner Authors. * 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 io.openthread.commissioner.service; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import io.openthread.commissioner.ByteArray; import io.openthread.commissioner.Commissioner; import io.openthread.commissioner.Error; import io.openthread.commissioner.ErrorCode; import java.util.concurrent.ExecutionException; public class SelectNetworkFragment extends Fragment implements InputNetworkPasswordDialogFragment.PasswordDialogListener, FetchCredentialDialogFragment.CredentialListener, View.OnClickListener { private static final String TAG = SelectNetworkFragment.class.getSimpleName(); private FragmentCallback networkInfoCallback; @Nullable private JoinerDeviceInfo joinerDeviceInfo; private NetworkAdapter networksAdapter; private ThreadNetworkInfoHolder selectedNetwork; private byte[] userInputPskc; private Button addDeviceButton; private BorderAgentDiscoverer borderAgentDiscoverer; public SelectNetworkFragment() {} public SelectNetworkFragment( @NonNull FragmentCallback networkInfoCallback, @Nullable JoinerDeviceInfo joinerDeviceInfo) { this.networkInfoCallback = networkInfoCallback; this.joinerDeviceInfo = joinerDeviceInfo; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "::onCreate"); networksAdapter = new NetworkAdapter(getContext()); borderAgentDiscoverer = new BorderAgentDiscoverer(getContext(), networksAdapter); borderAgentDiscoverer.start(); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "::onDestroy"); borderAgentDiscoverer.stop(); } @Override public void onResume() { super.onResume(); Log.d(TAG, "::onResume"); borderAgentDiscoverer.start(); } @Override public void onPause() { super.onPause(); Log.d(TAG, "::onPause"); borderAgentDiscoverer.stop(); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_select_network, container, false); } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Hide the button addDeviceButton = view.findViewById(R.id.add_device_button); addDeviceButton.setVisibility(View.GONE); if (joinerDeviceInfo != null) { String deviceInfoString = String.format( "eui64: %s\npskd: %s", CommissionerUtils.getHexString(joinerDeviceInfo.getEui64()), joinerDeviceInfo.getPskd()); TextView deviceInfoView = view.findViewById(R.id.device_info); deviceInfoView.setText(deviceInfoString); } else { view.findViewById(R.id.your_device).setVisibility(View.INVISIBLE); view.findViewById(R.id.device_info).setVisibility(View.INVISIBLE); } final ListView networkListView = view.findViewById(R.id.networks); networkListView.setAdapter(networksAdapter); networkListView.setOnItemClickListener( (AdapterView<?> adapterView, View v, int position, long id) -> { selectedNetwork = (ThreadNetworkInfoHolder) adapterView.getItemAtPosition(position); addDeviceButton.setVisibility(View.VISIBLE); }); view.findViewById(R.id.add_device_button).setOnClickListener(this); } // Click listeners for network password dialog. @Override public void onPositiveClick(InputNetworkPasswordDialogFragment fragment, String password) { BorderAgentInfo selectedBorderAgent = selectedNetwork.getBorderAgents().get(0); userInputPskc = computePskc(selectedNetwork.getNetworkInfo(), password); networkInfoCallback.onNetworkSelected(selectedNetwork, userInputPskc); } @Override public void onNegativeClick(InputNetworkPasswordDialogFragment fragment) { networkInfoCallback.onNetworkSelected(selectedNetwork, null); } private byte[] computePskc(ThreadNetworkInfo threadNetworkInfo, String password) { ByteArray extendedPanId = new ByteArray(threadNetworkInfo.getExtendedPanId()); ByteArray pskc = new ByteArray(); Error error = Commissioner.generatePSKc( pskc, password, threadNetworkInfo.getNetworkName(), extendedPanId); if (error.getCode() != ErrorCode.kNone) { Log.e( TAG, String.format( "failed to generate PSKc: %s; network-name=%s, extended-pan-id=%s", error.toString(), threadNetworkInfo.getNetworkName(), CommissionerUtils.getHexString(threadNetworkInfo.getExtendedPanId()))); } else { Log.d( TAG, String.format( "generated pskc=%s, network-name=%s, extended-pan-id=%s", CommissionerUtils.getHexString(pskc), threadNetworkInfo.getNetworkName(), CommissionerUtils.getHexString(threadNetworkInfo.getExtendedPanId()))); } return CommissionerUtils.getByteArray(pskc); } private void gotoFetchingCredential(BorderAgentInfo borderAgentInfo, byte[] pskc) { new FetchCredentialDialogFragment(borderAgentInfo, pskc, SelectNetworkFragment.this) .show(getParentFragmentManager(), FetchCredentialDialogFragment.class.getSimpleName()); } @Override public void onClick(View view) { try { BorderAgentInfo selectedBorderAgent = selectedNetwork.getBorderAgents().get(0); ThreadCommissionerServiceImpl commissionerService = new ThreadCommissionerServiceImpl(null); // TODO(wgtdkp): we could be blocked here. BorderAgentRecord borderAgentRecord = commissionerService.getBorderAgentRecord(selectedBorderAgent).get(); if (borderAgentRecord != null && borderAgentRecord.getPskc() != null) { networkInfoCallback.onNetworkSelected(selectedNetwork, borderAgentRecord.getPskc()); } else { // Ask the user to input Commissioner password. new InputNetworkPasswordDialogFragment(SelectNetworkFragment.this) .show( getParentFragmentManager(), InputNetworkPasswordDialogFragment.class.getSimpleName()); } } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void onCancelClick(FetchCredentialDialogFragment fragment) { // TODO: } @Override public void onConfirmClick( FetchCredentialDialogFragment fragment, ThreadNetworkCredential credential) { // TODO: } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.scheduler.v1beta1.stub; import static com.google.cloud.scheduler.v1beta1.CloudSchedulerClient.ListJobsPagedResponse; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.BetaApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.PagedListDescriptor; import com.google.api.gax.rpc.PagedListResponseFactory; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.scheduler.v1beta1.CreateJobRequest; import com.google.cloud.scheduler.v1beta1.DeleteJobRequest; import com.google.cloud.scheduler.v1beta1.GetJobRequest; import com.google.cloud.scheduler.v1beta1.Job; import com.google.cloud.scheduler.v1beta1.ListJobsRequest; import com.google.cloud.scheduler.v1beta1.ListJobsResponse; import com.google.cloud.scheduler.v1beta1.PauseJobRequest; import com.google.cloud.scheduler.v1beta1.ResumeJobRequest; import com.google.cloud.scheduler.v1beta1.RunJobRequest; import com.google.cloud.scheduler.v1beta1.UpdateJobRequest; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.protobuf.Empty; import java.io.IOException; import java.util.List; import javax.annotation.Generated; import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS /** * Settings class to configure an instance of {@link CloudSchedulerStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (cloudscheduler.googleapis.com) and default port (443) are * used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. For * example, to set the total timeout of getJob to 30 seconds: * * <pre> * <code> * CloudSchedulerStubSettings.Builder cloudSchedulerSettingsBuilder = * CloudSchedulerStubSettings.newBuilder(); * cloudSchedulerSettingsBuilder.getJobSettings().getRetrySettings().toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)); * CloudSchedulerStubSettings cloudSchedulerSettings = cloudSchedulerSettingsBuilder.build(); * </code> * </pre> */ @Generated("by gapic-generator") @BetaApi public class CloudSchedulerStubSettings extends StubSettings<CloudSchedulerStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build(); private final PagedCallSettings<ListJobsRequest, ListJobsResponse, ListJobsPagedResponse> listJobsSettings; private final UnaryCallSettings<GetJobRequest, Job> getJobSettings; private final UnaryCallSettings<CreateJobRequest, Job> createJobSettings; private final UnaryCallSettings<UpdateJobRequest, Job> updateJobSettings; private final UnaryCallSettings<DeleteJobRequest, Empty> deleteJobSettings; private final UnaryCallSettings<PauseJobRequest, Job> pauseJobSettings; private final UnaryCallSettings<ResumeJobRequest, Job> resumeJobSettings; private final UnaryCallSettings<RunJobRequest, Job> runJobSettings; /** Returns the object with the settings used for calls to listJobs. */ public PagedCallSettings<ListJobsRequest, ListJobsResponse, ListJobsPagedResponse> listJobsSettings() { return listJobsSettings; } /** Returns the object with the settings used for calls to getJob. */ public UnaryCallSettings<GetJobRequest, Job> getJobSettings() { return getJobSettings; } /** Returns the object with the settings used for calls to createJob. */ public UnaryCallSettings<CreateJobRequest, Job> createJobSettings() { return createJobSettings; } /** Returns the object with the settings used for calls to updateJob. */ public UnaryCallSettings<UpdateJobRequest, Job> updateJobSettings() { return updateJobSettings; } /** Returns the object with the settings used for calls to deleteJob. */ public UnaryCallSettings<DeleteJobRequest, Empty> deleteJobSettings() { return deleteJobSettings; } /** Returns the object with the settings used for calls to pauseJob. */ public UnaryCallSettings<PauseJobRequest, Job> pauseJobSettings() { return pauseJobSettings; } /** Returns the object with the settings used for calls to resumeJob. */ public UnaryCallSettings<ResumeJobRequest, Job> resumeJobSettings() { return resumeJobSettings; } /** Returns the object with the settings used for calls to runJob. */ public UnaryCallSettings<RunJobRequest, Job> runJobSettings() { return runJobSettings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public CloudSchedulerStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcCloudSchedulerStub.create(this); } else { throw new UnsupportedOperationException( "Transport not supported: " + getTransportChannelProvider().getTransportName()); } } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return "cloudscheduler.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(CloudSchedulerStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected CloudSchedulerStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); listJobsSettings = settingsBuilder.listJobsSettings().build(); getJobSettings = settingsBuilder.getJobSettings().build(); createJobSettings = settingsBuilder.createJobSettings().build(); updateJobSettings = settingsBuilder.updateJobSettings().build(); deleteJobSettings = settingsBuilder.deleteJobSettings().build(); pauseJobSettings = settingsBuilder.pauseJobSettings().build(); resumeJobSettings = settingsBuilder.resumeJobSettings().build(); runJobSettings = settingsBuilder.runJobSettings().build(); } private static final PagedListDescriptor<ListJobsRequest, ListJobsResponse, Job> LIST_JOBS_PAGE_STR_DESC = new PagedListDescriptor<ListJobsRequest, ListJobsResponse, Job>() { @Override public String emptyToken() { return ""; } @Override public ListJobsRequest injectToken(ListJobsRequest payload, String token) { return ListJobsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListJobsRequest injectPageSize(ListJobsRequest payload, int pageSize) { return ListJobsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListJobsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListJobsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Job> extractResources(ListJobsResponse payload) { return payload.getJobsList() != null ? payload.getJobsList() : ImmutableList.<Job>of(); } }; private static final PagedListResponseFactory< ListJobsRequest, ListJobsResponse, ListJobsPagedResponse> LIST_JOBS_PAGE_STR_FACT = new PagedListResponseFactory<ListJobsRequest, ListJobsResponse, ListJobsPagedResponse>() { @Override public ApiFuture<ListJobsPagedResponse> getFuturePagedResponse( UnaryCallable<ListJobsRequest, ListJobsResponse> callable, ListJobsRequest request, ApiCallContext context, ApiFuture<ListJobsResponse> futureResponse) { PageContext<ListJobsRequest, ListJobsResponse, Job> pageContext = PageContext.create(callable, LIST_JOBS_PAGE_STR_DESC, request, context); return ListJobsPagedResponse.createAsync(pageContext, futureResponse); } }; /** Builder for CloudSchedulerStubSettings. */ public static class Builder extends StubSettings.Builder<CloudSchedulerStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final PagedCallSettings.Builder< ListJobsRequest, ListJobsResponse, ListJobsPagedResponse> listJobsSettings; private final UnaryCallSettings.Builder<GetJobRequest, Job> getJobSettings; private final UnaryCallSettings.Builder<CreateJobRequest, Job> createJobSettings; private final UnaryCallSettings.Builder<UpdateJobRequest, Job> updateJobSettings; private final UnaryCallSettings.Builder<DeleteJobRequest, Empty> deleteJobSettings; private final UnaryCallSettings.Builder<PauseJobRequest, Job> pauseJobSettings; private final UnaryCallSettings.Builder<ResumeJobRequest, Job> resumeJobSettings; private final UnaryCallSettings.Builder<RunJobRequest, Job> runJobSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "idempotent", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE))); definitions.put("non_idempotent", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList())); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(60000L)) .setInitialRpcTimeout(Duration.ofMillis(20000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(20000L)) .setTotalTimeout(Duration.ofMillis(600000L)) .build(); definitions.put("default", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this((ClientContext) null); } protected Builder(ClientContext clientContext) { super(clientContext); listJobsSettings = PagedCallSettings.newBuilder(LIST_JOBS_PAGE_STR_FACT); getJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); pauseJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); resumeJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); runJobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( listJobsSettings, getJobSettings, createJobSettings, updateJobSettings, deleteJobSettings, pauseJobSettings, resumeJobSettings, runJobSettings); initDefaults(this); } private static Builder createDefault() { Builder builder = new Builder((ClientContext) null); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setEndpoint(getDefaultEndpoint()); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .listJobsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .getJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .createJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .updateJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .deleteJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .pauseJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .resumeJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .runJobSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); return builder; } protected Builder(CloudSchedulerStubSettings settings) { super(settings); listJobsSettings = settings.listJobsSettings.toBuilder(); getJobSettings = settings.getJobSettings.toBuilder(); createJobSettings = settings.createJobSettings.toBuilder(); updateJobSettings = settings.updateJobSettings.toBuilder(); deleteJobSettings = settings.deleteJobSettings.toBuilder(); pauseJobSettings = settings.pauseJobSettings.toBuilder(); resumeJobSettings = settings.resumeJobSettings.toBuilder(); runJobSettings = settings.runJobSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( listJobsSettings, getJobSettings, createJobSettings, updateJobSettings, deleteJobSettings, pauseJobSettings, resumeJobSettings, runJobSettings); } // NEXT_MAJOR_VER: remove 'throws Exception' /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to listJobs. */ public PagedCallSettings.Builder<ListJobsRequest, ListJobsResponse, ListJobsPagedResponse> listJobsSettings() { return listJobsSettings; } /** Returns the builder for the settings used for calls to getJob. */ public UnaryCallSettings.Builder<GetJobRequest, Job> getJobSettings() { return getJobSettings; } /** Returns the builder for the settings used for calls to createJob. */ public UnaryCallSettings.Builder<CreateJobRequest, Job> createJobSettings() { return createJobSettings; } /** Returns the builder for the settings used for calls to updateJob. */ public UnaryCallSettings.Builder<UpdateJobRequest, Job> updateJobSettings() { return updateJobSettings; } /** Returns the builder for the settings used for calls to deleteJob. */ public UnaryCallSettings.Builder<DeleteJobRequest, Empty> deleteJobSettings() { return deleteJobSettings; } /** Returns the builder for the settings used for calls to pauseJob. */ public UnaryCallSettings.Builder<PauseJobRequest, Job> pauseJobSettings() { return pauseJobSettings; } /** Returns the builder for the settings used for calls to resumeJob. */ public UnaryCallSettings.Builder<ResumeJobRequest, Job> resumeJobSettings() { return resumeJobSettings; } /** Returns the builder for the settings used for calls to runJob. */ public UnaryCallSettings.Builder<RunJobRequest, Job> runJobSettings() { return runJobSettings; } @Override public CloudSchedulerStubSettings build() throws IOException { return new CloudSchedulerStubSettings(this); } } }
/* * 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.aries.blueprint.namespace; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import static javax.xml.XMLConstants.XML_NS_URI; import static org.apache.aries.blueprint.parser.Parser.BLUEPRINT_NAMESPACE; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; import org.apache.aries.blueprint.container.NamespaceHandlerRegistry; import org.apache.aries.blueprint.parser.NamespaceHandlerSet; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.SAXException; /** * Default implementation of the NamespaceHandlerRegistry. * * This registry will track NamespaceHandler objects in the OSGi registry and make * them available, calling listeners when handlers are registered or unregistered. * * @version $Rev$, $Date$ */ public class NamespaceHandlerRegistryImpl implements NamespaceHandlerRegistry, ServiceTrackerCustomizer { public static final String NAMESPACE = "osgi.service.blueprint.namespace"; private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceHandlerRegistryImpl.class); // The bundle context is thread safe private final BundleContext bundleContext; // The service tracker is thread safe private final ServiceTracker tracker; // The handlers map is concurrent private final ConcurrentHashMap<URI, CopyOnWriteArraySet<NamespaceHandler>> handlers = new ConcurrentHashMap<URI, CopyOnWriteArraySet<NamespaceHandler>>(); // Access to the LRU schemas map is synchronized on itself private final LRUMap<Map<URI, NamespaceHandler>, Reference<Schema>> schemas = new LRUMap<Map<URI, NamespaceHandler>, Reference<Schema>>(10); // Access to this factory is synchronized on itself private final SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); // Access to this variable is must be synchronized on itself private final ArrayList<NamespaceHandlerSetImpl> sets = new ArrayList<NamespaceHandlerSetImpl>(); public NamespaceHandlerRegistryImpl(BundleContext bundleContext) { this.bundleContext = bundleContext; tracker = new ServiceTracker(bundleContext, NamespaceHandler.class.getName(), this); tracker.open(); } public Object addingService(ServiceReference reference) { LOGGER.debug("Adding NamespaceHandler " + reference.toString()); NamespaceHandler handler = (NamespaceHandler) bundleContext.getService(reference); if (handler != null) { try { Map<String, Object> props = new HashMap<String, Object>(); for (String name : reference.getPropertyKeys()) { props.put(name, reference.getProperty(name)); } registerHandler(handler, props); } catch (Exception e) { LOGGER.warn("Error registering NamespaceHandler", e); } } else { Bundle bundle = reference.getBundle(); // If bundle is null, the service has already been unregistered, // so do nothing in that case if (bundle != null) { LOGGER.warn("Error resolving NamespaceHandler, null Service obtained from tracked ServiceReference {} for bundle {}/{}", reference.toString(), reference.getBundle().getSymbolicName(), reference.getBundle().getVersion()); } } return handler; } public void modifiedService(ServiceReference reference, Object service) { removedService(reference, service); addingService(reference); } public void removedService(ServiceReference reference, Object service) { try { LOGGER.debug("Removing NamespaceHandler " + reference.toString()); NamespaceHandler handler = (NamespaceHandler) service; Map<String, Object> props = new HashMap<String, Object>(); for (String name : reference.getPropertyKeys()) { props.put(name, reference.getProperty(name)); } unregisterHandler(handler, props); } catch (Exception e) { LOGGER.warn("Error unregistering NamespaceHandler", e); } } public void registerHandler(NamespaceHandler handler, Map properties) { List<URI> namespaces = getNamespaces(properties); for (URI uri : namespaces) { CopyOnWriteArraySet<NamespaceHandler> h = handlers.putIfAbsent(uri, new CopyOnWriteArraySet<NamespaceHandler>()); if (h == null) { h = handlers.get(uri); } if (h.add(handler)) { List<NamespaceHandlerSetImpl> sets; synchronized (this.sets) { sets = new ArrayList<NamespaceHandlerSetImpl>(this.sets); } for (NamespaceHandlerSetImpl s : sets) { s.registerHandler(uri, handler); } } } } public void unregisterHandler(NamespaceHandler handler, Map properties) { List<URI> namespaces = getNamespaces(properties); for (URI uri : namespaces) { CopyOnWriteArraySet<NamespaceHandler> h = handlers.get(uri); if (!h.remove(handler)) { continue; } List<NamespaceHandlerSetImpl> sets; synchronized (this.sets) { sets = new ArrayList<NamespaceHandlerSetImpl>(this.sets); } for (NamespaceHandlerSetImpl s : sets) { s.unregisterHandler(uri, handler); } } removeSchemasFor(handler); } private static List<URI> getNamespaces(Map properties) { Object ns = properties != null ? properties.get(NAMESPACE) : null; if (ns == null) { throw new IllegalArgumentException("NamespaceHandler service does not have an associated " + NAMESPACE + " property defined"); } else if (ns instanceof URI[]) { return Arrays.asList((URI[]) ns); } else if (ns instanceof URI) { return Collections.singletonList((URI) ns); } else if (ns instanceof String) { return Collections.singletonList(URI.create((String) ns)); } else if (ns instanceof String[]) { String[] strings = (String[]) ns; List<URI> namespaces = new ArrayList<URI>(strings.length); for (String string : strings) { namespaces.add(URI.create(string)); } return namespaces; } else if (ns instanceof Collection) { Collection col = (Collection) ns; List<URI> namespaces = new ArrayList<URI>(col.size()); for (Object o : col) { namespaces.add(toURI(o)); } return namespaces; } else if (ns instanceof Object[]) { Object[] array = (Object[]) ns; List<URI> namespaces = new ArrayList<URI>(array.length); for (Object o : array) { namespaces.add(toURI(o)); } return namespaces; } else { throw new IllegalArgumentException("NamespaceHandler service has an associated " + NAMESPACE + " property defined which can not be converted to an array of URI"); } } private static URI toURI(Object o) { if (o instanceof URI) { return (URI) o; } else if (o instanceof String) { return URI.create((String) o); } else { throw new IllegalArgumentException("NamespaceHandler service has an associated " + NAMESPACE + " property defined which can not be converted to an array of URI"); } } public NamespaceHandlerSet getNamespaceHandlers(Set<URI> uris, Bundle bundle) { NamespaceHandlerSetImpl s; synchronized (sets) { s = new NamespaceHandlerSetImpl(uris, bundle); sets.add(s); } return s; } public void destroy() { tracker.close(); } private Schema getExistingSchema(Map<URI, NamespaceHandler> handlers) { synchronized (schemas) { for (Map<URI, NamespaceHandler> key : schemas.keySet()) { boolean found = true; for (URI uri : handlers.keySet()) { if (!handlers.get(uri).equals(key.get(uri))) { found = false; break; } } if (found) { return schemas.get(key).get(); } } return null; } } private void removeSchemasFor(NamespaceHandler handler) { synchronized (schemas) { List<Map<URI, NamespaceHandler>> keys = new ArrayList<Map<URI, NamespaceHandler>>(); for (Map<URI, NamespaceHandler> key : schemas.keySet()) { if (key.values().contains(handler)) { keys.add(key); } } for (Map<URI, NamespaceHandler> key : keys) { schemas.remove(key); } } } private void cacheSchema(Map<URI, NamespaceHandler> handlers, Schema schema) { synchronized (schemas) { // Remove schemas that are fully included for (Iterator<Map<URI, NamespaceHandler>> iterator = schemas.keySet().iterator(); iterator.hasNext();) { Map<URI, NamespaceHandler> key = iterator.next(); boolean found = true; for (URI uri : key.keySet()) { if (!key.get(uri).equals(handlers.get(uri))) { found = false; break; } } if (found) { iterator.remove(); break; } } // Add our new schema schemas.put(handlers, new SoftReference<Schema>(schema)); } } private static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { // Ignore } } private static class SourceLSInput implements LSInput { private final StreamSource source; public SourceLSInput(StreamSource source) { this.source = source; } public Reader getCharacterStream() { return null; } public void setCharacterStream(Reader characterStream) { } public InputStream getByteStream() { return source.getInputStream(); } public void setByteStream(InputStream byteStream) { } public String getStringData() { return null; } public void setStringData(String stringData) { } public String getSystemId() { return source.getSystemId(); } public void setSystemId(String systemId) { } public String getPublicId() { return null; } public void setPublicId(String publicId) { } public String getBaseURI() { return null; } public void setBaseURI(String baseURI) { } public String getEncoding() { return null; } public void setEncoding(String encoding) { } public boolean getCertifiedText() { return false; } public void setCertifiedText(boolean certifiedText) { } } protected class NamespaceHandlerSetImpl implements NamespaceHandlerSet { private final List<Listener> listeners; private final Bundle bundle; private final Set<URI> namespaces; private final Map<URI, NamespaceHandler> handlers; private final Properties schemaMap = new Properties(); private Schema schema; public NamespaceHandlerSetImpl(Set<URI> namespaces, Bundle bundle) { this.listeners = new CopyOnWriteArrayList<Listener>(); this.namespaces = new HashSet<URI>(namespaces); this.bundle = bundle; handlers = new ConcurrentHashMap<URI, NamespaceHandler>(); for (URI ns : namespaces) { findCompatibleNamespaceHandler(ns); } URL url = bundle.getResource("OSGI-INF/blueprint/schema.map"); if (url != null) { InputStream ins = null; try { ins = url.openStream(); schemaMap.load(ins); } catch (IOException ex) { ex.printStackTrace(); //ignore } finally { closeQuietly(ins); } } for (Object ns : schemaMap.keySet()) { try { this.namespaces.remove(new URI(ns.toString())); } catch (URISyntaxException e) { //ignore } } } public boolean isComplete() { return handlers.size() == namespaces.size(); } public Set<URI> getNamespaces() { return namespaces; } public NamespaceHandler getNamespaceHandler(URI namespace) { return handlers.get(namespace); } public Schema getSchema() throws SAXException, IOException { return getSchema(null); } public Schema getSchema(Map<String, String> locations) throws SAXException, IOException { if (!isComplete()) { throw new IllegalStateException("NamespaceHandlerSet is not complete"); } if (schema == null) { schema = doGetSchema(locations); } return schema; } private Schema doGetSchema(Map<String, String> locations) throws IOException, SAXException { if (schemaMap != null && !schemaMap.isEmpty()) { return createSchema(locations); } // Find a schema that can handle all the requested namespaces // If it contains additional namespaces, it should not be a problem since // they won't be used at all Schema schema = getExistingSchema(handlers); if (schema == null) { // Create schema schema = createSchema(locations); cacheSchema(handlers, schema); } return schema; } private class Loader implements LSResourceResolver, Closeable { final List<StreamSource> sources = new ArrayList<StreamSource>(); final Map<String, URL> loaded = new HashMap<String, URL>(); final Map<String, String> namespaces = new HashMap<String, String>(); @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { // Compute id String id; String prevNamespace = baseURI != null ? namespaces.get(baseURI) : null; if (namespaceURI != null && prevNamespace != null && namespaceURI.equals(prevNamespace)) { // This is an include id = getId(type, namespaceURI, publicId, systemId); } else { id = getId(type, namespaceURI, publicId, null); } // Check if it has already been loaded if (loaded.containsKey(id)) { return createLSInput(loaded.get(id), id, namespaceURI); } // Schema map //----------- // Use provided schema map to find the resource. // If the schema map contains the namespaceURI, publicId or systemId, // load the corresponding resource directly from the bundle. String loc = null; if (namespaceURI != null) { loc = schemaMap.getProperty(namespaceURI); } if (loc == null && publicId != null) { loc = schemaMap.getProperty(publicId); } if (loc == null && systemId != null) { loc = schemaMap.getProperty(systemId); } if (loc != null) { URL url = bundle.getResource(loc); if (url != null) { return createLSInput(url, id, namespaceURI); } } // Relative uris //--------------- // For relative uris, don't use the namespace handlers, but simply resolve the uri // and use that one directly to load the resource. String resolved = resolveIfRelative(systemId, baseURI); if (resolved != null) { URL url; try { url = new URL(resolved); } catch (IOException e) { throw new RuntimeException(e); } return createLSInput(url, id, namespaceURI); } // Only support xml schemas from now on if (namespaceURI == null || !W3C_XML_SCHEMA_NS_URI.equals(type)) { return null; } // We are now loading a schema, or schema part with // * notNull(namespaceURI) // * null(systemId) or absolute(systemId) URI nsUri = URI.create(namespaceURI); String rid = systemId != null ? systemId : namespaceURI; NamespaceHandler h = getNamespaceHandler(nsUri); // This is a resource from a known namespace if (h != null) { URL url = h.getSchemaLocation(rid); if (isCorrectUrl(url)) { return createLSInput(url, id, namespaceURI); } } else { // Ask known handlers if they have this schema for (NamespaceHandler hd : handlers.values()) { URL url = hd.getSchemaLocation(rid); if (isCorrectUrl(url)) { return createLSInput(url, id, namespaceURI); } } } LOGGER.warn("Unable to find namespace handler for {}", namespaceURI); return null; } public String getId(String type, String namespaceURI, String publicId, String systemId) { return type + "|" + namespaceURI + "|" + publicId + "|" + systemId; } public StreamSource use(URL resource, String id, String namespace) throws IOException { String url = resource.toExternalForm(); StreamSource ss = new StreamSource(resource.openStream(), url); sources.add(ss); loaded.put(id, resource); namespaces.put(url, namespace); return ss; } @Override public void close() { for (StreamSource source : sources) { closeQuietly(source.getInputStream()); } } public Source[] getSources() { return sources.toArray(new Source[sources.size()]); } private boolean isCorrectUrl(URL url) { return url != null && !loaded.values().contains(url); } private String resolveIfRelative(String systemId, String baseURI) { if (baseURI != null && systemId != null) { URI sId = URI.create(systemId); if (!sId.isAbsolute()) { URI resolved = URI.create(baseURI).resolve(sId); if (resolved.isAbsolute()) { return resolved.toString(); } else { try { return new URL(new URL(baseURI), systemId).toString(); } catch (MalformedURLException e) { LOGGER.warn("Can't resolve " + systemId + " against " + baseURI); return null; } } } } return null; } private LSInput createLSInput(URL url, String id, String namespace) { try { return new SourceLSInput(use(url, id, namespace)); } catch (IOException e) { throw new RuntimeException(e); } } } private Schema createSchema(Map<String, String> locations) throws IOException, SAXException { Loader loader = new Loader(); try { loader.use(getClass().getResource("/org/osgi/service/blueprint/blueprint.xsd"), loader.getId(W3C_XML_SCHEMA_NS_URI, BLUEPRINT_NAMESPACE, null, null), BLUEPRINT_NAMESPACE); loader.use(getClass().getResource("/org/apache/aries/blueprint/ext/impl/xml.xsd"), loader.getId(W3C_XML_SCHEMA_NS_URI, XML_NS_URI, null, null), XML_NS_URI); // Create a schema for the namespaces for (URI ns : handlers.keySet()) { URL url = handlers.get(ns).getSchemaLocation(ns.toString()); if (url == null && locations != null) { String loc = locations.get(ns.toString()); if (loc != null) { url = handlers.get(ns).getSchemaLocation(loc); } } if (url == null) { LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated"); } else { loader.use(url, loader.getId(W3C_XML_SCHEMA_NS_URI, ns.toString(), null, null), ns.toString()); } } for (Object ns : schemaMap.values()) { URL url = bundle.getResource(ns.toString()); if (url == null) { LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated"); } else { loader.use(url, loader.getId(W3C_XML_SCHEMA_NS_URI, ns.toString(), null, null), ns.toString()); } } synchronized (schemaFactory) { schemaFactory.setResourceResolver(loader); return schemaFactory.newSchema(loader.getSources()); } } finally { loader.close(); } } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public void destroy() { synchronized (NamespaceHandlerRegistryImpl.this.sets) { NamespaceHandlerRegistryImpl.this.sets.remove(this); } } public void registerHandler(URI uri, NamespaceHandler handler) { if (namespaces.contains(uri) && handlers.get(uri) == null) { if (findCompatibleNamespaceHandler(uri) != null) { for (Listener listener : listeners) { try { listener.namespaceHandlerRegistered(uri); } catch (Throwable t) { LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t); } } } } } public void unregisterHandler(URI uri, NamespaceHandler handler) { if (handlers.get(uri) == handler) { handlers.remove(uri); for (Listener listener : listeners) { try { listener.namespaceHandlerUnregistered(uri); } catch (Throwable t) { LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t); } } } } private NamespaceHandler findCompatibleNamespaceHandler(URI ns) { Set<NamespaceHandler> candidates = NamespaceHandlerRegistryImpl.this.handlers.get(ns); if (candidates != null) { for (NamespaceHandler h : candidates) { Set<Class> classes = h.getManagedClasses(); boolean compat = true; if (classes != null) { Set<Class> allClasses = new HashSet<Class>(); for (Class cl : classes) { for (Class c = cl; c != null; c = c.getSuperclass()) { allClasses.add(c); for (Class i : c.getInterfaces()) { allClasses.add(i); } } } for (Class cl : allClasses) { Class clb; try { clb = bundle.loadClass(cl.getName()); if (clb != cl) { compat = false; break; } } catch (ClassNotFoundException e) { // Ignore } catch (NoClassDefFoundError e) { // Ignore } } } if (compat) { namespaces.add(ns); handlers.put(ns, wrapIfNeeded(h)); return h; } } } return null; } } /** * Wrap the handler if needed to fix its behavior. * When asked for a schema location, some simple handlers always return * the same url, whatever the asked location is. This can lead to lots * of problems, so we need to verify and fix those behaviors. */ private static NamespaceHandler wrapIfNeeded(final NamespaceHandler handler) { URL result = null; try { result = handler.getSchemaLocation(""); } catch (Throwable t) { // Ignore } if (result != null) { LOGGER.warn("NamespaceHandler " + handler.getClass().getName() + " is behaving badly and should be fixed"); final URL res = result; return new NamespaceHandler() { final ConcurrentMap<String, Boolean> cache = new ConcurrentHashMap<String, Boolean>(); @Override public URL getSchemaLocation(String s) { URL url = handler.getSchemaLocation(s); if (url != null && url.equals(res)) { Boolean v, newValue; Boolean valid = ((v = cache.get(s)) == null && (newValue = isValidSchema(s, url)) != null && (v = cache.putIfAbsent(s, newValue)) == null) ? newValue : v; return valid ? url : null; } return url; } @Override public Set<Class> getManagedClasses() { return handler.getManagedClasses(); } @Override public Metadata parse(Element element, ParserContext parserContext) { return handler.parse(element, parserContext); } @Override public ComponentMetadata decorate(Node node, ComponentMetadata componentMetadata, ParserContext parserContext) { return handler.decorate(node, componentMetadata, parserContext); } private boolean isValidSchema(String ns, URL url) { try { InputStream is = url.openStream(); try { XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(is); try { reader.nextTag(); String nsuri = reader.getNamespaceURI(); String name = reader.getLocalName(); if ("http://www.w3.org/2001/XMLSchema".equals(nsuri) && "schema".equals(name)) { String target = reader.getAttributeValue(null, "targetNamespace"); if (ns.equals(target)) { return true; } } } finally { reader.close(); } } finally { is.close(); } } catch (Throwable t) { // Ignore } return false; } }; } else { return handler; } } public static class LRUMap<K,V> extends AbstractMap<K,V> { private final int bound; private final LinkedList<Entry<K,V>> entries = new LinkedList<Entry<K,V>>(); private static class LRUEntry<K,V> implements Entry<K,V> { private final K key; private final V value; private LRUEntry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } } private LRUMap(int bound) { this.bound = bound; } public V get(Object key) { if (key == null) { throw new NullPointerException(); } for (Entry<K,V> e : entries) { if (e.getKey().equals(key)) { entries.remove(e); entries.addFirst(e); return e.getValue(); } } return null; } public V put(K key, V value) { if (key == null) { throw new NullPointerException(); } V old = null; for (Entry<K,V> e : entries) { if (e.getKey().equals(key)) { entries.remove(e); old = e.getValue(); break; } } if (value != null) { entries.addFirst(new LRUEntry<K,V>(key, value)); while (entries.size() > bound) { entries.removeLast(); } } return old; } public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K,V>>() { public Iterator<Entry<K, V>> iterator() { return entries.iterator(); } public int size() { return entries.size(); } }; } } }
/** * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.coprocessor.Batch; import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback; import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.PoolMap; import org.apache.hadoop.hbase.util.PoolMap.PoolType; /** * A simple pool of HTable instances. * * Each HTablePool acts as a pool for all tables. To use, instantiate an * HTablePool and use {@link #getTable(String)} to get an HTable from the pool. * * This method is not needed anymore, clients should call * HTableInterface.close() rather than returning the tables to the pool * * Once you are done with it, close your instance of {@link HTableInterface} * by calling {@link HTableInterface#close()} rather than returning the tables * to the pool with (deprecated) {@link #putTable(HTableInterface)}. * * <p> * A pool can be created with a <i>maxSize</i> which defines the most HTable * references that will ever be retained for each table. Otherwise the default * is {@link Integer#MAX_VALUE}. * * <p> * Pool will manage its own connections to the cluster. See * {@link HConnectionManager}. */ public class HTablePool implements Closeable { private final PoolMap<String, HTableInterface> tables; private final int maxSize; private final PoolType poolType; private final Configuration config; private final HTableInterfaceFactory tableFactory; /** * Default Constructor. Default HBaseConfiguration and no limit on pool size. */ public HTablePool() { this(HBaseConfiguration.create(), Integer.MAX_VALUE); } /** * Constructor to set maximum versions and use the specified configuration. * * @param config * configuration * @param maxSize * maximum number of references to keep for each table */ public HTablePool(final Configuration config, final int maxSize) { this(config, maxSize, null, null); } /** * Constructor to set maximum versions and use the specified configuration and * table factory. * * @param config * configuration * @param maxSize * maximum number of references to keep for each table * @param tableFactory * table factory */ public HTablePool(final Configuration config, final int maxSize, final HTableInterfaceFactory tableFactory) { this(config, maxSize, tableFactory, PoolType.Reusable); } /** * Constructor to set maximum versions and use the specified configuration and * pool type. * * @param config * configuration * @param maxSize * maximum number of references to keep for each table * @param poolType * pool type which is one of {@link PoolType#Reusable} or * {@link PoolType#ThreadLocal} */ public HTablePool(final Configuration config, final int maxSize, final PoolType poolType) { this(config, maxSize, null, poolType); } /** * Constructor to set maximum versions and use the specified configuration, * table factory and pool type. The HTablePool supports the * {@link PoolType#Reusable} and {@link PoolType#ThreadLocal}. If the pool * type is null or not one of those two values, then it will default to * {@link PoolType#Reusable}. * * @param config * configuration * @param maxSize * maximum number of references to keep for each table * @param tableFactory * table factory * @param poolType * pool type which is one of {@link PoolType#Reusable} or * {@link PoolType#ThreadLocal} */ public HTablePool(final Configuration config, final int maxSize, final HTableInterfaceFactory tableFactory, PoolType poolType) { // Make a new configuration instance so I can safely cleanup when // done with the pool. this.config = config == null ? HBaseConfiguration.create() : config; this.maxSize = maxSize; this.tableFactory = tableFactory == null ? new HTableFactory() : tableFactory; if (poolType == null) { this.poolType = PoolType.Reusable; } else { switch (poolType) { case Reusable: case ThreadLocal: this.poolType = poolType; break; default: this.poolType = PoolType.Reusable; break; } } this.tables = new PoolMap<String, HTableInterface>(this.poolType, this.maxSize); } /** * Get a reference to the specified table from the pool. * <p> * <p/> * * @param tableName * table name * @return a reference to the specified table * @throws RuntimeException * if there is a problem instantiating the HTable */ public HTableInterface getTable(String tableName) { // call the old getTable implementation renamed to findOrCreateTable HTableInterface table = findOrCreateTable(tableName); // return a proxy table so when user closes the proxy, the actual table // will be returned to the pool return new PooledHTable(table); } /** * Get a reference to the specified table from the pool. * <p> * * Create a new one if one is not available. * * @param tableName * table name * @return a reference to the specified table * @throws RuntimeException * if there is a problem instantiating the HTable */ private HTableInterface findOrCreateTable(String tableName) { HTableInterface table = tables.get(tableName); if (table == null) { table = createHTable(tableName); } return table; } /** * Get a reference to the specified table from the pool. * <p> * * Create a new one if one is not available. * * @param tableName * table name * @return a reference to the specified table * @throws RuntimeException * if there is a problem instantiating the HTable */ public HTableInterface getTable(byte[] tableName) { return getTable(Bytes.toString(tableName)); } /** * This method is not needed anymore, clients should call * HTableInterface.close() rather than returning the tables to the pool * * @param table * the proxy table user got from pool * @deprecated */ public void putTable(HTableInterface table) throws IOException { // we need to be sure nobody puts a proxy implementation in the pool // but if the client code is not updated // and it will continue to call putTable() instead of calling close() // then we need to return the wrapped table to the pool instead of the // proxy // table if (table instanceof PooledHTable) { returnTable(((PooledHTable) table).getWrappedTable()); } else { // normally this should not happen if clients pass back the same // table // object they got from the pool // but if it happens then it's better to reject it throw new IllegalArgumentException("not a pooled table: " + table); } } /** * Puts the specified HTable back into the pool. * <p> * * If the pool already contains <i>maxSize</i> references to the table, then * the table instance gets closed after flushing buffered edits. * * @param table * table */ private void returnTable(HTableInterface table) throws IOException { // this is the old putTable method renamed and made private String tableName = Bytes.toString(table.getTableName()); if (tables.size(tableName) >= maxSize) { // release table instance since we're not reusing it this.tables.remove(tableName, table); this.tableFactory.releaseHTableInterface(table); return; } tables.put(tableName, table); } protected HTableInterface createHTable(String tableName) { return this.tableFactory.createHTableInterface(config, Bytes.toBytes(tableName)); } /** * Closes all the HTable instances , belonging to the given table, in the * table pool. * <p> * Note: this is a 'shutdown' of the given table pool and different from * {@link #putTable(HTableInterface)}, that is used to return the table * instance to the pool for future re-use. * * @param tableName */ public void closeTablePool(final String tableName) throws IOException { Collection<HTableInterface> tables = this.tables.values(tableName); if (tables != null) { for (HTableInterface table : tables) { this.tableFactory.releaseHTableInterface(table); } } this.tables.remove(tableName); } /** * See {@link #closeTablePool(String)}. * * @param tableName */ public void closeTablePool(final byte[] tableName) throws IOException { closeTablePool(Bytes.toString(tableName)); } /** * Closes all the HTable instances , belonging to all tables in the table * pool. * <p> * Note: this is a 'shutdown' of all the table pools. */ public void close() throws IOException { for (String tableName : tables.keySet()) { closeTablePool(tableName); } this.tables.clear(); } public int getCurrentPoolSize(String tableName) { return tables.size(tableName); } /** * A proxy class that implements HTableInterface.close method to return the * wrapped table back to the table pool * */ class PooledHTable implements HTableInterface { private HTableInterface table; // actual table implementation public PooledHTable(HTableInterface table) { this.table = table; } @Override public byte[] getTableName() { return table.getTableName(); } @Override public Configuration getConfiguration() { return table.getConfiguration(); } @Override public HTableDescriptor getTableDescriptor() throws IOException { return table.getTableDescriptor(); } @Override public boolean exists(Get get) throws IOException { return table.exists(get); } @Override public void batch(List<? extends Row> actions, Object[] results) throws IOException, InterruptedException { table.batch(actions, results); } @Override public Object[] batch(List<? extends Row> actions) throws IOException, InterruptedException { return table.batch(actions); } @Override public Result get(Get get) throws IOException { return table.get(get); } @Override public Result[] get(List<Get> gets) throws IOException { return table.get(gets); } @Override @SuppressWarnings("deprecation") public Result getRowOrBefore(byte[] row, byte[] family) throws IOException { return table.getRowOrBefore(row, family); } @Override public ResultScanner getScanner(Scan scan) throws IOException { return table.getScanner(scan); } @Override public ResultScanner getScanner(byte[] family) throws IOException { return table.getScanner(family); } @Override public ResultScanner getScanner(byte[] family, byte[] qualifier) throws IOException { return table.getScanner(family, qualifier); } @Override public void put(Put put) throws IOException { table.put(put); } @Override public void put(List<Put> puts) throws IOException { table.put(puts); } @Override public boolean checkAndPut(byte[] row, byte[] family, byte[] qualifier, byte[] value, Put put) throws IOException { return table.checkAndPut(row, family, qualifier, value, put); } @Override public void delete(Delete delete) throws IOException { table.delete(delete); } @Override public void delete(List<Delete> deletes) throws IOException { table.delete(deletes); } @Override public boolean checkAndDelete(byte[] row, byte[] family, byte[] qualifier, byte[] value, Delete delete) throws IOException { return table.checkAndDelete(row, family, qualifier, value, delete); } @Override public Result increment(Increment increment) throws IOException { return table.increment(increment); } @Override public long incrementColumnValue(byte[] row, byte[] family, byte[] qualifier, long amount) throws IOException { return table.incrementColumnValue(row, family, qualifier, amount); } @Override public long incrementColumnValue(byte[] row, byte[] family, byte[] qualifier, long amount, boolean writeToWAL) throws IOException { return table.incrementColumnValue(row, family, qualifier, amount, writeToWAL); } @Override public boolean isAutoFlush() { return table.isAutoFlush(); } @Override public void flushCommits() throws IOException { table.flushCommits(); } /** * Returns the actual table back to the pool * * @throws IOException */ public void close() throws IOException { returnTable(table); } /** * @deprecated {@link RowLock} and associated operations are deprecated */ @Override public RowLock lockRow(byte[] row) throws IOException { return table.lockRow(row); } /** * @deprecated {@link RowLock} and associated operations are deprecated */ @Override public void unlockRow(RowLock rl) throws IOException { table.unlockRow(rl); } @Override public <T extends CoprocessorProtocol> T coprocessorProxy( Class<T> protocol, byte[] row) { return table.coprocessorProxy(protocol, row); } @Override public <T extends CoprocessorProtocol, R> Map<byte[], R> coprocessorExec( Class<T> protocol, byte[] startKey, byte[] endKey, Batch.Call<T, R> callable) throws IOException, Throwable { return table.coprocessorExec(protocol, startKey, endKey, callable); } @Override public <T extends CoprocessorProtocol, R> void coprocessorExec( Class<T> protocol, byte[] startKey, byte[] endKey, Batch.Call<T, R> callable, Batch.Callback<R> callback) throws IOException, Throwable { table.coprocessorExec(protocol, startKey, endKey, callable, callback); } @Override public String toString() { return "PooledHTable{" + ", table=" + table + '}'; } /** * Expose the wrapped HTable to tests in the same package * * @return wrapped htable */ HTableInterface getWrappedTable() { return table; } @Override public void mutateRow(RowMutations rm) throws IOException { table.mutateRow(rm); } @Override public Result append(Append append) throws IOException { return table.append(append); } @Override public void setAutoFlush(boolean autoFlush) { table.setAutoFlush(autoFlush); } @Override public void setAutoFlush(boolean autoFlush, boolean clearBufferOnFail) { table.setAutoFlush(autoFlush, clearBufferOnFail); } @Override public long getWriteBufferSize() { return table.getWriteBufferSize(); } @Override public void setWriteBufferSize(long writeBufferSize) throws IOException { table.setWriteBufferSize(writeBufferSize); } } }
// Copyright (c) 2012 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.database; import android.database.AbstractCursor; import android.database.CursorWindow; import android.util.Log; import org.chromium.base.CalledByNative; import java.sql.Types; /** * This class exposes the query result from native side. */ public class SQLiteCursor extends AbstractCursor { private static final String TAG = "SQLiteCursor"; // Used by JNI. private int mNativeSQLiteCursor; // The count of result rows. private int mCount = -1; private int[] mColumnTypes; private final Object mColumnTypeLock = new Object(); // The belows are the locks for those methods that need wait for // the callback result in native side. private final Object mMoveLock = new Object(); private final Object mGetBlobLock = new Object(); private SQLiteCursor(int nativeSQLiteCursor) { mNativeSQLiteCursor = nativeSQLiteCursor; } @CalledByNative private static SQLiteCursor create(int nativeSQLiteCursor) { return new SQLiteCursor(nativeSQLiteCursor); } @Override public int getCount() { synchronized (mMoveLock) { if (mCount == -1) mCount = nativeGetCount(mNativeSQLiteCursor); } return mCount; } @Override public String[] getColumnNames() { return nativeGetColumnNames(mNativeSQLiteCursor); } @Override public String getString(int column) { return nativeGetString(mNativeSQLiteCursor, column); } @Override public short getShort(int column) { return (short) nativeGetInt(mNativeSQLiteCursor, column); } @Override public int getInt(int column) { return nativeGetInt(mNativeSQLiteCursor, column); } @Override public long getLong(int column) { return nativeGetLong(mNativeSQLiteCursor, column); } @Override public float getFloat(int column) { return (float)nativeGetDouble(mNativeSQLiteCursor, column); } @Override public double getDouble(int column) { return nativeGetDouble(mNativeSQLiteCursor, column); } @Override public boolean isNull(int column) { return nativeIsNull(mNativeSQLiteCursor, column); } @Override public void close() { super.close(); nativeDestroy(mNativeSQLiteCursor); mNativeSQLiteCursor = 0; } @Override public boolean onMove(int oldPosition, int newPosition) { synchronized (mMoveLock) { nativeMoveTo(mNativeSQLiteCursor, newPosition); } return super.onMove(oldPosition, newPosition); } @Override public byte[] getBlob(int column) { synchronized (mGetBlobLock) { return nativeGetBlob(mNativeSQLiteCursor, column); } } @Deprecated public boolean supportsUpdates() { return false; } @Override protected void finalize() { super.finalize(); if (!isClosed()) { Log.w(TAG, "Cursor hasn't been closed"); close(); } } @Override public void fillWindow(int position, CursorWindow window) { if (position < 0 || position > getCount()) { return; } window.acquireReference(); try { int oldpos = mPos; mPos = position - 1; window.clear(); window.setStartPosition(position); int columnNum = getColumnCount(); window.setNumColumns(columnNum); while (moveToNext() && window.allocRow()) { for (int i = 0; i < columnNum; i++) { boolean hasRoom = true; switch (getColumnType(i)) { case Types.DOUBLE: hasRoom = fillRow(window, Double.valueOf(getDouble(i)), mPos, i); break; case Types.NUMERIC: hasRoom = fillRow(window, Long.valueOf(getLong(i)), mPos, i); break; case Types.BLOB: hasRoom = fillRow(window, getBlob(i), mPos, i); break; case Types.LONGVARCHAR: hasRoom = fillRow(window, getString(i), mPos, i); break; case Types.NULL: hasRoom = fillRow(window, null, mPos, i); break; } if (!hasRoom) { break; } } } mPos = oldpos; } catch (IllegalStateException e) { // simply ignore it } finally { window.releaseReference(); } } /** * Fill row with the given value. If the value type is other than Long, * String, byte[] or Double, the NULL will be filled. * * @return true if succeeded, false if window is full. */ private boolean fillRow(CursorWindow window, Object value, int pos, int column) { if (putValue(window, value, pos, column)) { return true; } else { window.freeLastRow(); return false; } } /** * Put the value in given window. If the value type is other than Long, * String, byte[] or Double, the NULL will be filled. * * @return true if succeeded. */ private boolean putValue(CursorWindow window, Object value, int pos, int column) { if (value == null) { return window.putNull(pos, column); } else if (value instanceof Long) { return window.putLong((Long) value, pos, column); } else if (value instanceof String) { return window.putString((String) value, pos, column); } else if (value instanceof byte[] && ((byte[]) value).length > 0) { return window.putBlob((byte[]) value, pos, column); } else if (value instanceof Double) { return window.putDouble((Double) value, pos, column); } else { return window.putNull(pos, column); } } /** * @param index the column index. * @return the column type from cache or native side. */ private int getColumnType(int index) { synchronized (mColumnTypeLock) { if (mColumnTypes == null) { int columnCount = getColumnCount(); mColumnTypes = new int[columnCount]; for (int i = 0; i < columnCount; i++) { mColumnTypes[i] = nativeGetColumnType(mNativeSQLiteCursor, i); } } } return mColumnTypes[index]; } private native void nativeDestroy(int nativeSQLiteCursor); private native int nativeGetCount(int nativeSQLiteCursor); private native String[] nativeGetColumnNames(int nativeSQLiteCursor); private native int nativeGetColumnType(int nativeSQLiteCursor, int column); private native String nativeGetString(int nativeSQLiteCursor, int column); private native byte[] nativeGetBlob(int nativeSQLiteCursor, int column); private native boolean nativeIsNull(int nativeSQLiteCursor, int column); private native long nativeGetLong(int nativeSQLiteCursor, int column); private native int nativeGetInt(int nativeSQLiteCursor, int column); private native double nativeGetDouble(int nativeSQLiteCursor, int column); private native int nativeMoveTo(int nativeSQLiteCursor, int newPosition); }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.datavec.image.loader; import org.datavec.image.data.Image; import org.junit.Test; import org.nd4j.common.resources.Resources; import org.nd4j.linalg.api.ndarray.INDArray; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Random; import static org.junit.Assert.assertEquals; public class TestImageLoader { private static long seed = 10; private static Random rng = new Random(seed); @Test public void testToIntArrayArray() throws Exception { BufferedImage img = makeRandomBufferedImage(true); int w = img.getWidth(); int h = img.getHeight(); int ch = 4; ImageLoader loader = new ImageLoader(0, 0, ch); int[][] arr = loader.toIntArrayArray(img); assertEquals(h, arr.length); assertEquals(w, arr[0].length); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { assertEquals(img.getRGB(j, i), arr[i][j]); } } } @Test public void testToINDArrayBGR() throws Exception { BufferedImage img = makeRandomBufferedImage(false); int w = img.getWidth(); int h = img.getHeight(); int ch = 3; ImageLoader loader = new ImageLoader(0, 0, ch); INDArray arr = loader.toINDArrayBGR(img); long[] shape = arr.shape(); assertEquals(3, shape.length); assertEquals(ch, shape[0]); assertEquals(h, shape[1]); assertEquals(w, shape[2]); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { int srcColor = img.getRGB(j, i); int a = 0xff << 24; int r = arr.getInt(2, i, j) << 16; int g = arr.getInt(1, i, j) << 8; int b = arr.getInt(0, i, j) & 0xff; int dstColor = a | r | g | b; assertEquals(srcColor, dstColor); } } } @Test public void testScalingIfNeed() throws Exception { BufferedImage img1 = makeRandomBufferedImage(true); BufferedImage img2 = makeRandomBufferedImage(false); int w1 = 60, h1 = 110, ch1 = 6; ImageLoader loader1 = new ImageLoader(h1, w1, ch1); BufferedImage scaled1 = loader1.scalingIfNeed(img1, true); assertEquals(w1, scaled1.getWidth()); assertEquals(h1, scaled1.getHeight()); assertEquals(BufferedImage.TYPE_4BYTE_ABGR, scaled1.getType()); assertEquals(4, scaled1.getSampleModel().getNumBands()); BufferedImage scaled2 = loader1.scalingIfNeed(img1, false); assertEquals(w1, scaled2.getWidth()); assertEquals(h1, scaled2.getHeight()); assertEquals(BufferedImage.TYPE_3BYTE_BGR, scaled2.getType()); assertEquals(3, scaled2.getSampleModel().getNumBands()); BufferedImage scaled3 = loader1.scalingIfNeed(img2, true); assertEquals(w1, scaled3.getWidth()); assertEquals(h1, scaled3.getHeight()); assertEquals(BufferedImage.TYPE_3BYTE_BGR, scaled3.getType()); assertEquals(3, scaled3.getSampleModel().getNumBands()); BufferedImage scaled4 = loader1.scalingIfNeed(img2, false); assertEquals(w1, scaled4.getWidth()); assertEquals(h1, scaled4.getHeight()); assertEquals(BufferedImage.TYPE_3BYTE_BGR, scaled4.getType()); assertEquals(3, scaled4.getSampleModel().getNumBands()); int w2 = 70, h2 = 120, ch2 = 6; ImageLoader loader2 = new ImageLoader(h2, w2, ch2); BufferedImage scaled5 = loader2.scalingIfNeed(img1, true); assertEquals(w2, scaled5.getWidth()); assertEquals(h2, scaled5.getHeight(), h2); assertEquals(BufferedImage.TYPE_4BYTE_ABGR, scaled5.getType()); assertEquals(4, scaled5.getSampleModel().getNumBands()); BufferedImage scaled6 = loader2.scalingIfNeed(img1, false); assertEquals(w2, scaled6.getWidth()); assertEquals(h2, scaled6.getHeight()); assertEquals(BufferedImage.TYPE_3BYTE_BGR, scaled6.getType()); assertEquals(3, scaled6.getSampleModel().getNumBands()); } @Test public void testScalingIfNeedWhenSuitableSizeButDiffChannel() { int width1 = 60; int height1 = 110; int channel1 = BufferedImage.TYPE_BYTE_GRAY; BufferedImage img1 = makeRandomBufferedImage(true, width1, height1); ImageLoader loader1 = new ImageLoader(height1, width1, channel1); BufferedImage scaled1 = loader1.scalingIfNeed(img1, false); assertEquals(width1, scaled1.getWidth()); assertEquals(height1, scaled1.getHeight()); assertEquals(channel1, scaled1.getType()); assertEquals(1, scaled1.getSampleModel().getNumBands()); int width2 = 70; int height2 = 120; int channel2 = BufferedImage.TYPE_BYTE_GRAY; BufferedImage img2 = makeRandomBufferedImage(false, width2, height2); ImageLoader loader2 = new ImageLoader(height2, width2, channel2); BufferedImage scaled2 = loader2.scalingIfNeed(img2, false); assertEquals(width2, scaled2.getWidth()); assertEquals(height2, scaled2.getHeight()); assertEquals(channel2, scaled2.getType()); assertEquals(1, scaled2.getSampleModel().getNumBands()); } @Test public void testToBufferedImageRGB() { BufferedImage img = makeRandomBufferedImage(false); int w = img.getWidth(); int h = img.getHeight(); int ch = 3; ImageLoader loader = new ImageLoader(0, 0, ch); INDArray arr = loader.toINDArrayBGR(img); BufferedImage img2 = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR); loader.toBufferedImageRGB(arr, img2); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { int srcColor = img.getRGB(j, i); int restoredColor = img2.getRGB(j, i); assertEquals(srcColor, restoredColor); } } } /** * Generate a Random BufferedImage with specified width and height * * @param alpha Is image alpha * @param width Proposed width * @param height Proposed height * @return Generated BufferedImage */ private BufferedImage makeRandomBufferedImage(boolean alpha, int width, int height) { int type = alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR; BufferedImage img = new BufferedImage(width, height, type); for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { int a = (alpha ? rng.nextInt() : 1) & 0xff; int r = rng.nextInt() & 0xff; int g = rng.nextInt() & 0xff; int b = rng.nextInt() & 0xff; int v = (a << 24) | (r << 16) | (g << 8) | b; img.setRGB(j, i, v); } } return img; } /** * Generate a Random BufferedImage with random width and height * * @param alpha Is image alpha * @return Generated BufferedImage */ private BufferedImage makeRandomBufferedImage(boolean alpha) { return makeRandomBufferedImage(alpha, rng.nextInt() % 100 + 100, rng.nextInt() % 100 + 100); } @Test public void testNCHW_NHWC() throws Exception { File f = Resources.asFile("datavec-data-image/voc/2007/JPEGImages/000005.jpg"); ImageLoader il = new ImageLoader(32, 32, 3); //asMatrix(File, boolean) INDArray a_nchw = il.asMatrix(f); INDArray a_nchw2 = il.asMatrix(f, true); INDArray a_nhwc = il.asMatrix(f, false); assertEquals(a_nchw, a_nchw2); assertEquals(a_nchw, a_nhwc.permute(0,3,1,2)); //asMatrix(InputStream, boolean) try(InputStream is = new BufferedInputStream(new FileInputStream(f))){ a_nchw = il.asMatrix(is); } try(InputStream is = new BufferedInputStream(new FileInputStream(f))){ a_nchw2 = il.asMatrix(is, true); } try(InputStream is = new BufferedInputStream(new FileInputStream(f))){ a_nhwc = il.asMatrix(is, false); } assertEquals(a_nchw, a_nchw2); assertEquals(a_nchw, a_nhwc.permute(0,3,1,2)); //asImageMatrix(File, boolean) Image i_nchw = il.asImageMatrix(f); Image i_nchw2 = il.asImageMatrix(f, true); Image i_nhwc = il.asImageMatrix(f, false); assertEquals(i_nchw.getImage(), i_nchw2.getImage()); assertEquals(i_nchw.getImage(), i_nhwc.getImage().permute(0,3,1,2)); //NHWC to NCHW //asImageMatrix(InputStream, boolean) try(InputStream is = new BufferedInputStream(new FileInputStream(f))){ i_nchw = il.asImageMatrix(is); } try(InputStream is = new BufferedInputStream(new FileInputStream(f))){ i_nchw2 = il.asImageMatrix(is, true); } try(InputStream is = new BufferedInputStream(new FileInputStream(f))){ i_nhwc = il.asImageMatrix(is, false); } assertEquals(i_nchw.getImage(), i_nchw2.getImage()); assertEquals(i_nchw.getImage(), i_nhwc.getImage().permute(0,3,1,2)); //NHWC to NCHW } }
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.databinding; import com.android.SdkConstants; import com.android.ide.common.res2.DataBindingResourceType; import com.android.ide.common.resources.ResourceUrl; import com.android.resources.ResourceType; import com.android.tools.idea.gradle.util.GradleUtil; import com.android.tools.idea.model.ManifestInfo; import com.android.tools.idea.rendering.DataBindingInfo; import com.android.tools.idea.rendering.LocalResourceRepository; import com.android.tools.idea.rendering.PsiDataBindingResourceItem; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.intellij.lang.Language; import com.intellij.lang.java.JavaLanguage; import com.intellij.lexer.JavaLexer; import com.intellij.lexer.Lexer; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ModificationTracker; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.light.LightField; import com.intellij.psi.impl.light.LightIdentifier; import com.intellij.psi.impl.light.LightMethod; import com.intellij.psi.scope.ElementClassHint; import com.intellij.psi.scope.NameHint; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.searches.AnnotatedElementsSearch; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.xml.XmlTag; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.HashSet; import org.jetbrains.android.augment.AndroidLightClassBase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.must.android.module.extension.AndroidModuleExtension; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /** * Utility class that handles the interaction between Data Binding and the IDE. * <p/> * This class handles adding class finders and short names caches for DataBinding related code * completion etc. */ public class DataBindingUtil { public static final String BR = "BR"; private static List<String> VIEW_PACKAGE_ELEMENTS = Arrays.asList(SdkConstants.VIEW, SdkConstants.VIEW_GROUP, SdkConstants.VIEW_STUB, SdkConstants.TEXTURE_VIEW, SdkConstants.SURFACE_VIEW); private static AtomicLong ourDataBindingEnabledModificationCount = new AtomicLong(0); /** * Package private class used by BR class finder and BR short names cache to create a BR file on demand. * * @param facet The facet for which the BR file is necessary. * @return The LightBRClass that belongs to the given AndroidFacet */ static LightBrClass getOrCreateBrClassFor(AndroidModuleExtension<?> facet) { LightBrClass existing = facet.getLightBrClass(); if (existing == null) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (facet) { existing = facet.getLightBrClass(); if (existing == null) { existing = new LightBrClass(PsiManager.getInstance(facet.getModule().getProject()), facet); facet.setLightBrClass(existing); } } } return existing; } private static PsiType parsePsiType(String text, AndroidModuleExtension<?> facet, PsiElement context) { return PsiElementFactory.SERVICE.getInstance(facet.getModule().getProject()).createTypeFromText(text, context); } private static void handleGradleSyncResult(Project project, AndroidModuleExtension<?> facet) { boolean wasEnabled = facet.isDataBindingEnabled(); boolean enabled = project != null && resolveHasDataBinding(facet); if (enabled != wasEnabled) { facet.setDataBindingEnabled(enabled); ourDataBindingEnabledModificationCount.incrementAndGet(); } } public static PsiType resolveViewPsiType(DataBindingInfo.ViewWithId viewWithId, AndroidModuleExtension<?> facet) { String viewClassName = getViewClassName(viewWithId.tag, facet); if (StringUtil.isNotEmpty(viewClassName)) { return parsePsiType(viewClassName, facet, null); } return null; } /** * Receives an {@linkplain XmlTag} and returns the View class that is represented by the tag. * May return null if it cannot find anything reasonable (e.g. it is a merge but does not have data binding) * * @param tag The {@linkplain XmlTag} that represents the View */ @Nullable private static String getViewClassName(XmlTag tag, AndroidModuleExtension<?> facet) { final String elementName = getViewName(tag); if (elementName.indexOf('.') == -1) { if (VIEW_PACKAGE_ELEMENTS.contains(elementName)) { return SdkConstants.VIEW_PKG_PREFIX + elementName; } else if (SdkConstants.WEB_VIEW.equals(elementName)) { return SdkConstants.ANDROID_WEBKIT_PKG + elementName; } else if (SdkConstants.VIEW_MERGE.equals(elementName)) { return getViewClassNameFromMerge(tag, facet); } else if (SdkConstants.VIEW_INCLUDE.equals(elementName)) { return getViewClassNameFromInclude(tag, facet); } return SdkConstants.WIDGET_PKG_PREFIX + elementName; } else { return elementName; } } private static String getViewClassNameFromInclude(XmlTag tag, AndroidModuleExtension<?> facet) { String reference = getViewClassNameFromLayoutReferenceTag(tag, facet); return reference == null ? SdkConstants.CLASS_VIEW : reference; } private static String getViewClassNameFromMerge(XmlTag tag, AndroidModuleExtension<?> facet) { return getViewClassNameFromLayoutReferenceTag(tag, facet); } private static String getViewClassNameFromLayoutReferenceTag(XmlTag tag, AndroidModuleExtension<?> facet) { String layout = tag.getAttributeValue(SdkConstants.ATTR_LAYOUT); if (layout == null) { return null; } LocalResourceRepository moduleResources = facet.getModuleResources(false); if (moduleResources == null) { return null; } ResourceUrl resourceUrl = ResourceUrl.parse(layout); if (resourceUrl == null || resourceUrl.type != ResourceType.LAYOUT) { return null; } DataBindingInfo info = moduleResources.getDataBindingInfoForLayout(resourceUrl.name); if (info == null) { return null; } return info.getQualifiedName(); } private static String getViewName(XmlTag tag) { String viewName = tag.getName(); if (SdkConstants.VIEW_TAG.equals(viewName)) { viewName = tag.getAttributeValue(SdkConstants.ATTR_CLASS, SdkConstants.ANDROID_URI); } return viewName; } private static boolean resolveHasDataBinding(AndroidModuleExtension<?> facet) { if (!facet.isGradleProject()) { return false; } if (facet.getIdeaAndroidProject() == null) { return false; } // TODO Instead of checking library dependency, we should be checking whether data binding plugin is // applied to this facet or not. Having library dependency does not guarantee data binding // unless the plugin is applied as well. return GradleUtil.dependsOn(facet.getIdeaAndroidProject(), SdkConstants.DATA_BINDING_LIB_ARTIFACT); } static PsiClass getOrCreatePsiClass(DataBindingInfo info) { PsiClass psiClass = info.getPsiClass(); if (psiClass == null) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (info) { psiClass = info.getPsiClass(); if (psiClass == null) { psiClass = new LightBindingClass(info.getFacet(), PsiManager.getInstance(info.getProject()), info); info.setPsiClass(psiClass); } } } return psiClass; } /** * Utility method that implements Data Binding's logic to convert a file name to a Java Class name * * @param name The name of the file * @return The class name that will represent the given file */ public static String convertToJavaClassName(String name) { int dotIndex = name.indexOf('.'); if (dotIndex >= 0) { name = name.substring(0, dotIndex); } String[] split = name.split("[_-]"); StringBuilder out = new StringBuilder(); for (String section : split) { out.append(StringUtil.capitalize(section)); } return out.toString(); } /** * Utility method to convert a variable name into java field name. * * @param name The variable name. * @return The java field name for the given variable name. */ public static String convertToJavaFieldName(String name) { int dotIndex = name.indexOf('.'); if (dotIndex >= 0) { name = name.substring(0, dotIndex); } String[] split = name.split("[_-]"); StringBuilder out = new StringBuilder(); boolean first = true; for (String section : split) { if (first) { first = false; out.append(section); } else { out.append(StringUtil.capitalize(section)); } } return out.toString(); } /** * Returns the qualified name for the BR file for the given Facet. * * @param facet The {@linkplain AndroidModuleExtension} to check. * @return The qualified name for the BR class of the given Android Facet. */ public static String getBrQualifiedName(AndroidModuleExtension facet) { return getGeneratedPackageName(facet) + "." + BR; } /** * Returns the package name that will be use to generate R file or BR file. * * @param facet The {@linkplain org.must.android.module.extension.AndroidModuleExtension} to check. * @return The package name that can be used to generate R and BR classes. */ public static String getGeneratedPackageName(AndroidModuleExtension<?> facet) { return ManifestInfo.get(facet.getModule(), false).getPackage(); } /** * Called by the {@linkplain AndroidModuleExtension} to refresh its data binding status. * * @param facet the {@linkplain AndroidModuleExtension} whose IdeaProject is just set. */ public static void onIdeaProjectSet(AndroidModuleExtension<?> facet) { handleGradleSyncResult(facet.getModule().getProject(), facet); } /** * The light class that represents the generated data binding code for a layout file. */ static class LightBindingClass extends AndroidLightClassBase { private static final String BASE_CLASS = "android.databinding.ViewDataBinding"; static final int STATIC_METHOD_COUNT = 3; private DataBindingInfo myInfo; private CachedValue<PsiMethod[]> myPsiMethodsCache; private CachedValue<PsiField[]> myPsiFieldsCache; private CachedValue<Map<String, String>> myAliasCache; private PsiReferenceList myExtendsList; private PsiClassType[] myExtendsListTypes; private final AndroidModuleExtension<?> myFacet; private static Lexer ourJavaLexer; protected LightBindingClass(final AndroidModuleExtension<?> facet, @NotNull PsiManager psiManager, DataBindingInfo info) { super(psiManager); myInfo = info; myFacet = facet; CachedValuesManager cachedValuesManager = CachedValuesManager.getManager(info.getProject()); myAliasCache = cachedValuesManager.createCachedValue(new ResourceCacheValueProvider<Map<String, String>>(facet) { @Override Map<String, String> doCompute() { List<PsiDataBindingResourceItem> imports = myInfo.getItems(DataBindingResourceType.IMPORT); Map<String, String> result = new HashMap<String, String>(); if (imports != null) { for (PsiDataBindingResourceItem imp : imports) { String alias = imp.getExtra(SdkConstants.ATTR_ALIAS); if (alias != null) { result.put(alias, imp.getExtra(SdkConstants.ATTR_TYPE)); } } } return result; } @Override Map<String, String> defaultValue() { return Maps.newHashMap(); } }, false); myPsiMethodsCache = cachedValuesManager.createCachedValue(new ResourceCacheValueProvider<PsiMethod[]>(facet) { @Override PsiMethod[] doCompute() { List<PsiDataBindingResourceItem> variables = myInfo.getItems(DataBindingResourceType.VARIABLE); if (variables == null) { return PsiMethod.EMPTY_ARRAY; } PsiMethod[] methods = new PsiMethod[variables.size() * 2 + STATIC_METHOD_COUNT]; PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(myInfo.getProject()); for (int i = 0; i < variables.size(); i++) { createVariableMethods(factory, variables.get(i), methods, i * 2); } createStaticMethods(factory, methods, variables.size() * 2); return methods; } @Override PsiMethod[] defaultValue() { return PsiMethod.EMPTY_ARRAY; } }); myPsiFieldsCache = cachedValuesManager.createCachedValue(new ResourceCacheValueProvider<PsiField[]>(facet) { @Override PsiField[] doCompute() { List<DataBindingInfo.ViewWithId> viewsWithIds = myInfo.getViewsWithIds(); PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(myInfo.getProject()); PsiField[] result = new PsiField[viewsWithIds.size()]; int i = 0; int unresolved = 0; for (DataBindingInfo.ViewWithId viewWithId : viewsWithIds) { PsiField psiField = createPsiField(factory, viewWithId); if (psiField == null) { unresolved++; } else { result[i++] = psiField; } } if (unresolved > 0) { PsiField[] validResult = new PsiField[i]; System.arraycopy(result, 0, validResult, 0, i); return validResult; } return result; } @Override PsiField[] defaultValue() { return PsiField.EMPTY_ARRAY; } }); } @Override public String toString() { return myInfo.getClassName(); } @Nullable @Override public String getQualifiedName() { return myInfo.getQualifiedName(); } @Nullable @Override public PsiClass getContainingClass() { return null; } @NotNull @Override public PsiField[] getFields() { return myPsiFieldsCache.getValue(); } @NotNull @Override public PsiField[] getAllFields() { return getFields(); } @NotNull @Override public PsiMethod[] getMethods() { return myPsiMethodsCache.getValue(); } @Override public PsiClass getSuperClass() { return JavaPsiFacade.getInstance(myInfo.getProject()) .findClass(BASE_CLASS, myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(false)); } @Override public PsiReferenceList getExtendsList() { if (myExtendsList == null) { PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(myInfo.getProject()); PsiJavaCodeReferenceElement referenceElementByType = factory.createReferenceElementByType(getExtendsListTypes()[0]); myExtendsList = factory.createReferenceList(new PsiJavaCodeReferenceElement[]{referenceElementByType}); } return myExtendsList; } @NotNull @Override public PsiClassType[] getSuperTypes() { return getExtendsListTypes(); } @NotNull @Override public PsiClassType[] getExtendsListTypes() { if (myExtendsListTypes == null) { myExtendsListTypes = new PsiClassType[]{ PsiType.getTypeByName(BASE_CLASS, myInfo.getProject(), myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(false))}; } return myExtendsListTypes; } @NotNull @Override public PsiMethod[] getAllMethods() { return getMethods(); } @NotNull @Override public PsiMethod[] findMethodsByName(@NonNls String name, boolean checkBases) { List<PsiMethod> matched = null; for (PsiMethod method : getMethods()) { if (name.equals(method.getName())) { if (matched == null) { matched = Lists.newArrayList(); } matched.add(method); } } return matched == null ? PsiMethod.EMPTY_ARRAY : matched.toArray(new PsiMethod[matched.size()]); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { boolean continueProcessing = super.processDeclarations(processor, state, lastParent, place); if (!continueProcessing) { return false; } List<PsiDataBindingResourceItem> imports = myInfo.getItems(DataBindingResourceType.IMPORT); if (imports == null || imports.isEmpty()) { return true; } final ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); if (classHint != null && classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) { final NameHint nameHint = processor.getHint(NameHint.KEY); final String name = nameHint != null ? nameHint.getName(state) : null; for (PsiDataBindingResourceItem imp : imports) { String alias = imp.getExtra(SdkConstants.ATTR_ALIAS); if (alias != null) { continue; // aliases are pre-resolved in {@linkplain #replaceImportAliases} } String qName = imp.getExtra(SdkConstants.ATTR_TYPE); if (qName == null) { continue; } if (name != null && !qName.endsWith("." + name)) { continue; } Module module = myInfo.getModule(); if (module == null) { return true; // this should not really happen but just to be safe } PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(qName, module .getModuleWithDependenciesAndLibrariesScope(true)); if (aClass != null) { if (!processor.execute(aClass, state)) { // found it! return false; } } } } return true; } private static Lexer getJavaLexer() { if (ourJavaLexer == null) { ourJavaLexer = new JavaLexer(LanguageLevel.JDK_1_6); } return ourJavaLexer; } private String replaceImportAliases(String type) { Map<String, String> lookup = myAliasCache.getValue(); if (lookup == null || lookup.isEmpty()) { return type; } Lexer lexer = getJavaLexer(); lexer.start(type); boolean checkNext = true; StringBuilder out = new StringBuilder(); IElementType tokenType = lexer.getTokenType(); while (tokenType != null) { if (checkNext && tokenType == JavaTokenType.IDENTIFIER) { // this might be something we want to replace String tokenText = lexer.getTokenText(); String replacement = lookup.get(tokenText); if (replacement != null) { out.append(replacement); } else { out.append(tokenText); } } else { out.append(lexer.getTokenText()); } if (tokenType != TokenType.WHITE_SPACE) { // ignore spaces if (tokenType == JavaTokenType.LT || tokenType == JavaTokenType.COMMA) { checkNext = true; } else { checkNext = false; } } lexer.advance(); tokenType = lexer.getTokenType(); } return out.toString(); } private void createVariableMethods(PsiElementFactory factory, PsiDataBindingResourceItem item, PsiMethod[] outPsiMethods, int index) { PsiManager psiManager = PsiManager.getInstance(myInfo.getProject()); PsiMethod setter = factory.createMethod("set" + StringUtil.capitalize(item.getName()), PsiType.VOID); String variableType = replaceImportAliases(item.getExtra(SdkConstants.ATTR_TYPE)); PsiType type = parsePsiType(variableType, myFacet, this); PsiParameter param = factory.createParameter(item.getName(), type); setter.getParameterList().add(param); PsiUtil.setModifierProperty(setter, PsiModifier.PUBLIC, true); outPsiMethods[index] = new LightDataBindingMethod(item.getXmlTag(), psiManager, setter, this, JavaLanguage.INSTANCE); PsiMethod getter = factory.createMethod("get" + StringUtil.capitalize(item.getName()), type); PsiUtil.setModifierProperty(getter, PsiModifier.PUBLIC, true); outPsiMethods[index + 1] = new LightDataBindingMethod(item.getXmlTag(), psiManager, getter, this, JavaLanguage.INSTANCE); } private void createStaticMethods(PsiElementFactory factory, PsiMethod[] outPsiMethods, int index) { PsiClassType myType = factory.createType(this); PsiClassType viewGroupType = PsiType .getTypeByName(SdkConstants.CLASS_VIEWGROUP, myInfo.getProject(), myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(true)); PsiClassType layoutInflaterType = PsiType.getTypeByName(SdkConstants.CLASS_LAYOUT_INFLATER, myInfo.getProject(), myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(true)); PsiClassType viewType = PsiType .getTypeByName(SdkConstants.CLASS_VIEW, myInfo.getProject(), myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(true)); PsiParameter layoutInflaterParam = factory.createParameter("inflater", layoutInflaterType); PsiParameter rootParam = factory.createParameter("root", viewGroupType); PsiParameter attachToRootParam = factory.createParameter("attachToRoot", PsiType.BOOLEAN); PsiParameter viewParam = factory.createParameter("view", viewType); PsiMethod inflate3Arg = factory.createMethod("inflate", myType); inflate3Arg.getParameterList().add(layoutInflaterParam); inflate3Arg.getParameterList().add(rootParam); inflate3Arg.getParameterList().add(attachToRootParam); PsiMethod inflate1Arg = factory.createMethod("inflate", myType); inflate1Arg.getParameterList().add(layoutInflaterParam); PsiMethod bind = factory.createMethod("bind", myType); bind.getParameterList().add(viewParam); PsiMethod[] methods = new PsiMethod[]{inflate1Arg, inflate3Arg, bind}; PsiManager psiManager = PsiManager.getInstance(myInfo.getProject()); for (PsiMethod method : methods) { PsiUtil.setModifierProperty(method, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(method, PsiModifier.STATIC, true); //noinspection ConstantConditions outPsiMethods[index++] = new LightDataBindingMethod(myInfo.getPsiFile(), psiManager, method, this, JavaLanguage.INSTANCE); } } @Nullable private PsiField createPsiField(PsiElementFactory factory, DataBindingInfo.ViewWithId viewWithId) { PsiType type = resolveViewPsiType(viewWithId, myFacet); assert type != null; PsiField field = factory.createField(viewWithId.name, type); PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); return new LightDataBindingField(viewWithId, PsiManager.getInstance(myInfo.getProject()), field, this); } @Override public boolean isInterface() { return false; } @NotNull @Override public PsiElement getNavigationElement() { return myInfo.getNavigationElement(); } @Override public String getName() { return myInfo.getClassName(); } @Nullable @Override public PsiFile getContainingFile() { return myInfo.getPsiFile(); } } /** * The light method class that represents the generated data binding methods for a layout file. */ static class LightDataBindingMethod extends LightMethod { private PsiElement myNavigationElement; public LightDataBindingMethod(@NotNull PsiElement navigationElement, @NotNull PsiManager manager, @NotNull PsiMethod method, @NotNull PsiClass containingClass, @NotNull Language language) { super(manager, method, containingClass, language); myNavigationElement = navigationElement; } @NotNull @Override public PsiElement getNavigationElement() { return myNavigationElement; } @Override public PsiIdentifier getNameIdentifier() { return new LightIdentifier(getManager(), getName()); } } /** * The light field class that represents the generated view fields for a layout file. */ static class LightDataBindingField extends LightField { private final DataBindingInfo.ViewWithId myViewWithId; public LightDataBindingField(DataBindingInfo.ViewWithId viewWithId, @NotNull PsiManager manager, @NotNull PsiField field, @NotNull PsiClass containingClass) { super(manager, field, containingClass); myViewWithId = viewWithId; } @NotNull @Override public PsiElement getNavigationElement() { return myViewWithId.tag; } } /** * The light class that represents a data binding BR file */ public static class LightBrClass extends AndroidLightClassBase { private static final String BINDABLE_QUALIFIED_NAME = "android.databinding.Bindable"; private final AndroidModuleExtension<?> myFacet; private CachedValue<PsiField[]> myFieldCache; @NotNull private String[] myCachedFieldNames = new String[]{"_all"}; private final String myQualifiedName; private PsiFile myContainingFile; public LightBrClass(@NotNull PsiManager psiManager, final AndroidModuleExtension<?> facet) { super(psiManager); myQualifiedName = getBrQualifiedName(facet); myFacet = facet; myFieldCache = CachedValuesManager.getManager(facet.getModule().getProject()).createCachedValue( new ResourceCacheValueProvider<PsiField[]>(facet, psiManager.getModificationTracker().getJavaStructureModificationTracker()) { @Override PsiField[] doCompute() { Project project = facet.getModule().getProject(); PsiElementFactory elementFactory = PsiElementFactory.SERVICE.getInstance(project); LocalResourceRepository moduleResources = facet.getModuleResources(false); if (moduleResources == null) { return defaultValue(); } Map<String, DataBindingInfo> dataBindingResourceFiles = moduleResources.getDataBindingResourceFiles(); if (dataBindingResourceFiles == null) { return defaultValue(); } Set<String> variableNames = new HashSet<String>(); for (DataBindingInfo info : dataBindingResourceFiles.values()) { List<PsiDataBindingResourceItem> variables = info.getItems(DataBindingResourceType.VARIABLE); if (variables != null) { for (PsiDataBindingResourceItem item : variables) { variableNames.add(item.getName()); } } } Set<String> bindables = collectVariableNamesFromBindables(); if (bindables != null) { variableNames.addAll(bindables); } PsiField[] result = new PsiField[variableNames.size() + 1]; result[0] = createPsiField(project, elementFactory, "_all"); int i = 1; for (String variable : variableNames) { result[i++] = createPsiField(project, elementFactory, variable); } myCachedFieldNames = ArrayUtil.toStringArray(variableNames); return result; } @Override PsiField[] defaultValue() { Project project = facet.getModule().getProject(); return new PsiField[]{createPsiField(project, PsiElementFactory.SERVICE.getInstance(project), "_all")}; } }); } private Set<String> collectVariableNamesFromBindables() { JavaPsiFacade facade = JavaPsiFacade.getInstance(myFacet.getModule().getProject()); PsiClass aClass = facade.findClass(BINDABLE_QUALIFIED_NAME, myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(false)); if (aClass == null) { return null; } //noinspection unchecked final Collection<? extends PsiModifierListOwner> psiElements = AnnotatedElementsSearch.searchElements(aClass, myFacet.getModule().getModuleScope(), PsiMethod.class, PsiField.class).findAll(); return BrUtil.collectIds(psiElements); } private PsiField createPsiField(Project project, PsiElementFactory factory, String id) { PsiField field = factory.createField(id, PsiType.INT); PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); return new LightBRField(PsiManager.getInstance(project), field, this); } @Override public String toString() { return "BR class for " + myFacet; } @Nullable @Override public String getQualifiedName() { return myQualifiedName; } @Override public String getName() { return BR; } @NotNull public String[] getAllFieldNames() { return myCachedFieldNames; } @Nullable @Override public PsiClass getContainingClass() { return null; } @NotNull @Override public PsiField[] getFields() { return myFieldCache.getValue(); } @NotNull @Override public PsiField[] getAllFields() { return getFields(); } @Nullable @Override public PsiFile getContainingFile() { if (myContainingFile == null) { // TODO: using R file for now. Would be better if we create a real VirtualFile for this. PsiClass aClass = JavaPsiFacade.getInstance(myFacet.getModule().getProject()) .findClass(getGeneratedPackageName(myFacet) + ".R", myFacet.getModule().getModuleScope()); if (aClass != null) { myContainingFile = aClass.getContainingFile(); } } return myContainingFile; } @Override public PsiIdentifier getNameIdentifier() { return new LightIdentifier(getManager(), getName()); } @NotNull @Override public PsiElement getNavigationElement() { PsiFile containingFile = getContainingFile(); return containingFile == null ? super.getNavigationElement() : containingFile; } } /** * The light field representing elements of BR class */ static class LightBRField extends LightField { public LightBRField(@NotNull PsiManager manager, @NotNull PsiField field, @NotNull PsiClass containingClass) { super(manager, field, containingClass); } } /** * Tracker that changes when a facet's data binding enabled value changes */ public static ModificationTracker DATA_BINDING_ENABLED_TRACKER = new ModificationTracker() { @Override public long getModificationCount() { return ourDataBindingEnabledModificationCount.longValue(); } }; }
/* * 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 opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; import opennlp.tools.util.StringUtil; /** * An import stream which can parse the CONLL03 data. */ public class Conll03NameSampleStream implements ObjectStream<NameSample> { public enum LANGUAGE { EN, DE } private final LANGUAGE lang; private final ObjectStream<String> lineStream; private final int types; /** * * @param lang the language of the CONLL 03 data * @param lineStream an Object Stream over the lines in the CONLL 03 data file * @param types the entity types to include in the Name Sample object stream */ public Conll03NameSampleStream(LANGUAGE lang, ObjectStream<String> lineStream, int types) { this.lang = lang; this.lineStream = lineStream; this.types = types; } public Conll03NameSampleStream(LANGUAGE lang, InputStreamFactory in, int types) throws IOException { this.lang = lang; try { this.lineStream = new PlainTextByLineStream(in, StandardCharsets.UTF_8); System.setOut(new PrintStream(System.out, true, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { // UTF-8 is available on all JVMs, will never happen throw new IllegalStateException(e); } this.types = types; } public NameSample read() throws IOException { List<String> sentence = new ArrayList<>(); List<String> tags = new ArrayList<>(); boolean isClearAdaptiveData = false; // Empty line indicates end of sentence String line; while ((line = lineStream.read()) != null && !StringUtil.isEmpty(line)) { if (line.startsWith(Conll02NameSampleStream.DOCSTART)) { isClearAdaptiveData = true; String emptyLine = lineStream.read(); if (!StringUtil.isEmpty(emptyLine)) throw new IOException("Empty line after -DOCSTART- not empty: '" + emptyLine + "'!"); continue; } String[] fields = line.split(" "); // For English: WORD POS-TAG SC-TAG NE-TAG if (LANGUAGE.EN.equals(lang) && fields.length == 4) { sentence.add(fields[0]); tags.add(fields[3]); // 3 is NE-TAG } // For German: WORD LEMA-TAG POS-TAG SC-TAG NE-TAG else if (LANGUAGE.DE.equals(lang) && fields.length == 5) { sentence.add(fields[0]); tags.add(fields[4]); // 4 is NE-TAG } else { throw new IOException("Incorrect number of fields per line for language: '" + line + "'!"); } } if (sentence.size() > 0) { // convert name tags into spans List<Span> names = new ArrayList<>(); int beginIndex = -1; int endIndex = -1; for (int i = 0; i < tags.size(); i++) { String tag = tags.get(i); if (tag.endsWith("PER") && (types & Conll02NameSampleStream.GENERATE_PERSON_ENTITIES) == 0) tag = "O"; if (tag.endsWith("ORG") && (types & Conll02NameSampleStream.GENERATE_ORGANIZATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("LOC") && (types & Conll02NameSampleStream.GENERATE_LOCATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("MISC") && (types & Conll02NameSampleStream.GENERATE_MISC_ENTITIES) == 0) tag = "O"; if (tag.equals("O")) { // O means we don't have anything this round. if (beginIndex != -1) { names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = -1; endIndex = -1; } } else if (tag.startsWith("B-")) { // B- prefix means we have two same entities next to each other if (beginIndex != -1) { names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); } beginIndex = i; endIndex = i + 1; } else if (tag.startsWith("I-")) { // I- starts or continues a current name entity if (beginIndex == -1) { beginIndex = i; endIndex = i + 1; } else if (!tag.endsWith(tags.get(beginIndex).substring(1))) { // we have a new tag type following a tagged word series // also may not have the same I- starting the previous! names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = i; endIndex = i + 1; } else { endIndex ++; } } else { throw new IOException("Invalid tag: " + tag); } } // if one span remains, create it here if (beginIndex != -1) names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); return new NameSample(sentence.toArray(new String[sentence.size()]), names.toArray(new Span[names.size()]), isClearAdaptiveData); } else if (line != null) { // Just filter out empty events, if two lines in a row are empty return read(); } else { // source stream is not returning anymore lines return null; } } public void reset() throws IOException, UnsupportedOperationException { lineStream.reset(); } public void close() throws IOException { lineStream.close(); } }
package net.wigle.wigleandroid.listener; import static android.location.LocationManager.GPS_PROVIDER; import static android.location.LocationManager.NETWORK_PROVIDER; import net.wigle.wigleandroid.ListFragment; import net.wigle.wigleandroid.MainActivity; import net.wigle.wigleandroid.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.GpsStatus.Listener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; public class GPSListener implements Listener, LocationListener { private static final long GPS_TIMEOUT = 15000L; private static final long NET_LOC_TIMEOUT = 60000L; private MainActivity mainActivity; private Location location; private Location networkLocation; private GpsStatus gpsStatus; // set these times to avoid NPE in locationOK() seen by <DooMMasteR> private Long lastLocationTime = 0L; private Long lastNetworkLocationTime = 0L; private Long satCountLowTime = 0L; private float previousSpeed = 0f; private LocationListener mapLocationListener; public GPSListener( MainActivity mainActivity ) { this.mainActivity = mainActivity; } public void setMapListener( LocationListener mapLocationListener ) { this.mapLocationListener = mapLocationListener; } public void setMainActivity( MainActivity mainActivity ) { this.mainActivity = mainActivity; } @Override public void onGpsStatusChanged( final int event ) { if ( event == GpsStatus.GPS_EVENT_STOPPED ) { MainActivity.info("GPS STOPPED"); // this event lies, on one device it gets called when the // network provider is disabled :( so we do nothing... // listActivity.setLocationUpdates(); } // MainActivity.info("GPS event: " + event); updateLocationData(null); } public void handleScanStop() { MainActivity.info("GPSListener: handleScanStop"); gpsStatus = null; location = null; } @Override public void onLocationChanged( final Location newLocation ) { // MainActivity.info("GPS onLocationChanged: " + newLocation); updateLocationData( newLocation ); if ( mapLocationListener != null ) { mapLocationListener.onLocationChanged( newLocation ); } } @Override public void onProviderDisabled( final String provider ) { MainActivity.info("provider disabled: " + provider); if ( mapLocationListener != null ) { mapLocationListener.onProviderDisabled( provider ); } } @Override public void onProviderEnabled( final String provider ) { MainActivity.info("provider enabled: " + provider); if ( mapLocationListener != null ) { mapLocationListener.onProviderEnabled( provider ); } } @Override public void onStatusChanged( final String provider, final int status, final Bundle extras ) { MainActivity.info("provider status changed: " + provider + " status: " + status); if ( mapLocationListener != null ) { mapLocationListener.onStatusChanged( provider, status, extras ); } } /** newLocation can be null */ private void updateLocationData( final Location newLocation ) { final LocationManager locationManager = (LocationManager) mainActivity.getSystemService(Context.LOCATION_SERVICE); // see if we have new data gpsStatus = locationManager.getGpsStatus( gpsStatus ); final int satCount = getSatCount(); boolean newOK = newLocation != null; final boolean locOK = locationOK( location, satCount ); final long now = System.currentTimeMillis(); if ( newOK ) { if ( NETWORK_PROVIDER.equals( newLocation.getProvider() ) ) { // save for later, in case we lose gps networkLocation = newLocation; lastNetworkLocationTime = now; } else { lastLocationTime = now; // make sure there's enough sats on this new gps location newOK = locationOK( newLocation, satCount ); } } if ( mainActivity.inEmulator() && newLocation != null ) { newOK = true; } final boolean netLocOK = locationOK( networkLocation, satCount ); boolean wasProviderChange = false; if ( ! locOK ) { if ( newOK ) { wasProviderChange = true; //noinspection RedundantIfStatement if ( location != null && ! location.getProvider().equals( newLocation.getProvider() ) ) { wasProviderChange = false; } location = newLocation; } else if ( netLocOK ) { location = networkLocation; wasProviderChange = true; } else if ( location != null ) { // transition to null MainActivity.info( "nulling location: " + location ); location = null; wasProviderChange = true; // make sure we're registered for updates mainActivity.setLocationUpdates(); } } else if ( newOK && GPS_PROVIDER.equals( newLocation.getProvider() ) ) { if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { // this is an upgrade from network to gps wasProviderChange = true; } location = newLocation; if ( wasProviderChange ) { // save it in prefs saveLocation(); } } else if ( newOK && NETWORK_PROVIDER.equals( newLocation.getProvider() ) ) { if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { // just a new network provided location over an old one location = newLocation; } } // for maps. so lame! ListFragment.lameStatic.location = location; boolean scanScheduled = false; if ( location != null ) { final float currentSpeed = location.getSpeed(); if ( (previousSpeed == 0f && currentSpeed > 0f) || (previousSpeed < 5f && currentSpeed >= 5f)) { // moving faster now than before, schedule a scan because the timing config pry changed MainActivity.info("Going faster, scheduling scan"); mainActivity.scheduleScan(); scanScheduled = true; } previousSpeed = currentSpeed; } else { previousSpeed = 0f; } // MainActivity.info("sat count: " + satCount); if ( wasProviderChange ) { MainActivity.info( "wasProviderChange: satCount: " + satCount + " newOK: " + newOK + " locOK: " + locOK + " netLocOK: " + netLocOK + (newOK ? " newProvider: " + newLocation.getProvider() : "") + (locOK ? " locProvider: " + location.getProvider() : "") + " newLocation: " + newLocation ); final SharedPreferences prefs = mainActivity.getSharedPreferences( ListFragment.SHARED_PREFS, 0 ); final boolean disableToast = prefs.getBoolean( ListFragment.PREF_DISABLE_TOAST, false ); if (!disableToast) { final String announce = location == null ? mainActivity.getString(R.string.lost_location) : mainActivity.getString(R.string.have_location) + " \"" + location.getProvider() + "\""; Toast.makeText( mainActivity, announce, Toast.LENGTH_SHORT ).show(); } final boolean speechGPS = prefs.getBoolean( ListFragment.PREF_SPEECH_GPS, true ); if ( speechGPS ) { // no quotes or the voice pauses final String speakAnnounce = location == null ? "Lost Location" : "Now have location from " + location.getProvider() + "."; mainActivity.speak( speakAnnounce ); } if ( ! scanScheduled ) { // get the ball rolling MainActivity.info("Location provider change, scheduling scan"); mainActivity.scheduleScan(); } } // update the UI mainActivity.setLocationUI(); } public void checkLocationOK() { if ( ! locationOK( location, getSatCount() ) ) { // do a self-check updateLocationData(null); } } private boolean locationOK( final Location location, final int satCount ) { boolean retval = false; final long now = System.currentTimeMillis(); //noinspection StatementWithEmptyBody if ( location == null ) { // bad! } else if ( GPS_PROVIDER.equals( location.getProvider() ) ) { if ( satCount > 0 && satCount < 3 ) { if ( satCountLowTime == null ) { satCountLowTime = now; } } else { // plenty of sats satCountLowTime = null; } boolean gpsLost = satCountLowTime != null && (now - satCountLowTime) > GPS_TIMEOUT; gpsLost |= now - lastLocationTime > GPS_TIMEOUT; gpsLost |= horribleGps(location); retval = ! gpsLost; } else if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { boolean gpsLost = now - lastNetworkLocationTime > NET_LOC_TIMEOUT; gpsLost |= horribleGps(location); retval = ! gpsLost; } return retval; } private boolean horribleGps(final Location location) { // try to protect against some horrible gps's out there // check if accuracy is under 10 miles boolean horrible = location.hasAccuracy() && location.getAccuracy() > 16000; horrible |= location.getLatitude() < -90 || location.getLatitude() > 90; horrible |= location.getLongitude() < -180 || location.getLongitude() > 180; return horrible; } public int getSatCount() { int satCount = 0; if ( gpsStatus != null ) { for ( GpsSatellite sat : gpsStatus.getSatellites() ) { if ( sat.usedInFix() ) { satCount++; } } } return satCount; } public void saveLocation() { // save our location for use on later runs if ( this.location != null ) { final SharedPreferences prefs = mainActivity.getSharedPreferences( ListFragment.SHARED_PREFS, 0 ); final Editor edit = prefs.edit(); // there is no putDouble edit.putFloat( ListFragment.PREF_PREV_LAT, (float) location.getLatitude() ); edit.putFloat( ListFragment.PREF_PREV_LON, (float) location.getLongitude() ); edit.apply(); } } public Location getLocation() { return location; } }
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Author: Mike J&auml;ger * * Creation Date: 12.03.2010 * * Completion Time: 12.03.2010 * *******************************************************************************/ package org.oscm.domobjects; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import org.junit.Assert; import org.junit.Test; import org.oscm.dataservice.bean.DataServiceBean; import org.oscm.dataservice.local.DataService; import org.oscm.domobjects.enums.BillingAdapterIdentifier; import org.oscm.domobjects.enums.LocalizedObjectTypes; import org.oscm.internal.types.enumtypes.EventType; import org.oscm.internal.types.enumtypes.OrganizationRoleType; import org.oscm.internal.types.enumtypes.ParameterType; import org.oscm.internal.types.enumtypes.ParameterValueType; import org.oscm.internal.types.enumtypes.PaymentCollectionType; import org.oscm.internal.types.enumtypes.PriceModelType; import org.oscm.internal.types.enumtypes.ServiceStatus; import org.oscm.internal.types.enumtypes.ServiceType; import org.oscm.internal.types.enumtypes.SubscriptionStatus; import org.oscm.internal.types.enumtypes.TriggerProcessStatus; import org.oscm.internal.types.enumtypes.TriggerTargetType; import org.oscm.internal.types.enumtypes.TriggerType; import org.oscm.test.EJBTestBase; import org.oscm.test.data.Marketplaces; import org.oscm.test.data.TechnicalProducts; import org.oscm.test.ejb.TestContainer; import org.oscm.test.stubs.ConfigurationServiceStub; import org.oscm.types.enumtypes.OperationParameterType; public class LocalizedResourceIT extends EJBTestBase { private DataService mgr; @Override protected void setup(TestContainer container) throws Exception { container.login("testuser"); container.addBean(new ConfigurationServiceStub()); container.addBean(new DataServiceBean()); mgr = container.get(DataService.class); } @Test public void testCreate() { LocalizedResource lr = new LocalizedResource(); lr.setLocale("locale"); lr.setObjectKey(1L); lr.setValue("value"); lr.setObjectType(LocalizedObjectTypes.EVENT_DESC); Assert.assertEquals("Wrong key value", 1L, lr.getObjectKey()); Assert.assertEquals("Wrong locale", "locale", lr.getLocale()); Assert.assertEquals("Wrong value", "value", lr.getValue()); Assert.assertEquals("Wrong object type", LocalizedObjectTypes.EVENT_DESC, lr.getObjectType()); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_Event() { Event obj = new Event(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_Organization() { Organization obj = new Organization(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_Marketplace() { Marketplace obj = new Marketplace(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_ParameterDefinition() { ParameterDefinition obj = new ParameterDefinition(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_ParameterOption() { ParameterOption obj = new ParameterOption(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_PaymentType() { PaymentType obj = new PaymentType(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_PriceModel() { PriceModel obj = new PriceModel(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_Product() { Product obj = new Product(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_Report() { Report obj = new Report(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_RoleDefinition() { RoleDefinition obj = new RoleDefinition(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_Subscription() { Subscription obj = new Subscription(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_TechnicalProduct() { TechnicalProduct obj = new TechnicalProduct(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_TechnicalProductOperation() { TechnicalProductOperation obj = new TechnicalProductOperation(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_OperationParameter() { OperationParameter obj = new OperationParameter(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_TriggerProcess() { TriggerProcess obj = new TriggerProcess(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test(expected = UnsupportedOperationException.class) public void unmodifiableList_CatalogEntry() { CatalogEntry obj = new CatalogEntry(); obj.getLocalizedObjectTypes().add(LocalizedObjectTypes.MAIL_CONTENT); } @Test public void removeLocalization_Product() throws Exception { Product product = createProduct(null, true); PriceModel pm = product.getPriceModel(); // remove object without localization remove(product); product = createProduct(null, true); pm = product.getPriceModel(); persistLocalizedResource(product); persistLocalizedResource(pm); // clear to detach the entities clear(); // remove object with localization remove(product); validateLocalizedResources(product, false); validateLocalizedResources(pm, false); } @Test public void removeLocalization_Organization() throws Exception { Organization org = createOrganization(); // remove object without localization remove(org); org = createOrganization(); persistLocalizedResource(org); Marketplace mp1 = createMarketplace(org); persistLocalizedResource(mp1); Marketplace mp2 = createMarketplace(org); persistLocalizedResource(mp2); TechnicalProduct tp1 = createTechnicalProductWithDependentEntities(org); persistLocalizedResource(tp1); TechnicalProduct tp2 = createTechnicalProductWithDependentEntities(org); persistLocalizedResource(tp2); Product prod1 = createProduct(org, true); persistLocalizedResource(prod1); PriceModel pm1 = prod1.getPriceModel(); persistLocalizedResource(pm1); Product prod2 = createProduct(org, true); persistLocalizedResource(prod2); PriceModel pm2 = prod2.getPriceModel(); persistLocalizedResource(pm2); // for subscription not possible, if subscription exists // the product and organization cannot be deleted // clear to detach the entities clear(); // remove object with localization remove(org); validateLocalizedResources(org, false); validateLocalizedResources(mp1, false); validateLocalizedResources(mp2, false); validateLocalizedResources(tp1, false); validateLocalizedResources(tp2, false); validateLocalizedResources(prod1, false); validateLocalizedResources(pm1, false); validateLocalizedResources(prod2, false); validateLocalizedResources(pm2, false); } @Test public void removeLocalization_Event() throws Exception { Event event = createEvent(null); // remove object without localization remove(event); event = createEvent(null); persistLocalizedResource(event); // remove object with localization remove(event); validateLocalizedResources(event, false); } @Test public void removeLocalization_ParameterDefinition() throws Exception { ParameterDefinition pd = createParameterDefinition(null); // remove object without localization remove(pd); pd = createParameterDefinition(null); persistLocalizedResource(pd); // remove object with localization remove(pd); validateLocalizedResources(pd, false); } @Test public void removeLocalization_ParameterOption() throws Exception { ParameterOption po = createParameterOption(null); // remove object without localization remove(po); po = createParameterOption(null); persistLocalizedResource(po); // remove object with localization remove(po); validateLocalizedResources(po, false); } @Test public void removeLocalization_Report() throws Exception { Report report = createReport(); // remove object without localization remove(report); report = createReport(); persistLocalizedResource(report); // remove object with localization remove(report); validateLocalizedResources(report, false); } @Test public void removeLocalization_RoleDefinition() throws Exception { RoleDefinition roledef = createRoleDefinition(); // remove object without localization remove(roledef); roledef = createRoleDefinition(); persistLocalizedResource(roledef); // remove object with localization remove(roledef); validateLocalizedResources(roledef, false); } @Test public void removeLocalization_TriggerProcess() throws Exception { TriggerProcess trigger = createTriggerProcess(null); // remove object without localization remove(trigger); trigger = createTriggerProcess(null); persistLocalizedResource(trigger); // remove object with localization remove(trigger); validateLocalizedResources(trigger, false); } @Test public void removeLocalization_PriceModel() throws Exception { PriceModel pm = createPriceModel(null); // remove object without localization remove(pm); pm = createPriceModel(null); persistLocalizedResource(pm); // remove object with localization remove(pm); validateLocalizedResources(pm, false); } @Test public void removeLocalization_PaymentType() throws Exception { PaymentType pt = createPaymentType(); // remove object without localization remove(pt); pt = createPaymentType(); persistLocalizedResource(pt); // remove object with localization remove(pt); validateLocalizedResources(pt, false); } @Test public void removeLocalization_TechnicalProductOperation() throws Exception { TechnicalProduct tp = createTechnicalProduct(null); TechnicalProductOperation tpo = createTechnicalProductOperation(tp); // remove object without localization remove(tpo); tpo = createTechnicalProductOperation(tp); persistLocalizedResource(tpo); // remove object with localization remove(tpo); validateLocalizedResources(tpo, false); } @Test public void removeLocalization_OperationParameter() throws Exception { TechnicalProductOperation tpo = createTechnicalProductOperation( createTechnicalProduct(null)); OperationParameter op = createOperationParameter(tpo); // remove object without localization remove(op); op = createOperationParameter(tpo); persistLocalizedResource(op); // remove object with localization remove(op); validateLocalizedResources(op, false); } @Test public void removeLocalization_Marketplace() throws Exception { Marketplace mp = createMarketplace(null); // remove object without localization remove(mp); mp = createMarketplace(null); persistLocalizedResource(mp); // remove object with localization remove(mp); validateLocalizedResources(mp, false); } @Test public void removeLocalization_Subscription() throws Exception { Subscription sub = createSubscription(null, null); // remove object without localization remove(sub); sub = createSubscription(null, null); persistLocalizedResource(sub); // remove object with localization remove(sub); validateLocalizedResources(sub, false); } @Test public void removeLocalization_TechnicalProduct() throws Exception { TechnicalProduct tp = createTechnicalProductWithDependentEntities(null); // remove object without localization remove(tp); tp = createTechnicalProductWithDependentEntities(null); persistLocalizedResource(tp); List<Event> events = tp.getEvents(); List<TechnicalProductOperation> tpos = tp .getTechnicalProductOperations(); List<ParameterDefinition> pardefs = tp.getParameterDefinitions(); for (Event e : events) { persistLocalizedResource(e); } for (TechnicalProductOperation tpo : tpos) { persistLocalizedResource(tpo); } for (ParameterDefinition pd : pardefs) { persistLocalizedResource(pd); for (ParameterOption po : pd.getOptionList()) { persistLocalizedResource(po); } } // clear to detach the entities clear(); // remove object with localization remove(tp); validateLocalizedResources(tp, false); for (Event e : events) { validateLocalizedResources(e, false); } for (TechnicalProductOperation tpo : tpos) { validateLocalizedResources(tpo, false); } for (ParameterDefinition pd : pardefs) { validateLocalizedResources(pd, false); for (ParameterOption po : pd.getOptionList()) { validateLocalizedResources(po, false); } } } /** * Tests the remove for domain object without object types for localization. * CatalogEntry is domain object without localization. * * @throws Exception */ @Test public void removeLocalization_CatalogEntry() throws Exception { CatalogEntry catEntry = createCatalogEntry(null); // remove object without localization remove(catEntry); } private void remove(final DomainObject<?> domobj) throws Exception { runTX(new Callable<Void>() { @Override public Void call() throws Exception { mgr.remove(mgr.find(domobj.getClass(), domobj.getKey())); return null; } }); } private void persistLocalizedResource(final DomainObject<?> domobj) throws Exception { runTX(new Callable<Void>() { @Override public Void call() throws Exception { long key = domobj.getKey(); List<LocalizedObjectTypes> ltypes = domobj .getLocalizedObjectTypes(); assertTrue(ltypes.size() > 0); for (LocalizedObjectTypes objectType : ltypes) { LocalizedResource lr; lr = new LocalizedResource("en", key, objectType); lr.setValue("english"); mgr.persist(lr); lr = new LocalizedResource("ge", key, objectType); lr.setValue("german"); mgr.persist(lr); lr = new LocalizedResource("ja", key, objectType); lr.setValue("japanese"); mgr.persist(lr); mgr.flush(); } return null; } }); validateLocalizedResources(domobj, true); } private void validateLocalizedResources(final DomainObject<?> domobj, final boolean existExpected) throws Exception { runTX(new Callable<Void>() { @Override public Void call() throws Exception { long key = domobj.getKey(); for (LocalizedObjectTypes objectType : domobj .getLocalizedObjectTypes()) { LocalizedResource lr; lr = new LocalizedResource("en", key, objectType); if (existExpected) assertNotNull(mgr.find(lr)); else assertNull(mgr.find(lr)); lr = new LocalizedResource("ge", key, objectType); if (existExpected) assertNotNull(mgr.find(lr)); else assertNull(mgr.find(lr)); lr = new LocalizedResource("ja", key, objectType); if (existExpected) assertNotNull(mgr.find(lr)); else assertNull(mgr.find(lr)); } return null; } }); } private Organization createOrganization() throws Exception { Organization org = runTX(new Callable<Organization>() { @Override public Organization call() throws Exception { Organization org = new Organization(); org.setOrganizationId("orgId"); org.setName("organization"); org.setCutOffDay(1); Organization org1 = (Organization) mgr.find(org); if (org1 == null) { mgr.persist(org); } else { org = org1; } return org; } }); return org; } private PriceModel createPriceModel(final Product product) throws Exception { PriceModel priceModel = runTX(new Callable<PriceModel>() { @Override public PriceModel call() throws Exception { PriceModel priceModel = new PriceModel(); priceModel.setType(PriceModelType.FREE_OF_CHARGE); Product prod = product; if (prod == null) { prod = new Product(); prod.setKey(1111110000); } priceModel.setProduct(prod); mgr.persist(priceModel); return priceModel; } }); return priceModel; } private TechnicalProduct createTechnicalProduct(final Organization org) throws Exception { TechnicalProduct tp = runTX(new Callable<TechnicalProduct>() { @Override public TechnicalProduct call() throws Exception { Organization provider = null; if (org != null) { provider = (Organization) mgr.find(org); } if (provider == null) { provider = createOrganization(); } TechnicalProduct tp = new TechnicalProduct(); tp.setBillingIdentifier( BillingAdapterIdentifier.NATIVE_BILLING.toString()); tp.setTechnicalProductId( "technicalproductId" + System.currentTimeMillis()); tp.setOrganization(provider); tp.setProvisioningURL("http://test.com"); TechnicalProduct tp1 = (TechnicalProduct) mgr.find(tp); if (tp1 == null) { mgr.persist(tp); } else { tp = tp1; } return tp; } }); return tp; } private TechnicalProduct createTechnicalProductWithDependentEntities( final Organization org) throws Exception { TechnicalProduct tp = runTX(new Callable<TechnicalProduct>() { @Override public TechnicalProduct call() throws Exception { TechnicalProduct tp = createTechnicalProduct(org); tp = mgr.find(tp.getClass(), tp.getKey()); Event event = createEvent(tp); List<Event> events = new ArrayList<>(); events.add(event); event = createEvent(tp); events.add(event); tp.setEvents(events); ParameterOption po = createParameterOption(tp); List<ParameterDefinition> pds = new ArrayList<>(); pds.add(po.getParameterDefinition()); tp.setParameterDefinitions(pds); TechnicalProductOperation tpo = createTechnicalProductOperation( tp); List<TechnicalProductOperation> tpos = new ArrayList<>(); tpos.add(tpo); tp.setTechnicalProductOperations(tpos); mgr.persist(tp); return tp; } }); return tp; } private Event createEvent(final TechnicalProduct tp) throws Exception { Event event = runTX(new Callable<Event>() { @Override public Event call() throws Exception { TechnicalProduct tp1 = tp; if (tp1 != null) { tp1 = mgr.find(tp.getClass(), tp.getKey()); } Event event = new Event(); event.setEventIdentifier( "eventId" + System.currentTimeMillis()); event.setEventType(EventType.PLATFORM_EVENT); event.setTechnicalProduct(tp1); mgr.persist(event); return event; } }); return event; } private Report createReport() throws Exception { Report report = runTX(new Callable<Report>() { @Override public Report call() throws Exception { OrganizationRole orgrole = new OrganizationRole(); orgrole.setRoleName(OrganizationRoleType.MARKETPLACE_OWNER); OrganizationRole orgrole1 = (OrganizationRole) mgr .find(orgrole); if (orgrole1 == null) { mgr.persist(orgrole); } else { orgrole = orgrole1; } Report report = new Report(); report.setReportName("reportname"); report.setOrganizationRole(orgrole); mgr.persist(report); return report; } }); return report; } private Marketplace createMarketplace(final Organization owner) throws Exception { Marketplace mp = runTX(new Callable<Marketplace>() { @Override public Marketplace call() throws Exception { Organization org = owner; if (org == null) { org = createOrganization(); } else { org = (Organization) mgr.find(org); } return Marketplaces.createMarketplace(org, "MpId" + System.currentTimeMillis(), false, mgr); } }); return mp; } private RoleDefinition createRoleDefinition() throws Exception { RoleDefinition roledef = runTX(new Callable<RoleDefinition>() { @Override public RoleDefinition call() throws Exception { TechnicalProduct tp = createTechnicalProduct(null); RoleDefinition roledef = new RoleDefinition(); roledef.setRoleId("roleId"); roledef.setTechnicalProduct(tp); mgr.persist(roledef); return roledef; } }); return roledef; } private ParameterDefinition createParameterDefinition( final TechnicalProduct tp) throws Exception { ParameterDefinition pd = runTX(new Callable<ParameterDefinition>() { @Override public ParameterDefinition call() throws Exception { TechnicalProduct tp1 = tp; if (tp1 != null) { tp1 = mgr.find(tp.getClass(), tp.getKey()); } ParameterDefinition pd = new ParameterDefinition(); pd.setParameterId("parameterId"); pd.setParameterType(ParameterType.PLATFORM_PARAMETER); pd.setValueType(ParameterValueType.STRING); pd.setTechnicalProduct(tp1); mgr.persist(pd); return pd; } }); return pd; } private ParameterOption createParameterOption(final TechnicalProduct tp) throws Exception { ParameterOption po = runTX(new Callable<ParameterOption>() { @Override public ParameterOption call() throws Exception { ParameterDefinition pd = createParameterDefinition(tp); ParameterOption po = new ParameterOption(); po.setOptionId("optionId"); po.setParameterDefinition(pd); mgr.persist(po); return po; } }); return po; } private TriggerProcess createTriggerProcess(final Organization org) throws Exception { TriggerProcess trigger = runTX(new Callable<TriggerProcess>() { @Override public TriggerProcess call() throws Exception { TriggerDefinition td = new TriggerDefinition(); td.setType(TriggerType.ACTIVATE_SERVICE); td.setTarget("target"); td.setTargetType(TriggerTargetType.WEB_SERVICE); if (org != null) { Organization org1 = (Organization) mgr.find(org); td.setOrganization(org1); } td.setName("testTrigger"); mgr.persist(td); TriggerProcess trigger = new TriggerProcess(); trigger.setState(TriggerProcessStatus.CANCELLED); trigger.setTriggerDefinition(td); mgr.persist(trigger); return trigger; } }); return trigger; } private TechnicalProductOperation createTechnicalProductOperation( final TechnicalProduct tp) throws Exception { TechnicalProductOperation tpo = runTX( new Callable<TechnicalProductOperation>() { @Override public TechnicalProductOperation call() throws Exception { TechnicalProduct tp1 = null; if (tp != null) { tp1 = mgr.find(tp.getClass(), tp.getKey()); } TechnicalProductOperation tpo = new TechnicalProductOperation(); tpo.setOperationId("tpoId"); tpo.setActionUrl("htpp:\\ttt.de"); tpo.setTechnicalProduct(tp1); mgr.persist(tpo); return tpo; } }); return tpo; } private OperationParameter createOperationParameter( final TechnicalProductOperation tpo) throws Exception { OperationParameter result = runTX(new Callable<OperationParameter>() { @Override public OperationParameter call() throws Exception { TechnicalProductOperation read = mgr .getReference(tpo.getClass(), tpo.getKey()); return TechnicalProducts.addOperationParameter(mgr, read, "PARAM1", false, OperationParameterType.INPUT_STRING); } }); return result; } private PaymentType createPaymentType() throws Exception { PaymentType pt = runTX(new Callable<PaymentType>() { @Override public PaymentType call() throws Exception { PSP psp = new PSP(); psp.setIdentifier("pspID"); psp.setWsdlUrl("http:\\ttt.com"); PSP psp1 = (PSP) mgr.find(psp); if (psp1 == null) { mgr.persist(psp); } else { psp = psp1; } PaymentType pt = new PaymentType(); pt.setPaymentTypeId("paymenttypeId"); pt.setCollectionType(PaymentCollectionType.ORGANIZATION); pt.setPsp(psp); mgr.persist(pt); return pt; } }); return pt; } private Product createProduct(final Organization org, final boolean withPriceModel) throws Exception { Product product = runTX(new Callable<Product>() { @Override public Product call() throws Exception { TechnicalProduct tp = createTechnicalProduct(null); Product product = new Product(); product.setProductId( "testproductId" + System.currentTimeMillis()); product.setStatus(ServiceStatus.SUSPENDED); Organization supplier = org; if (supplier == null) { supplier = tp.getOrganization(); } else { supplier = (Organization) mgr.find(supplier); } product.setVendor(supplier); product.setTechnicalProduct(tp); product.setType(ServiceType.TEMPLATE); Product product1 = (Product) mgr.find(product); if (product1 == null) { mgr.persist(product); } else { product = product1; } if (withPriceModel) { PriceModel pm = createPriceModel(product); pm = mgr.find(pm.getClass(), pm.getKey()); product.setPriceModel(pm); mgr.persist(product); } return product; } }); return product; } private Subscription createSubscription(final Product prod, final Organization org) throws Exception { Subscription subscription = runTX(new Callable<Subscription>() { @Override public Subscription call() throws Exception { Product product = prod; Organization owner = org; if (org != null) { owner = (Organization) mgr.find(org); } else { owner = createOrganization(); } if (prod != null) { product = (Product) mgr.find(prod); } else { product = createProduct(null, true); } Subscription subscription = new Subscription(); subscription.setCreationDate(Long.valueOf(16546465000L)); subscription.setStatus(SubscriptionStatus.PENDING); subscription.setSubscriptionId("subscriptionId"); subscription.setOrganization(owner); subscription.setProduct(product); subscription.setCutOffDay(1); mgr.persist(subscription); return subscription; } }); return subscription; } private CatalogEntry createCatalogEntry(final Product prod) throws Exception { CatalogEntry catEntry = runTX(new Callable<CatalogEntry>() { @Override public CatalogEntry call() throws Exception { Product product = prod; if (prod != null) { product = (Product) mgr.find(prod); } else { product = createProduct(null, true); } CatalogEntry catEntry = new CatalogEntry(); catEntry.setProduct(product); mgr.persist(catEntry); return catEntry; } }); return catEntry; } private void clear() throws Exception { runTX(new Callable<Void>() { @Override public Void call() throws Exception { mgr.clear(); return null; } }); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.formatter.java; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; /** * Is intended to hold specific java formatting tests for 'spacing' settings. * * @author Denis Zhdanov * @since Apr 29, 2010 5:50:34 PM */ public class JavaFormatterSpaceTest extends AbstractJavaFormatterTest { public void testSpacingBetweenTypeParameters() { // Implied by IDEADEV-3666 getSettings().SPACE_AFTER_COMMA = true; doTextTest("class Foo {\n" + "Map<String,String> map() {}\n" + "}", "class Foo {\n" + " Map<String, String> map() {\n" + " }\n" + "}"); } @SuppressWarnings("SpellCheckingInspection") public void testDoNotPlaceStatementsOnOneLineIfFirstEndsWithSingleLineComment() { getSettings().KEEP_MULTIPLE_EXPRESSIONS_IN_ONE_LINE = true; getSettings().KEEP_LINE_BREAKS = false; String before = "public class Reproduce {\n" + " public void start() {\n" + " if (true)\n" + " return; // comment\n" + " final int count = 5;\n" + " for (int i = 0; i < count; i++) {\n" + " System.out.println(\"AAA!\");\n" + " System.out.println(\"BBB!\"); // ololol\n" + " System.out.println(\"asda\"); /* ololo */\n" + " System.out.println(\"booo\");\n" + " }\n" + " }\n" + "}"; String after = "public class Reproduce {\n" + " public void start() {\n" + " if (true) return; // comment\n" + " final int count = 5; for (int i = 0; i < count; i++) {\n" + " System.out.println(\"AAA!\"); System.out.println(\"BBB!\"); // ololol\n" + " System.out.println(\"asda\"); /* ololo */ System.out.println(\"booo\");\n" + " }\n" + " }\n" + "}"; doTextTest(before, after); } public void testSpaceBeforeAnnotationParamArray() { // Inspired by IDEA-24329 getSettings().SPACE_BEFORE_ANNOTATION_ARRAY_INITIALIZER_LBRACE = true; String text = "@SuppressWarnings( {\"ALL\"})\n" + "public class FormattingTest {\n" + "}"; // Don't expect the space to be 'ate' doTextTest(text, text); } public void testCommaInTypeArguments() { // Inspired by IDEA-31681 getSettings().SPACE_AFTER_COMMA = false; getSettings().SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS = false; String initial = "interface TestInterface<A,B> {\n" + "\n" + " <X,Y> void foo(X x,Y y);\n" + "}\n" + "\n" + "public class FormattingTest implements TestInterface<String,Integer> {\n" + "\n" + " public <X,Y> void foo(X x,Y y) {\n" + " Map<String,Integer> map = new HashMap<String,Integer>();\n" + " }\n" + "}"; doTextTest(initial, initial); // Don't expect the comma to be inserted getSettings().SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS = true; String formatted = "interface TestInterface<A,B> {\n" + "\n" + " <X,Y> void foo(X x,Y y);\n" + "}\n" + "\n" + "public class FormattingTest implements TestInterface<String, Integer> {\n" + "\n" + " public <X,Y> void foo(X x,Y y) {\n" + " Map<String, Integer> map = new HashMap<String, Integer>();\n" + " }\n" + "}"; doTextTest(initial, formatted); // Expect the comma to be inserted between type arguments } public void testUnaryOperators() { // Inspired by IDEA-52127 getSettings().SPACE_AROUND_UNARY_OPERATOR = false; String initial = "public class FormattingTest {\n" + " public void foo() {\n" + " int i = 1;\n" + " System.out.println(-i);\n" + " System.out.println(+i);\n" + " System.out.println(++i);\n" + " System.out.println(i++);\n" + " System.out.println(--i);\n" + " System.out.println(i--);\n" + " boolean b = true;\n" + " System.out.println(!b);\n" + " }\n" + "}"; doTextTest(initial, initial); // Don't expect spaces to be inserted after unary operators getSettings().SPACE_AROUND_UNARY_OPERATOR = true; String formatted = "public class FormattingTest {\n" + " public void foo() {\n" + " int i = 1;\n" + " System.out.println(- i);\n" + " System.out.println(+ i);\n" + " System.out.println(++ i);\n" + " System.out.println(i++);\n" + " System.out.println(-- i);\n" + " System.out.println(i--);\n" + " boolean b = true;\n" + " System.out.println(! b);\n" + " }\n" + "}"; doTextTest(initial, formatted); // Expect spaces to be inserted after unary operators } public void _testJavadocMethodParams() { // Inspired by IDEA-42167 // Disabled because the contents of the {@code tag} is not necessarily Java code and // therefore it's incorrect to modify it when formatting getSettings().SPACE_AFTER_COMMA = false; String initial = "public class FormattingTest {\n" + " /**\n" + " * This is a convenience method for {@code doTest(test, new Object[0]);}\n" + " */\n" + " void doTest() {\n" + " }\n" + "}"; // Expect single space to left between 'new' and Object[0]. doTextTest(initial, "public class FormattingTest {\n" + " /**\n" + " * This is a convenience method for {@code doTest(test,new Object[0]);}\n" + " */\n" + " void doTest() {\n" + " }\n" + "}"); // Expect space to be inserted between ',' and 'new'. getSettings().SPACE_AFTER_COMMA = true; doTextTest(initial, "public class FormattingTest {\n" + " /**\n" + " * This is a convenience method for {@code doTest(test, new Object[0]);}\n" + " */\n" + " void doTest() {\n" + " }\n" + "}"); // Expect space to be inserted between 'test' and ','. getSettings().SPACE_BEFORE_COMMA = true; doTextTest(initial, "public class FormattingTest {\n" + " /**\n" + " * This is a convenience method for {@code doTest(test , new Object[0]);}\n" + " */\n" + " void doTest() {\n" + " }\n" + "}"); } public void testSpaceWithArrayBrackets() { // Inspired by IDEA-58510 getSettings().SPACE_WITHIN_BRACKETS = true; doMethodTest( "int[] i = new int[1]\n" + "i[0] = 1;\n" + "int[] i2 = new int[]{1}", "int[] i = new int[ 1 ]\n" + "i[ 0 ] = 1;\n" + "int[] i2 = new int[]{1}" ); } public void testSpaceBeforeElse() { // Inspired by IDEA-58068 getSettings().ELSE_ON_NEW_LINE = false; getSettings().SPACE_BEFORE_ELSE_KEYWORD = false; doMethodTest( "if (true) {\n" + "} else {\n" + "}", "if (true) {\n" + "}else {\n" + "}" ); getSettings().SPACE_BEFORE_ELSE_KEYWORD = true; doMethodTest( "if (true) {\n" + "}else {\n" + "}", "if (true) {\n" + "} else {\n" + "}" ); } public void testSpaceBeforeWhile() { // Inspired by IDEA-58068 getSettings().WHILE_ON_NEW_LINE = false; getSettings().SPACE_BEFORE_WHILE_KEYWORD = false; doMethodTest( "do {\n" + "} while (true);", "do {\n" + "}while (true);" ); getSettings().SPACE_BEFORE_WHILE_KEYWORD = true; doMethodTest( "do {\n" + "}while (true);", "do {\n" + "} while (true);" ); } public void testSpaceBeforeCatch() { // Inspired by IDEA-58068 getSettings().CATCH_ON_NEW_LINE = false; getSettings().SPACE_BEFORE_CATCH_KEYWORD = false; doMethodTest( "try {\n" + "} catch (Exception e) {\n" + "}", "try {\n" + "}catch (Exception e) {\n" + "}" ); getSettings().SPACE_BEFORE_CATCH_KEYWORD = true; doMethodTest( "try {\n" + "}catch (Exception e) {\n" + "}", "try {\n" + "} catch (Exception e) {\n" + "}" ); } public void testSpaceBeforeFinally() { // Inspired by IDEA-58068 getSettings().FINALLY_ON_NEW_LINE = false; getSettings().SPACE_BEFORE_FINALLY_KEYWORD = false; doMethodTest( "try {\n" + "} finally {\n" + "}", "try {\n" + "}finally {\n" + "}" ); getSettings().SPACE_BEFORE_FINALLY_KEYWORD = true; doMethodTest( "try {\n" + "}finally {\n" + "}", "try {\n" + "} finally {\n" + "}" ); } public void testEmptyIterationAtFor() { // Inspired by IDEA-58293 getSettings().SPACE_AFTER_SEMICOLON = true; getSettings().SPACE_WITHIN_FOR_PARENTHESES = false; doMethodTest( "for ( ; ; )", "for (; ; )" ); } public void testSpacesInDisjunctiveType() { getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true; getSettings().CATCH_ON_NEW_LINE = false; getSettings().SPACE_AROUND_BITWISE_OPERATORS = true; doMethodTest("try { } catch (E1|E2 e) { }", "try { } catch (E1 | E2 e) { }"); getSettings().SPACE_AROUND_BITWISE_OPERATORS = false; doMethodTest("try { } catch (E1 | E2 e) { }", "try { } catch (E1|E2 e) { }"); } public void testSpacesInsideLambda() { getSettings().KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE = true; getSettings().SPACE_AROUND_LAMBDA_ARROW = true; doMethodTest("()->{}", "() -> {}"); getSettings().SPACE_AROUND_LAMBDA_ARROW = false; doMethodTest("() -> {}", "()->{}"); } public void testSpacesInsideMethodRef() { getSettings().SPACE_AROUND_METHOD_REF_DBL_COLON = true; doMethodTest("Runnable r = this::foo", "Runnable r = this :: foo"); getSettings().SPACE_AROUND_METHOD_REF_DBL_COLON = false; doMethodTest("Runnable r = this::foo", "Runnable r = this::foo"); } public void testSpacesBeforeResourceList() { getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true; getSettings().BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE; getSettings().SPACE_BEFORE_TRY_PARENTHESES = true; getSettings().SPACE_BEFORE_TRY_LBRACE = true; doMethodTest("try(AutoCloseable r = null){ }", "try (AutoCloseable r = null) { }"); getSettings().SPACE_BEFORE_TRY_PARENTHESES = false; getSettings().SPACE_BEFORE_TRY_LBRACE = false; doMethodTest("try (AutoCloseable r = null) { }", "try(AutoCloseable r = null){ }"); } public void testSpacesWithinResourceList() { getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true; getSettings().SPACE_WITHIN_TRY_PARENTHESES = false; doMethodTest("try ( R r = null ) { }", "try (R r = null) { }"); getSettings().SPACE_AFTER_SEMICOLON = false; doMethodTest("try ( R r1 = null ; R r2 = null; ) { }", "try (R r1 = null;R r2 = null;) { }"); getSettings().SPACE_WITHIN_TRY_PARENTHESES = true; doMethodTest("try (R r = null) { }", "try ( R r = null ) { }"); getSettings().SPACE_AFTER_SEMICOLON = true; doMethodTest("try (R r1 = null ; R r2 = null;) { }", "try ( R r1 = null; R r2 = null; ) { }"); } public void testSpacesBetweenResources() { getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true; getSettings().SPACE_BEFORE_SEMICOLON = false; getSettings().SPACE_AFTER_SEMICOLON = true; doMethodTest("try (R r1 = null ; R r2 = null;) { }", "try (R r1 = null; R r2 = null;) { }"); getSettings().SPACE_BEFORE_SEMICOLON = true; getSettings().SPACE_AFTER_SEMICOLON = false; doMethodTest("try (R r1 = null; R r2 = null;) { }", "try (R r1 = null ;R r2 = null ;) { }"); } public void testSpacesInResourceAssignment() { getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true; getSettings().SPACE_AROUND_ASSIGNMENT_OPERATORS = true; doMethodTest("try (R r=null) { }", "try (R r = null) { }"); getSettings().SPACE_AROUND_ASSIGNMENT_OPERATORS = false; doMethodTest("try (R r = null) { }", "try (R r=null) { }"); } public void testBetweenMethodCallArguments() { // Inspired by IDEA-71823 getSettings().SPACE_AFTER_COMMA = false; doMethodTest( "foo(1, 2, 3);", "foo(1,2,3);" ); } public void testBeforeAnonymousClassConstructor() { // Inspired by IDEA-72321. getSettings().SPACE_BEFORE_METHOD_CALL_PARENTHESES = true; doMethodTest( "actions.add(new Action(this) {\n" + " public void run() {\n" + " }\n" + "});", "actions.add (new Action (this) {\n" + " public void run() {\n" + " }\n" + "});" ); } public void testBeforeAnnotationArrayInitializer() { // Inspired by IDEA-72317 getSettings().SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = false; getSettings().SPACE_BEFORE_ANNOTATION_ARRAY_INITIALIZER_LBRACE = true; doClassTest( "@SuppressWarnings({\"HardCodedStringLiteral\"})\n" + "void test() {\n" + " int[] data = new int[] {1, 2, 3};\n" + "}", "@SuppressWarnings( {\"HardCodedStringLiteral\"})\n" + "void test() {\n" + " int[] data = new int[]{1, 2, 3};\n" + "}" ); } public void testBetweenParenthesesOfNoArgsMethod() { // Inspired by IDEA-74751 getSettings().SPACE_WITHIN_METHOD_CALL_PARENTHESES = false; getSettings().SPACE_WITHIN_EMPTY_METHOD_CALL_PARENTHESES = false; getSettings().SPACE_WITHIN_METHOD_PARENTHESES = true; getSettings().SPACE_WITHIN_EMPTY_METHOD_PARENTHESES = true; doClassTest( "void test() {\n" + " foo();\n" + "}", "void test( ) {\n" + " foo();\n" + "}" ); getSettings().SPACE_WITHIN_METHOD_CALL_PARENTHESES = true; getSettings().SPACE_WITHIN_EMPTY_METHOD_CALL_PARENTHESES = true; getSettings().SPACE_WITHIN_METHOD_PARENTHESES = false; getSettings().SPACE_WITHIN_EMPTY_METHOD_PARENTHESES = false; doClassTest( "void test() {\n" + " foo();\n" + "}", "void test() {\n" + " foo( );\n" + "}" ); } public void testIncompleteCastExpression() { // Inspired by IDEA-75043. String text = "void test(int i) {\n" + " (() i)\n" + "}"; doClassTest(text, text); } public void testSpacesWithinAngleBrackets() { getJavaSettings().SPACES_WITHIN_ANGLE_BRACKETS = true; String beforeMethod = "static < T > void fromArray( T [ ] a , Collection< T > c) {\n}"; doClassTest(beforeMethod, "static < T > void fromArray(T[] a, Collection< T > c) {\n}"); String beforeLocal = "Map< String, String > map = new HashMap< String, String >();"; doMethodTest(beforeLocal, "Map< String, String > map = new HashMap< String, String >();"); String beforeClass = "class A < U > {\n}"; doTextTest(beforeClass, "class A< U > {\n}"); getJavaSettings().SPACES_WITHIN_ANGLE_BRACKETS = false; doMethodTest(beforeLocal, "Map<String, String> map = new HashMap<String, String>();"); doClassTest(beforeMethod, "static <T> void fromArray(T[] a, Collection<T> c) {\n}"); doTextTest(beforeClass, "class A<U> {\n}"); } public void testSpaceAfterClosingAngleBracket_InTypeArgument() { String before = "Bar.<String, Integer> mess(null);"; getJavaSettings().SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENT = false; doMethodTest(before, "Bar.<String, Integer>mess(null);"); getJavaSettings().SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENT = true; doMethodTest(before, "Bar.<String, Integer> mess(null);"); } public void testSpaceBeforeOpeningAngleBracket_InTypeParameter() { String before = "class A<T> {\n}"; getJavaSettings().SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETER = false; doTextTest(before, "class A<T> {\n}"); getJavaSettings().SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETER = true; doTextTest(before, "class A <T> {\n}"); } public void testSpaceAroundTypeBounds() { String before = "public class Foo<T extends Bar & Abba, U> {\n}"; getJavaSettings().SPACE_AROUND_TYPE_BOUNDS_IN_TYPE_PARAMETERS = true; doTextTest(before, "public class Foo<T extends Bar & Abba, U> {\n}"); getJavaSettings().SPACE_AROUND_TYPE_BOUNDS_IN_TYPE_PARAMETERS = false; doTextTest(before, "public class Foo<T extends Bar&Abba, U> {\n}"); } public void testInnerTypeAnnotations() { doTextTest( "class C<@TA(1)T> {\n" + " L<@TA(2)A> f = (@TA(3) A) new @TA(4) A() {\n" + " void m(@TA(6) int @TA(7)[] p) {\n" + " }\n" + " };\n" + "}", "class C<@TA(1) T> {\n" + " L<@TA(2) A> f = (@TA(3) A) new @TA(4) A() {\n" + " void m(@TA(6) int @TA(7) [] p) {\n" + " }\n" + " };\n" + "}" ); } public void testClassObjectAccessExpression_BeforeDot() { String before = "Test \n .class"; getSettings().KEEP_LINE_BREAKS = true; doMethodTest(before, "Test\n .class"); getSettings().KEEP_LINE_BREAKS = false; doMethodTest(before, "Test.class"); } public void testClassObjectAccessExpression_AfterDot() { String before = "Test. \n class"; getSettings().KEEP_LINE_BREAKS = true; doMethodTest(before, "Test.\n class"); getSettings().KEEP_LINE_BREAKS = false; doMethodTest(before, "Test.class"); } public void testMultipleFieldDeclaration_InAnonymousClass() { doMethodTest( "new Object() {\n" + "boolean one, two;\n" + "};", "new Object() {\n" + " boolean one, two;\n" + "};" ); } public void testCommentBetweenAnnotationAndModifierList() { getSettings().KEEP_LINE_BREAKS = false; getSettings().KEEP_FIRST_COLUMN_COMMENT = false; doClassTest("@Override\n" + "//FIX me this stupid stuff\n" + "public void run() {\n" + " int a = 2;\n" + "}", "@Override\n" + "//FIX me this stupid stuff\n" + "public void run() {\n" + " int a = 2;\n" + "}"); } public void testSpace_BeforeSemicolon_InsideFor() { getSettings().SPACE_BEFORE_SEMICOLON = true; doMethodTest( "int i = 0;\n" + "for (; i < 10 ; i++) {\n" + "}\n", "int i = 0;\n" + "for ( ; i < 10 ; i++) {\n" + "}\n" ); } public void testSpace_BeforeSemicolon_InsideFor_IfSpacesWithinForIsOn() { getSettings().SPACE_WITHIN_FOR_PARENTHESES = true; doMethodTest( "int i = 0;\n" + "for (; i < 10 ; i++) {\n" + "}\n", "int i = 0;\n" + "for ( ; i < 10; i++ ) {\n" + "}\n" ); } public void testSpaceBeforeTypeArgumentList() { getSettings().SPACE_BEFORE_TYPE_PARAMETER_LIST = true; doMethodTest( "Map<Int, String> map = new HashMap<Int, String>();", "Map <Int, String> map = new HashMap <Int, String>();" ); doMethodTest( "Bar.<Int, String>call();", "Bar. <Int, String>call();" ); } public void testKeepLineBreaksWorks_InsidePolyExpression() { getSettings().KEEP_LINE_BREAKS = false; doMethodTest( "int x = (1 + 2 + 3) *\n" + " (1 + 2 + 2) * (1 + 2);", "int x = (1 + 2 + 3) * (1 + 2 + 2) * (1 + 2);" ); } }
package eu.fbk.knowledgestore.data; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import org.openrdf.model.URI; /** * Merge criteria for combining old and new values of record properties. * <p> * A {@code Criteria} represents (a set of) merge criteria for combining old and new values of * selected record properties. Merge criteria are specified when updating records in the * KnowledgeStore via its API, and can be also used on their own for manipulating records on the * client side. * </p> * <p> * The set of properties a {@code Criteria} object supports may be restricted. Method * {@link #getProperties()} returns this set; the result is empty if the {@code Criteria} object * supports any property. Methods {@link #appliesTo(URI)} and {@link #appliesToAll()} can be * conveniently used for testing whether a specific property or all possible properties are * respectively supported by a given {@code Criteria} object. * </p> * <p> * Merging can be performed at two levels: * </p> * <ul> * <li>on a single property, via method {@link #merge(URI, List, List)} that returns the list * produced by merging old and new values, without modifying its inputs;</li> * <li>over multiple properties in common to a pair of records, via method * {@link #merge(Record, Record)}; this method merges values of any property in common to the old * and new record which is supported by the {@code Criteria}, storing the resulting values in the * old record, which is thus modified in place; if modification of input parameters is not * desired, the caller may clone the old record in advance and supply the clone to the * {@code merge()} method.</li> * </ul> * <p> * The following {@code Criteria} are supported, and can be instantiated based on specific factory * methods: * </p> * <ul> * <li><i>overwrite criteria</i> (factory method {@link #overwrite(URI...)}), consisting in the * discarding of old values which are overwritten with new values (even if new values are the * empty list, which means the affected property is cleared);</li> * <li><i>update criteria</i> (factory method {@link #update(URI...)}), consisting in the * replacement of old values with new ones, but only if the list of new values is not empty * (otherwise, old values are kept);</li> * <li><i>init criteria</i> (factory method {@link #init(URI...)}), consisting in the assignment * of new values only if the list of old values is empty, i.e., the property is initialized to the * supplied of new values if previously unset, otherwise old values are kept;</li> * <li><i>union criteria</i> (factory method {@link #union(URI...)}), consisting in computing and * assigning the union of old and new values, removing duplicates (in which case the new value is * kept, which for nested records means that properties of old nested records are discarded);</li> * <li><i>min criteria</i> (factory method {@link #min(URI...)}), consisting in identifying and * assigning the minimum value among the old and new ones (the comparator returned by * {@link Data#getTotalComparator()} is used);</li> * <li><i>max criteria</i> (factory method {@link #max(URI...)}), consisting in identifying and * assigning the maximum value among the old and new ones (the comparator returned by * {@link Data#getTotalComparator()} is used);</li> * <li><i>composed criteria</i> (factory method {@link #compose(Criteria...)}), consisting in * applying the first matching {@code Criteria} of the specified list to an input property; the * resulting {@code Criteria} will be able to merge the union of all the properties supported by * the composed {@code Criteria}. In case decomposition of a possibly composed {@code Criteria} is * desired, method {@link #decompose()} returns the (recursively) composed elementary * {@code Criteria} for a certain input {@code Criteria} (the input {@code Criteria} is returned * unchanged if not composes).</li> * </ul> * <p> * {@code Criteria} objects are immutable and thus thread safe. Two {@code Criteria} objects are * equal if they implement the same strategy (possibly composed) and support the same properties. * Serialization to string and deserialization back to a {@code Criteria} object are supported, * via methods {@link #toString()}, {@link #toString(Map)} (which accepts a custom namespace map * for encoding properties) and {@link #parse(String, Map)}. The string specification of a * {@code Criteria} has the following form: * {@code criteria1 property11, ..., property1N, ..., criteriaM propertyM1, ... propertyMN} where * commas are all optional, the criteria token is one of {@code overwrite}, {@code update}, * {@code init}, {@code union}, {@code min}, {@code max} (case does not matter) and properties are * encoded according to the Turtle / TriG syntax (full URIs between {@code <} and {@code >} * characters or QNames). * </p> */ public abstract class Criteria implements Serializable { private static final long serialVersionUID = 1L; private final Set<URI> properties; private Criteria(final URI... properties) { this.properties = ImmutableSet.copyOf(properties); } private static Criteria create(final String name, final URI... properties) { if (Overwrite.class.getSimpleName().equalsIgnoreCase(name)) { return overwrite(properties); } else if (Update.class.getSimpleName().equalsIgnoreCase(name)) { return update(properties); } else if (Init.class.getSimpleName().equalsIgnoreCase(name)) { return init(properties); } else if (Min.class.getSimpleName().equalsIgnoreCase(name)) { return min(properties); } else if (Max.class.getSimpleName().equalsIgnoreCase(name)) { return max(properties); } else if (Union.class.getSimpleName().equalsIgnoreCase(name)) { return union(properties); } else { throw new IllegalArgumentException("Unknown criteria name: " + name); } } /** * Parses the supplied string specification of a merge criteria, returning the parsed * {@code Criteria} object. The string must adhere to the format specified in the main Javadoc * comment. * * @param string * the specification of the merge criteria * @param namespaces * the namespace map to be used for parsing the string, null if no mapping should * be used * @return the parsed {@code Criteria}, on success * @throws ParseException * in case the specification string is not valid */ public static Criteria parse(final String string, @Nullable final Map<String, String> namespaces) throws ParseException { Preconditions.checkNotNull(string); final List<Criteria> criteria = Lists.newArrayList(); final List<URI> uris = Lists.newArrayList(); String name = null; try { for (final String token : string.split("[\\s\\,]+")) { if ("*".equals(token)) { criteria.add(create(name, uris.toArray(new URI[uris.size()]))); name = null; uris.clear(); } else if (token.startsWith("<") && token.endsWith(">") // || token.indexOf(':') >= 0) { uris.add((URI) Data.parseValue(token, namespaces)); } else if (name != null || !uris.isEmpty()) { criteria.add(create(name, uris.toArray(new URI[uris.size()]))); name = token; uris.clear(); } else { name = token; } } if (!uris.isEmpty()) { criteria.add(create(name, uris.toArray(new URI[uris.size()]))); } return criteria.size() == 1 ? criteria.get(0) : compose(criteria .toArray(new Criteria[criteria.size()])); } catch (final Exception ex) { throw new ParseException(string, "Invalid criteria string - " + ex.getMessage(), ex); } } /** * Creates a {@code Criteria} object implementing the <i>overwrite</i> merge criteria for the * properties specified. The overwrite criteria always selects the new values of a property, * even if they consist in an empty list that will cause the property to be cleared. * * @param properties * a vararg array with the properties over which the criteria should be applied; if * empty, the criteria will be applied to any property * @return the created {@code Criteria} object */ public static Criteria overwrite(final URI... properties) { return new Overwrite(properties); } /** * Creates a {@code Criteria} object implementing the <i>update</i> merge criteria for the * properties specified. The update criteria assigns the new values to a property only if they * do not consist in the empty list, in which case old values are kept. * * @param properties * a vararg array with the properties over which the criteria should be applied; if * empty, the criteria will be applied to any property * @return the created {@code Criteria} object */ public static Criteria update(final URI... properties) { return new Update(properties); } /** * Creates a {@code Criteria} object implementing the <i>init</i> merge criteria for the * properties specified. The init criteria assignes the new values to a property only if it * has no old value (i.e., old values are the empty list), thus realizing a one-time property * initialization mechanism. * * @param properties * a vararg array with the properties over which the criteria should be applied; if * empty, the criteria will be applied to any property * @return the created {@code Criteria} object */ public static Criteria init(final URI... properties) { return new Init(properties); } /** * Creates a {@code Criteria} object implementing the <i>union</i> merge criteria for the * properties specified. The union criteria assigns the union of old and new values to a * property, discarding duplicates. In case duplicates are two nested records with the same ID * (thus evaluating equal), the new value is kept. * * @param properties * a vararg array with the properties over which the criteria should be applied; if * empty, the criteria will be applied to any property * @return the created {@code Criteria} object */ public static Criteria union(final URI... properties) { return new Union(properties); } /** * Creates a {@code Criteria} object implementing the <i>min</i> merge criteria for the * properties specified. The min criteria assignes the minimum value among the old and new * ones. * * @param properties * a vararg array with the properties over which the criteria should be applied; if * empty, the criteria will be applied to any property * @return the created {@code Criteria} object */ public static Criteria min(final URI... properties) { return new Min(properties); } /** * Creates a {@code Criteria} object implementing the <i>max</i> merge criteria for the * properties specified. The max criteria assignes the maximum value among the old and new * ones. * * @param properties * a vararg array with the properties over which the criteria should be applied; if * empty, the criteria will be applied to any property * @return the created {@code Criteria} object */ public static Criteria max(final URI... properties) { return new Max(properties); } /** * Creates a {@code Criteria} object that composes the {@code Criteria} objects specified in a * <i>composed</i> merge criteria. Given a property whose old and new values have to be * merged, the created composed criteria will scan through the supplied list of * {@code Criteria} using the first matching one. As a consequence, the created criteria will * support all the properties that are supported by at least one of the composed * {@code Criteria}; if one of them supports all the properties, then the composed criteria * will also support all the properties. * * @param criteria * the {@code Criteria} objects to compose * @return the created {@code Criteria} object */ public static Criteria compose(final Criteria... criteria) { Preconditions.checkArgument(criteria.length > 0, "At least a criteria must be supplied"); if (criteria.length == 1) { return criteria[0]; } else { return new Compose(criteria); } } /** * Returns the set of properties supported by this {@code Criteria} object. * * @return a set with the supported properties; if empty, all properties are supported */ public final Set<URI> getProperties() { return this.properties; } /** * Checks whether the property specified is supported by this {@code Criteria} object. * * @param property * the property * @return true, if the property is supported */ public final boolean appliesTo(final URI property) { if (this.properties.isEmpty() || this.properties.contains(property)) { return true; } Preconditions.checkNotNull(property); return false; } /** * Checks whether all properties are supported by this {@code Criteria} object. * * @return true, if all properties are supported, with no restriction */ public final boolean appliesToAll() { return this.properties.isEmpty(); } /** * Merges all supported properties in common to the old and new record specified, storing the * results in the old record. * * @param oldRecord * the record containing old property values, not null; results of the merging * operation are stored in this record, possibly replacing old values of affected * properties (if this behavious is not desired, clone the old record in advance) * @param newRecord * the record containing new property values, not null */ public final void merge(final Record oldRecord, final Record newRecord) { Preconditions.checkNotNull(oldRecord); for (final URI property : newRecord.getProperties()) { if (appliesTo(property)) { oldRecord.set(property, merge(property, oldRecord.get(property), newRecord.get(property))); } } } /** * Merges old and new values of the property specified, returning the resulting list of * values. Input value lists are not affected. In case the property specified is not supported * by this {@code Criteria} object, the old list of values is returned. * * @param property * the property to merge (used to control whether merging should be performed and * which strategy should be adopted in case of a composed {@code Criteria} object) * @param oldValues * a list with the old values of the property, not null * @param newValues * a list with the new values of the property, not null * @return the list of values obtained by applying the merge criteria */ @SuppressWarnings("unchecked") public final List<Object> merge(final URI property, final List<? extends Object> oldValues, final List<? extends Object> newValues) { Preconditions.checkNotNull(oldValues); Preconditions.checkNotNull(newValues); return doMerge(property, (List<Object>) oldValues, (List<Object>) newValues); } List<Object> doMerge(final URI property, final List<Object> oldValues, final List<Object> newValues) { return appliesTo(property) ? doMerge(oldValues, newValues) : oldValues; } List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { return oldValues; } /** * Decomposes this {@code Criteria} object in its elementary (i.e., non-composed) components. * In case this {@code Criteria} object is not composed, it is directly returned by the method * in a singleton list. Otherwise, its components are recursively extracted and returned in a * list that reflects their order of use. * * @return a list of non-composed {@code Criteria} objects, in the same order as they are * applied in this merge criteria object */ public final List<Criteria> decompose() { return doDecompose(); } List<Criteria> doDecompose() { return ImmutableList.of(this); } /** * {@inheritDoc} Two {@code Criteria} objects are equal if they implement the same merge * criteria over the same properties. */ @Override public final boolean equals(final Object object) { if (object == this) { return true; } if (object == null || object.getClass() != this.getClass()) { return false; } final Criteria other = (Criteria) object; return this.properties.equals(other.getProperties()); } /** * {@inheritDoc} The returned hash code reflects the specific criteria and supported * properties of this {@code Criteria} object. */ @Override public final int hashCode() { return this.properties.hashCode(); } /** * Returns a parseable string representation of this {@code Criteria} object, using the * supplied namespace map for encoding property URIs. * * @param namespaces * the namespace map to encode property URIs * @return the produced string */ public final String toString(@Nullable final Map<String, String> namespaces) { final StringBuilder builder = new StringBuilder(); doToString(builder, namespaces); return builder.toString(); } /** * {@inheritDoc} This method returns a parseable string representation of this * {@code Criteria} object, encoding property URIs as full, non-abbreviated URIs. */ @Override public final String toString() { return toString(null); } void doToString(final StringBuilder builder, @Nullable final Map<String, String> namespaces) { builder.append(getClass().getSimpleName().toLowerCase()).append(" "); if (this.properties.isEmpty()) { builder.append("*"); } else { String separator = ""; for (final URI property : this.properties) { builder.append(separator).append(Data.toString(property, namespaces)); separator = ", "; } } } private static final class Overwrite extends Criteria { private static final long serialVersionUID = 1L; Overwrite(final URI... properties) { super(properties); } @Override List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { return newValues; } } private static final class Update extends Criteria { private static final long serialVersionUID = 1L; Update(final URI... properties) { super(properties); } @Override List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { return newValues.isEmpty() ? oldValues : newValues; } } private static final class Init extends Criteria { private static final long serialVersionUID = 1L; Init(final URI... properties) { super(properties); } @Override List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { return oldValues.isEmpty() ? newValues : oldValues; } } private static final class Union extends Criteria { private static final long serialVersionUID = 1L; Union(final URI... properties) { super(properties); } @Override List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { if (oldValues.isEmpty()) { return newValues; } else if (newValues.isEmpty()) { return oldValues; } else { final Set<Object> set = Sets.newLinkedHashSet(); set.addAll(oldValues); set.addAll(newValues); return ImmutableList.copyOf(set); } } } private static final class Min extends Criteria { private static final long serialVersionUID = 1L; Min(final URI... properties) { super(properties); } @Override List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { if (oldValues.isEmpty()) { return newValues.size() <= 1 ? newValues : ImmutableList .of(((Ordering<Object>) Data.getTotalComparator()).min(newValues)); } else if (newValues.isEmpty()) { return oldValues.size() <= 1 ? oldValues : ImmutableList .of(((Ordering<Object>) Data.getTotalComparator()).min(oldValues)); } else { return ImmutableList.of(((Ordering<Object>) Data.getTotalComparator()) .min(Iterables.concat(oldValues, newValues))); } } } private static final class Max extends Criteria { private static final long serialVersionUID = 1L; Max(final URI... properties) { super(properties); } @Override List<Object> doMerge(final List<Object> oldValues, final List<Object> newValues) { if (oldValues.isEmpty()) { return newValues.size() <= 1 ? newValues : ImmutableList .of(((Ordering<Object>) Data.getTotalComparator()).max(newValues)); } else if (newValues.isEmpty()) { return oldValues.size() <= 1 ? oldValues : ImmutableList .of(((Ordering<Object>) Data.getTotalComparator()).max(oldValues)); } else { return ImmutableList.of(((Ordering<Object>) Data.getTotalComparator()) .max(Iterables.concat(oldValues, newValues))); } } } private static final class Compose extends Criteria { private static final long serialVersionUID = 1L; private final Criteria[] specificCriteria; private final Criteria defaultCriteria; Compose(final Criteria... criteria) { super(extractProperties(criteria)); Criteria candidateDefaultCriteria = null; final ImmutableList.Builder<Criteria> builder = ImmutableList.builder(); for (final Criteria c : criteria) { for (final Criteria d : c.decompose()) { if (!d.appliesToAll()) { builder.add(d); } else if (candidateDefaultCriteria == null) { candidateDefaultCriteria = d; } } } this.specificCriteria = Iterables.toArray(builder.build(), Criteria.class); this.defaultCriteria = candidateDefaultCriteria; } @Override List<Object> doMerge(final URI property, final List<Object> oldValues, final List<Object> newValues) { for (final Criteria c : this.specificCriteria) { if (c.appliesTo(property)) { return c.doMerge(oldValues, newValues); } } if (this.defaultCriteria != null) { return this.defaultCriteria.doMerge(oldValues, newValues); } return oldValues; } @Override List<Criteria> doDecompose() { final ImmutableList.Builder<Criteria> builder = ImmutableList.builder(); builder.add(this.specificCriteria); builder.add(this.defaultCriteria); return builder.build(); } @Override void doToString(final StringBuilder builder, // @Nullable final Map<String, String> namespaces) { String separator = ""; for (final Criteria c : this.specificCriteria) { builder.append(separator); c.doToString(builder, namespaces); separator = ", "; } if (this.defaultCriteria != null) { builder.append(separator); this.defaultCriteria.doToString(builder, namespaces); } } private static URI[] extractProperties(final Criteria... criteria) { final List<URI> properties = Lists.newArrayList(); for (final Criteria c : criteria) { properties.addAll(c.properties); } return properties.toArray(new URI[properties.size()]); } } } // alternative API can be: // (1) new Criteria().update(DC.TITLE).override(DC.ISSUED) // - modifiable, verbose if a single option is used // (2) Criteria.builder().update(DC.TITLE).override(DC.ISSUED).build() // - verbose, esp if a single option is used // alternative (2) can be however merged into this implementation, by adding a builder
/* * Copyright (C) 2014, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.vm.choice; import gov.nasa.jpf.Config; import gov.nasa.jpf.JPFException; import gov.nasa.jpf.vm.ChoiceGenerator; import gov.nasa.jpf.vm.ChoiceGeneratorBase; import gov.nasa.jpf.vm.IntChoiceGenerator; import java.util.Arrays; import java.util.Comparator; /** * Choice Generator that enumerates an interval of int values. Pretty simplistic * implementation for now, but at least it can count up and down * * randomizing is handled through RandomOrderIntCG */ public class IntIntervalGenerator extends ChoiceGeneratorBase<Integer> implements IntChoiceGenerator { protected int min, max; protected int next; protected int delta; @Override public void reset () { isDone = false; if (delta == 0) { throw new JPFException("IntIntervalGenerator delta value is 0"); } if (min > max) { int t = max; max = min; min = t; } if (delta > 0) { next = min - delta; } else { next = max - delta; } } /** * don't use this since it is not safe for cascaded ChoiceGenerators * (we need the 'id' to be as context specific as possible) */ @Deprecated public IntIntervalGenerator(int min, int max){ this("?", min, max); } @Deprecated public IntIntervalGenerator(int min, int max, int delta){ this("?", min, max, delta); } public IntIntervalGenerator(String id, int min, int max, int delta) { super(id); this.min = min; this.max = max; this.delta = delta; reset(); } public IntIntervalGenerator(String id, int min, int max) { this(id, min, max, 1); } public IntIntervalGenerator(Config conf, String id) { super(id); min = conf.getInt(id + ".min"); max = conf.getInt(id + ".max"); delta = conf.getInt(id + ".delta", 1); reset(); } @Override public Integer getChoice (int idx){ int nChoices = getTotalNumberOfChoices(); if (idx >= 0 && idx < nChoices){ return min + idx*delta; } else { throw new IllegalArgumentException("choice index out of range: " + idx); } } @Override public Integer getNextChoice () { return new Integer(next); } @Override public boolean hasMoreChoices () { if (isDone) { return false; } else { if (delta > 0) { return (next < max); } else { return (next > min); } } } @Override public void advance () { next += delta; } @Override public int getTotalNumberOfChoices () { return Math.abs((max - min) / delta) + 1; } @Override public int getProcessedNumberOfChoices () { if (delta > 0) { if (next < min){ return 0; } else { return (Math.abs((next - min) / delta) + 1); } } else { if (next > max){ return 0; } else { return (Math.abs((max - next) / delta) + 1); } } } public boolean isAscending(){ return delta > 0; } /** * note this should only be called before the CG is advanced since it resets * the enumeration state */ public void reverse(){ delta = -delta; reset(); } public Integer[] getChoices(){ int n = getTotalNumberOfChoices(); Integer[] vals = new Integer[n]; int v = (delta > 0) ? min : max; for (int i=0; i<n; i++){ vals[i] = v; v += delta; } return vals; } @Override public boolean supportsReordering(){ return true; } @Override public ChoiceGenerator<Integer> reorder (Comparator<Integer> comparator){ Integer[] vals = getChoices(); Arrays.sort(vals, comparator); return new IntChoiceFromList(id, vals); } @Override public String toString () { StringBuilder sb = new StringBuilder(getClass().getName()); sb.append("[id=\""); sb.append(id); sb.append('"'); sb.append(",isCascaded:"); sb.append(isCascaded); sb.append(","); sb.append(min); sb.append(".."); sb.append(max); sb.append(",delta="); if (delta > 0) { sb.append('+'); } sb.append(delta); sb.append(",cur="); sb.append(getNextChoice()); sb.append(']'); return sb.toString(); } @Override public Class<Integer> getChoiceType() { return Integer.class; } @Override public ChoiceGenerator<Integer> randomize() { return new RandomOrderIntCG(this); } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.client; import java.util.Map; import java.util.function.Function; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.test.publisher.PublisherProbe; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * Tests for {@link AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager}. * * @author Ankur Pathak * @author Phil Clay */ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests { private ReactiveClientRegistrationRepository clientRegistrationRepository; private ReactiveOAuth2AuthorizedClientService authorizedClientService; private ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider; private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper; private AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager; private ClientRegistration clientRegistration; private Authentication principal; private OAuth2AuthorizedClient authorizedClient; private ArgumentCaptor<OAuth2AuthorizationContext> authorizationContextCaptor; private PublisherProbe<Void> saveAuthorizedClientProbe; private PublisherProbe<Void> removeAuthorizedClientProbe; @SuppressWarnings("unchecked") @Before public void setup() { this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class); this.authorizedClientService = mock(ReactiveOAuth2AuthorizedClientService.class); this.saveAuthorizedClientProbe = PublisherProbe.empty(); given(this.authorizedClientService.saveAuthorizedClient(any(), any())) .willReturn(this.saveAuthorizedClientProbe.mono()); this.removeAuthorizedClientProbe = PublisherProbe.empty(); given(this.authorizedClientService.removeAuthorizedClient(any(), any())) .willReturn(this.removeAuthorizedClientProbe.mono()); this.authorizedClientProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class); this.contextAttributesMapper = mock(Function.class); given(this.contextAttributesMapper.apply(any())).willReturn(Mono.empty()); this.authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientService); this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider); this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper); this.clientRegistration = TestClientRegistrations.clientRegistration().build(); this.principal = new TestingAuthenticationToken("principal", "password"); this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken()); this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class); } @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null, this.authorizedClientService)) .withMessage("clientRegistrationRepository cannot be null"); } @Test public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( this.clientRegistrationRepository, null)) .withMessage("authorizedClientService cannot be null"); } @Test public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) .withMessage("authorizedClientProvider cannot be null"); } @Test public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) .withMessage("contextAttributesMapper cannot be null"); } @Test public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) .withMessage("authorizationSuccessHandler cannot be null"); } @Test public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) .withMessage("authorizationFailureHandler cannot be null"); } @Test public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null)) .withMessage("authorizeRequest cannot be null"); } @Test public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() { String clientRegistrationId = "invalid-registration-id"; OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId) .principal(this.principal).build(); given(this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(Mono.empty()); StepVerifier.create(this.authorizedClientManager.authorize(authorizeRequest)) .verifyError(IllegalArgumentException.class); } @SuppressWarnings("unchecked") @Test public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); given(this.authorizedClientProvider.authorize(any())).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); StepVerifier.create(authorizedClient).verifyComplete(); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class), eq(this.principal)); } @SuppressWarnings("unchecked") @Test public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.just(this.authorizedClient)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) .build(); Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete(); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService).saveAuthorizedClient(eq(this.authorizedClient), eq(this.principal)); this.saveAuthorizedClientProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); } @SuppressWarnings("unchecked") @Test public void authorizeWhenNotAuthorizedAndSupportedProviderAndCustomSuccessHandlerThenInvokeCustomSuccessHandler() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.just(this.authorizedClient)); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on PublisherProbe<Void> authorizationSuccessHandlerProbe = PublisherProbe.empty(); this.authorizedClientManager.setAuthorizationSuccessHandler( (client, principal, attributes) -> authorizationSuccessHandlerProbe.mono()); Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete(); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); authorizationSuccessHandlerProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any()); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); } @Test public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on ClientAuthorizationException exception = new ClientAuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null), this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); assertThatExceptionOfType(ClientAuthorizationException.class) .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), eq(this.principal.getName())); this.removeAuthorizedClientProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any()); } @Test public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on ClientAuthorizationException exception = new ClientAuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null), this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); assertThatExceptionOfType(ClientAuthorizationException.class) .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), eq(this.principal.getName())); this.removeAuthorizedClientProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any()); } @Test public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on ClientAuthorizationException exception = new ClientAuthorizationException( new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null), this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); assertThatExceptionOfType(ClientAuthorizationException.class) .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any()); } @Test public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on OAuth2AuthorizationException exception = new OAuth2AuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null)); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); assertThatExceptionOfType(OAuth2AuthorizationException.class) .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any()); } @Test public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()) .principal(this.principal) .build(); // @formatter:on OAuth2AuthorizationException exception = new OAuth2AuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null)); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty(); this.authorizedClientManager.setAuthorizationFailureHandler( (client, principal, attributes) -> authorizationFailureHandlerProbe.mono()); assertThatExceptionOfType(OAuth2AuthorizationException.class) .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isNull(); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); authorizationFailureHandlerProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any()); } @SuppressWarnings("unchecked") @Test public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() { given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) .willReturn(Mono.just(this.clientRegistration)); given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), eq(this.principal.getName()))).willReturn(Mono.just(this.authorizedClient)); OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.just(reauthorizedClient)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) .build(); Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); // @formatter:off StepVerifier.create(authorizedClient) .expectNext(reauthorizedClient) .verifyComplete(); // @formatter:on verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal)); this.saveAuthorizedClientProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); } @SuppressWarnings("unchecked") @Test public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() { given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.empty()); // @formatter:off OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient) .principal(this.principal) .build(); // @formatter:on Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest); StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete(); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class), eq(this.principal)); } @SuppressWarnings("unchecked") @Test public void reauthorizeWhenSupportedProviderThenReauthorized() { OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.just(reauthorizedClient)); // @formatter:off OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient) .principal(this.principal) .build(); // @formatter:on Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest); StepVerifier.create(authorizedClient).expectNext(reauthorizedClient).verifyComplete(); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal)); this.saveAuthorizedClientProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); } @SuppressWarnings("unchecked") @Test public void reauthorizeWhenRequestAttributeScopeThenMappedToContext() { OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.just(reauthorizedClient)); OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient) .principal(this.principal).attribute(OAuth2ParameterNames.SCOPE, "read write").build(); this.authorizedClientManager.setContextAttributesMapper( new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.DefaultContextAttributesMapper()); Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest); // @formatter:off StepVerifier.create(authorizedClient) .expectNext(reauthorizedClient) .verifyComplete(); // @formatter:on verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal)); this.saveAuthorizedClientProbe.assertWasSubscribed(); verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any()); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient); assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal); assertThat(authorizationContext.getAttributes()) .containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME); String[] requestScopeAttribute = authorizationContext .getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME); assertThat(requestScopeAttribute).contains("read", "write"); } }
/*========================================================================= * Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved. * This product is protected by U.S. and international copyright * and intellectual property laws. Pivotal products are covered by * more patents listed at http://www.pivotal.io/patents. *========================================================================= */ package com.gemstone.gemfire.internal.sequencelog; import java.util.UUID; import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; import com.gemstone.gemfire.internal.cache.CachedDeserializable; import com.gemstone.gemfire.internal.cache.DiskEntry.RecoveredEntry; import com.gemstone.gemfire.internal.cache.EntryEventImpl; import com.gemstone.gemfire.internal.cache.LocalRegion; import com.gemstone.gemfire.internal.cache.PlaceHolderDiskRegion; import com.gemstone.gemfire.internal.cache.Token; import com.gemstone.gemfire.internal.cache.persistence.DiskStoreID; import com.gemstone.gemfire.internal.offheap.StoredObject; import com.gemstone.gemfire.internal.offheap.annotations.Unretained; /** * A wrapper around the graph logger that logs entry level events. * @author dsmith * * *TODO * - I think I need some options to choose to deserialize a key to record states. */ public class EntryLogger { private static final SequenceLogger GRAPH_LOGGER = SequenceLoggerImpl.getInstance(); private static ThreadLocal<String> SOURCE = new ThreadLocal<String>(); private static ThreadLocal<String> SOURCE_TYPE = new ThreadLocal<String>(); public static final String TRACK_VALUES_PROPERTY = "gemfire.EntryLogger.TRACK_VALUES"; private static final boolean TRACK_VALUES = Boolean.getBoolean(TRACK_VALUES_PROPERTY); public static void clearSource() { if(isEnabled()) { SOURCE.set(null); SOURCE_TYPE.set(null); } } public static void setSource(Object source, String sourceType) { if(isEnabled()) { SOURCE.set(source.toString()); SOURCE_TYPE.set(sourceType); } } public static void logPut(EntryEventImpl event) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphName(event), getEdgeName("put"), processValue(event.getRawNewValue()), getSource(), getDest()); } } private static String getEdgeName(String transition) { String sourceType = SOURCE_TYPE.get(); if(sourceType == null) { sourceType = ""; } else { sourceType = sourceType + " "; } return sourceType + transition; } public static void logInvalidate(EntryEventImpl event) { if(isEnabled()) { final String invalidationType = event.getOperation().isLocal() ? "local_invalid" : "invalid"; GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphName(event), getEdgeName("invalidate"), invalidationType, getSource(), getDest()); } } public static void logDestroy(EntryEventImpl event) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphName(event), getEdgeName("destroy"), "destroyed", getSource(), getDest()); } } public static void logRecovery(Object owner, Object key, RecoveredEntry value) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphNameFromOwner(owner, key), "recovery", processValue(value.getValue()), getSource(), getDest()); } } public static void logPersistPut(String name, Object key, DiskStoreID diskStoreID) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphName(name, key), "persist", "persisted", getDest(), diskStoreID); } } public static void logPersistDestroy(String name, Object key, DiskStoreID diskStoreID) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphName(name, key), "persist_destroy", "destroy", getDest(), diskStoreID); } } public static void logInitialImagePut(Object owner, Object key, Object newValue) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphNameFromOwner(owner, key), "GII", processValue(newValue), getSource(), getDest()); } } public static void logTXDestroy(Object owner, Object key) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphNameFromOwner(owner, key), getEdgeName("txdestroy"), "destroyed", getSource(), getDest()); } } public static void logTXInvalidate(Object owner, Object key) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphNameFromOwner(owner, key), getEdgeName("txinvalidate"), "invalid", getSource(), getDest()); } } public static void logTXPut(Object owner, Object key, Object nv) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphNameFromOwner(owner, key), getEdgeName("txput"), processValue(nv), getSource(), getDest()); } } public static boolean isEnabled() { return GRAPH_LOGGER.isEnabled(GraphType.KEY); } private static Object getDest() { return InternalDistributedSystem.getAnyInstance().getMemberId(); } private static Object getSource() { Object source = SOURCE.get(); if(source == null) { source = InternalDistributedSystem.getAnyInstance().getMemberId(); } return source; } private static Object processValue(@Unretained Object rawNewValue) { if(rawNewValue != null && Token.isInvalid(rawNewValue)) { return "invalid"; } if(!TRACK_VALUES) { return "present"; } if (rawNewValue instanceof StoredObject) { return "off-heap"; } if(rawNewValue instanceof CachedDeserializable) { rawNewValue = ((CachedDeserializable) rawNewValue).getDeserializedForReading(); } if(rawNewValue instanceof byte[]) { return "serialized:" + hash((byte[])rawNewValue); } return rawNewValue; } private static Object hash(byte[] rawNewValue) { int hash = 17; int length = rawNewValue.length; if(length > 100) { length = 100; } for(int i =0; i < length; i++) { hash = 31 * hash + rawNewValue[i]; } return Integer.valueOf(hash); } private static String getGraphName(EntryEventImpl event) { return getGraphName(event.getRegion().getFullPath(), event.getKey()); } private static String getGraphNameFromOwner(Object owner, Object key) { String ownerName; if(owner instanceof LocalRegion) { ownerName = ((LocalRegion) owner).getFullPath(); } else if (owner instanceof PlaceHolderDiskRegion) { ownerName = ((PlaceHolderDiskRegion) owner).getName(); } else { ownerName = owner.toString(); } return getGraphName(ownerName, key); } private static String getGraphName(String ownerName, Object key) { return ownerName + ":" + key; } public static void logUpdateEntryVersion(EntryEventImpl event) { if(isEnabled()) { GRAPH_LOGGER.logTransition(GraphType.KEY, getGraphName(event), getEdgeName("update-version"), "version-updated", getSource(), getDest()); } } }
// Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package org.pantsbuild.tools.junit.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Closeables; import com.google.common.io.Files; import org.apache.commons.io.output.TeeOutputStream; import org.junit.runner.Computer; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runners.model.InitializationError; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.kohsuke.args4j.spi.StringArrayOptionHandler; import org.pantsbuild.args4j.InvalidCmdLineArgumentException; import org.pantsbuild.tools.junit.withretry.AllDefaultPossibilitiesBuilderWithRetry; /** * An alternative to {@link JUnitCore} with stream capture and junit-report xml output capabilities. */ public class ConsoleRunnerImpl { private static final SwappableStream<PrintStream> SWAPPABLE_OUT = new SwappableStream<PrintStream>(System.out); private static final SwappableStream<PrintStream> SWAPPABLE_ERR = new SwappableStream<PrintStream>(System.err); /** Should be set to false for unit testing via {@link #setCallSystemExitOnFinish} */ private static boolean callSystemExitOnFinish = true; /** Intended to be used in unit testing this class */ private static int exitStatus; /** * A stream that allows its underlying output to be swapped. */ static class SwappableStream<T extends OutputStream> extends FilterOutputStream { private final T original; SwappableStream(T out) { super(out); this.original = out; } OutputStream swap(OutputStream out) { OutputStream old = this.out; this.out = out; return old; } /** * Returns the original stream this swappable stream was created with. */ public T getOriginal() { return original; } } /** * Captures a tests stderr and stdout streams, restoring the previous streams on {@link #close()}. */ static class StreamCapture { private final File out; private OutputStream outstream; private final File err; private OutputStream errstream; /** * If true capture stdout and stderr to original System.out and System.err * as well as to out and err files. **/ private final boolean printToOriginalOutputs; private int useCount; private boolean closed; StreamCapture(File out, File err, boolean printToOriginalOutputs) throws IOException { this.out = out; this.err = err; this.printToOriginalOutputs = printToOriginalOutputs; } void incrementUseCount() { this.useCount++; } void open() throws FileNotFoundException { if (outstream == null) { outstream = new FileOutputStream(out); } if (errstream == null) { errstream = new FileOutputStream(err); } if (printToOriginalOutputs) { SWAPPABLE_OUT.swap(new TeeOutputStream(SWAPPABLE_OUT.getOriginal(), outstream)); SWAPPABLE_ERR.swap(new TeeOutputStream(SWAPPABLE_ERR.getOriginal(), errstream)); } else { SWAPPABLE_OUT.swap(outstream); SWAPPABLE_ERR.swap(errstream); } } void close() throws IOException { if (--useCount <= 0 && !closed) { if (outstream != null) { Closeables.close(outstream, /* swallowIOException */ true); } if (errstream != null) { Closeables.close(errstream, /* swallowIOException */ true); } closed = true; } } void dispose() throws IOException { useCount = 0; close(); } byte[] readOut() throws IOException { return read(out); } byte[] readErr() throws IOException { return read(err); } private byte[] read(File file) throws IOException { Preconditions.checkState(closed, "Capture must be closed by all users before it can be read"); return Files.toByteArray(file); } } /** * A run listener that captures the output and error streams for each test class and makes the * content of these available. */ static class StreamCapturingListener extends ForwardingListener implements StreamSource { private final Map<Class<?>, StreamCapture> captures = Maps.newHashMap(); private final File outdir; private final boolean printToOriginalOutputs; StreamCapturingListener(File outdir, boolean printToOriginalOutputs) { this.outdir = outdir; this.printToOriginalOutputs = printToOriginalOutputs; } @Override public void testRunStarted(Description description) throws Exception { registerTests(description.getChildren()); super.testRunStarted(description); } private void registerTests(Iterable<Description> tests) throws IOException { for (Description test : tests) { registerTests(test.getChildren()); if (Util.isRunnable(test)) { StreamCapture capture = captures.get(test.getTestClass()); if (capture == null) { String prefix = test.getClassName(); File out = new File(outdir, prefix + ".out.txt"); Files.createParentDirs(out); File err = new File(outdir, prefix + ".err.txt"); Files.createParentDirs(err); capture = new StreamCapture(out, err, printToOriginalOutputs); captures.put(test.getTestClass(), capture); } capture.incrementUseCount(); } } } @Override public void testRunFinished(Result result) throws Exception { for (StreamCapture capture : captures.values()) { capture.dispose(); } super.testRunFinished(result); } @Override public void testStarted(Description description) throws Exception { captures.get(description.getTestClass()).open(); super.testStarted(description); } @Override public void testFinished(Description description) throws Exception { captures.get(description.getTestClass()).close(); super.testFinished(description); } @Override public byte[] readOut(Class<?> testClass) throws IOException { return captures.get(testClass).readOut(); } @Override public byte[] readErr(Class<?> testClass) throws IOException { return captures.get(testClass).readErr(); } } private static final Pattern METHOD_PARSER = Pattern.compile("^([^#]+)#([^#]+)$"); private final boolean failFast; private final boolean suppressOutput; private final boolean xmlReport; private final File outdir; private final boolean perTestTimer; private final boolean defaultParallel; private final int parallelThreads; private final int testShard; private final int numTestShards; private final int numRetries; ConsoleRunnerImpl( boolean failFast, boolean suppressOutput, boolean xmlReport, boolean perTestTimer, File outdir, boolean defaultParallel, int parallelThreads, int testShard, int numTestShards, int numRetries) { this.failFast = failFast; this.suppressOutput = suppressOutput; this.xmlReport = xmlReport; this.perTestTimer = perTestTimer; this.outdir = outdir; this.defaultParallel = defaultParallel; this.parallelThreads = parallelThreads; this.testShard = testShard; this.numTestShards = numTestShards; this.numRetries = numRetries; } void run(Iterable<String> tests) { System.setOut(new PrintStream(SWAPPABLE_OUT)); System.setErr(new PrintStream(SWAPPABLE_ERR)); List<Request> requests = parseRequests(SWAPPABLE_OUT.getOriginal(), SWAPPABLE_ERR.getOriginal(), tests); if (numTestShards > 0) { requests = setFilterForTestShard(requests); } JUnitCore core = new JUnitCore(); final AbortableListener abortableListener = new AbortableListener(failFast) { @Override protected void abort(Result failureResult) { exit(failureResult.getFailureCount()); } }; core.addListener(abortableListener); if (xmlReport) { if (!outdir.exists()) { if (!outdir.mkdirs()) { throw new IllegalStateException("Failed to create output directory: " + outdir); } } StreamCapturingListener streamCapturingListener = new StreamCapturingListener(outdir, !suppressOutput); abortableListener.addListener(streamCapturingListener); AntJunitXmlReportListener xmlReportListener = new AntJunitXmlReportListener(outdir, streamCapturingListener); abortableListener.addListener(xmlReportListener); } // TODO: Register all listeners to core instead of to abortableListener because // abortableListener gets removed when one of the listener throws exceptions in // RunNotifier.java. Other listeners should not get removed. if (perTestTimer) { abortableListener.addListener(new PerTestConsoleListener(SWAPPABLE_OUT.getOriginal())); } else { core.addListener(new ConsoleListener(SWAPPABLE_OUT.getOriginal())); } // Wrap test execution with registration of a shutdown hook that will ensure we // never exit silently if the VM does. final Thread abnormalExitHook = createAbnormalExitHook(abortableListener, SWAPPABLE_OUT.getOriginal()); Runtime.getRuntime().addShutdownHook(abnormalExitHook); int failures = 0; try { if (this.parallelThreads > 1) { ConcurrentCompositeRequest request = new ConcurrentCompositeRequest( requests, this.defaultParallel, this.parallelThreads); failures = core.run(request).getFailureCount(); } else { for (Request request : requests) { Result result = core.run(request); failures += result.getFailureCount(); } } } catch (InitializationError initializationError) { failures = 1; } finally { // If we're exiting via a thrown exception, we'll get a better message by letting it // propagate than by halt()ing. Runtime.getRuntime().removeShutdownHook(abnormalExitHook); } exit(failures); } /** * Returns a thread that records a system exit to the listener, and then halts(1). */ private Thread createAbnormalExitHook(final AbortableListener listener, final PrintStream out) { Thread abnormalExitHook = new Thread() { @Override public void run() { try { listener.abort(new UnknownError("Abnormal VM exit - test crashed.")); // We want to trap and log no matter why abort failed for a better end user message. // SUPPRESS CHECKSTYLE RegexpSinglelineJava } catch (Exception e) { out.println(e); e.printStackTrace(out); } // This error might be a call to `System.exit(0)`, which we definitely do // not want to go unnoticed. out.println("FATAL: VM exiting uncleanly."); out.flush(); Runtime.getRuntime().halt(1); } }; return abnormalExitHook; } private List<Request> parseRequests(PrintStream out, PrintStream err, Iterable<String> specs) { /** * Datatype representing an individual test method. */ class TestMethod { private final Class<?> clazz; private final String name; TestMethod(Class<?> clazz, String name) { this.clazz = clazz; this.name = name; } } Set<TestMethod> testMethods = Sets.newLinkedHashSet(); Set<Class<?>> classes = Sets.newLinkedHashSet(); for (String spec : specs) { Matcher matcher = METHOD_PARSER.matcher(spec); try { if (matcher.matches()) { Class<?> testClass = loadClass(matcher.group(1)); if (isTest(testClass)) { String method = matcher.group(2); testMethods.add(new TestMethod(testClass, method)); } } else { Class<?> testClass = loadClass(spec); if (isTest(testClass)) { classes.add(testClass); } } } catch (NoClassDefFoundError e) { notFoundError(spec, out, e); } catch (ClassNotFoundException e) { notFoundError(spec, out, e); } catch (LinkageError e) { // Any of a number of runtime linking errors can occur when trying to load a class, // fail with the test spec so the class failing to link is known. notFoundError(spec, out, e); // See the comment below for justification. // SUPPRESS CHECKSTYLE RegexpSinglelineJava } catch (RuntimeException e) { // The class may fail with some variant of RTE in its static initializers, trap these // and dump the bad spec in question to help narrow down issue. notFoundError(spec, out, e); } } List<Request> requests = Lists.newArrayList(); if (!classes.isEmpty()) { if (this.perTestTimer || this.parallelThreads > 1) { for (Class<?> clazz : classes) { requests.add(new AnnotatedClassRequest(clazz, numRetries, err)); } } else { // The code below does what the original call // requests.add(Request.classes(classes.toArray(new Class<?>[classes.size()]))); // does, except that it instantiates our own builder, needed to support retries try { AllDefaultPossibilitiesBuilderWithRetry builder = new AllDefaultPossibilitiesBuilderWithRetry(numRetries, err); Runner suite = new Computer().getSuite( builder, classes.toArray(new Class<?>[classes.size()])); requests.add(Request.runner(suite)); } catch (InitializationError e) { throw new RuntimeException( "Internal error: Suite constructor, called as above, should always complete"); } } } for (TestMethod testMethod : testMethods) { requests.add(new AnnotatedClassRequest(testMethod.clazz, numRetries, err) .filterWith(Description.createTestDescription(testMethod.clazz, testMethod.name))); } return requests; } // Loads classes without initializing them. We just need the type, annotations and method // signatures, none of which requires initialization. private Class<?> loadClass(String name) throws ClassNotFoundException { return Class.forName(name, /* initialize = */ false, getClass().getClassLoader()); } /** * Using JUnit4 test filtering mechanism, replaces the provided list of requests with * the one where each request has a filter attached. The filters are used to run only * one test shard, i.e. every Mth test out of N (testShard and numTestShards fields). */ private List<Request> setFilterForTestShard(List<Request> requests) { // The filter below can be called multiple times for the same test, at least // when parallelThreads is true. To maintain the stable "run - not run" test status, // we determine it once, when the test is seen for the first time (always in serial // order), and save it in testToRunStatus table. class TestFilter extends Filter { private int testIdx; private HashMap<String, Boolean> testToRunStatus = new HashMap<String, Boolean>(); @Override public boolean shouldRun(Description desc) { if (desc.isSuite()) { return true; } String descString = Util.getPantsFriendlyDisplayName(desc); // Note that currently even when parallelThreads is true, the first time this // is called in serial order, by our own iterator below. synchronized (this) { Boolean shouldRun = testToRunStatus.get(descString); if (shouldRun != null) { return shouldRun; } else { shouldRun = testIdx % numTestShards == testShard; testIdx++; testToRunStatus.put(descString, shouldRun); return shouldRun; } } } @Override public String describe() { return "Filters a static subset of test methods"; } } class AlphabeticComparator implements Comparator<Description> { @Override public int compare(Description o1, Description o2) { return Util.getPantsFriendlyDisplayName(o1).compareTo(Util.getPantsFriendlyDisplayName(o2)); } } TestFilter testFilter = new TestFilter(); AlphabeticComparator alphaComp = new AlphabeticComparator(); ArrayList<Request> filteredRequests = new ArrayList<Request>(requests.size()); for (Request request: requests) { filteredRequests.add(request.sortWith(alphaComp).filterWith(testFilter)); } // This will iterate over all of the test serially, calling shouldRun() above. // It's needed to guarantee stable sharding in all situations. for (Request request: filteredRequests) { request.getRunner().getDescription(); } return filteredRequests; } private void notFoundError(String spec, PrintStream out, Throwable t) { out.printf("FATAL: Error during test discovery for %s: %s\n", spec, t); throw new RuntimeException("Classloading error during test discovery for " + spec, t); } /** * Launcher for JUnitConsoleRunner. * * @param args options from the command line */ public static void main(String[] args) { /** * Command line option bean. */ class Options { @Option(name = "-fail-fast", usage = "Causes the test suite run to fail fast.") private boolean failFast; @Option(name = "-suppress-output", usage = "Suppresses test output.") private boolean suppressOutput; @Option(name = "-xmlreport", usage = "Create ant compatible junit xml report files in -outdir.") private boolean xmlReport; @Option(name = "-outdir", usage = "Directory to output test captures too. Only used if -suppress-output or " + "-xmlreport is set.") private File outdir = new File(System.getProperty("java.io.tmpdir")); @Option(name = "-per-test-timer", usage = "Show a description of each test and timer for each test class.") private boolean perTestTimer; @Option(name = "-default-parallel", usage = "Whether to run test classes without @TestParallel or @TestSerial in parallel.") private boolean defaultParallel; private int parallelThreads = 0; @Option(name = "-parallel-threads", usage = "Number of threads to execute tests in parallel. Must be positive, " + "or 0 to set automatically.") public void setParallelThreads(int parallelThreads) { if (parallelThreads < 0) { throw new InvalidCmdLineArgumentException( "-parallel-threads", parallelThreads, "-parallel-threads cannot be negative"); } this.parallelThreads = parallelThreads; if (parallelThreads == 0) { int availableProcessors = Runtime.getRuntime().availableProcessors(); this.parallelThreads = availableProcessors; System.err.printf("Auto-detected %d processors, using -parallel-threads=%d\n", availableProcessors, this.parallelThreads); } } private int testShard; private int numTestShards; @Option(name = "-test-shard", usage = "Subset of tests to run, in the form M/N, 0 <= M < N. For example, 1/3 means " + "run tests number 2, 5, 8, 11, ...") public void setTestShard(String shard) { String errorMsg = "-test-shard should be in the form M/N"; int slashIdx = shard.indexOf('/'); if (slashIdx < 0) { throw new InvalidCmdLineArgumentException("-test-shard", shard, errorMsg); } try { this.testShard = Integer.parseInt(shard.substring(0, slashIdx)); this.numTestShards = Integer.parseInt(shard.substring(slashIdx + 1)); } catch (NumberFormatException ex) { throw new InvalidCmdLineArgumentException("-test-shard", shard, errorMsg); } if (testShard < 0 || numTestShards <= 0 || testShard >= numTestShards) { throw new InvalidCmdLineArgumentException( "-test-shard", shard, "0 <= M < N is required in -test-shard M/N"); } } private int numRetries; @Option(name = "-num-retries", usage = "Number of attempts to retry each failing test, 0 by default") public void setNumRetries(int numRetries) { if (numRetries < 0) { throw new InvalidCmdLineArgumentException( "-num-retries", numRetries, "-num-retries cannot be negative"); } this.numRetries = numRetries; } @Argument(usage = "Names of junit test classes or test methods to run. Names prefixed " + "with @ are considered arg file paths and these will be loaded and the " + "whitespace delimited arguments found inside added to the list", required = true, metaVar = "TESTS", handler = StringArrayOptionHandler.class) private String[] tests = {}; } Options options = new Options(); CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { parser.printUsage(System.err); exit(1); } catch (InvalidCmdLineArgumentException e) { parser.printUsage(System.err); exit(1); } ConsoleRunnerImpl runner = new ConsoleRunnerImpl(options.failFast, options.suppressOutput, options.xmlReport, options.perTestTimer, options.outdir, options.defaultParallel, options.parallelThreads, options.testShard, options.numTestShards, options.numRetries); List<String> tests = Lists.newArrayList(); for (String test : options.tests) { if (test.startsWith("@")) { try { String argFileContents = Files.toString(new File(test.substring(1)), Charsets.UTF_8); tests.addAll(Arrays.asList(argFileContents.split("\\s+"))); } catch (IOException e) { System.err.printf("Failed to load args from arg file %s: %s\n", test, e.getMessage()); exit(1); } } else { tests.add(test); } } runner.run(tests); } public static final Predicate<Constructor<?>> IS_PUBLIC_CONSTRUCTOR = new Predicate<Constructor<?>>() { @Override public boolean apply(Constructor<?> constructor) { return Modifier.isPublic(constructor.getModifiers()); } }; private static final Predicate<Method> IS_ANNOTATED_TEST_METHOD = new Predicate<Method>() { @Override public boolean apply(Method method) { return Modifier.isPublic(method.getModifiers()) && method.isAnnotationPresent(org.junit.Test.class); } }; private static boolean isTest(final Class<?> clazz) { // Must be a public concrete class to be a runnable junit Test. if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()) || !Modifier.isPublic(clazz.getModifiers())) { return false; } // The class must have some public constructor to be instantiated by the runner being used if (!Iterables.any(Arrays.asList(clazz.getConstructors()), IS_PUBLIC_CONSTRUCTOR)) { return false; } // Support junit 3.x Test hierarchy. if (junit.framework.Test.class.isAssignableFrom(clazz)) { return true; } // Support classes using junit 4.x custom runners. if (clazz.isAnnotationPresent(RunWith.class)) { return true; } // Support junit 4.x @Test annotated methods. return Iterables.any(Arrays.asList(clazz.getMethods()), IS_ANNOTATED_TEST_METHOD); } private static void exit(int code) { exitStatus = code; if (callSystemExitOnFinish) { // We're a main - its fine to exit. // SUPPRESS CHECKSTYLE RegexpSinglelineJava System.exit(code); } else { if (code != 0) { throw new RuntimeException("ConsoleRunner exited with status " + code); } } } // ---------------------------- For testing only --------------------------------- static void setCallSystemExitOnFinish(boolean v) { callSystemExitOnFinish = v; } static int getExitStatus() { return exitStatus; } static void setExitStatus(int v) { exitStatus = v; } }
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.client.remote; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.config.OStorageConfiguration; import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy; import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManager; import com.orientechnologies.orient.core.exception.ORecordNotFoundException; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.storage.OCluster; import com.orientechnologies.orient.core.storage.OPhysicalPosition; import com.orientechnologies.orient.core.storage.ORawBuffer; import com.orientechnologies.orient.core.storage.ORecordCallback; import com.orientechnologies.orient.core.storage.ORecordMetadata; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.storage.OStorageOperationResult; import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.core.tx.OTransaction; import com.orientechnologies.orient.core.version.ORecordVersion; import com.orientechnologies.orient.core.version.OVersionFactory; import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryAsynchClient; import com.orientechnologies.orient.enterprise.channel.binary.ORemoteServerEventListener; /** * Wrapper of OStorageRemote that maintains the sessionId. It's bound to the ODatabase and allow to use the shared OStorageRemote. */ @SuppressWarnings("unchecked") public class OStorageRemoteThread implements OStorageProxy { private static AtomicInteger sessionSerialId = new AtomicInteger(-1); private final OStorageRemote delegate; private String serverURL; private int sessionId; private byte[] token; public OStorageRemoteThread(final OStorageRemote iSharedStorage) { delegate = iSharedStorage; serverURL = null; sessionId = sessionSerialId.decrementAndGet(); } public OStorageRemoteThread(final OStorageRemote iSharedStorage, final int iSessionId) { delegate = iSharedStorage; serverURL = null; sessionId = iSessionId; } public static int getNextConnectionId() { return sessionSerialId.decrementAndGet(); } public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iOptions) { pushSession(); try { delegate.open(iUserName, iUserPassword, iOptions); } finally { popSession(); } } @Override public boolean isDistributed() { return delegate.isDistributed(); } @Override public Class<? extends OSBTreeCollectionManager> getCollectionManagerClass() { return delegate.getCollectionManagerClass(); } public void create(final Map<String, Object> iOptions) { pushSession(); try { delegate.create(iOptions); } finally { popSession(); } } public void close(boolean iForce, boolean onDelete) { pushSession(); try { delegate.close(iForce, false); Orient.instance().unregisterStorage(this); } finally { popSession(); } } public boolean dropCluster(final String iClusterName, final boolean iTruncate) { pushSession(); try { return delegate.dropCluster(iClusterName, iTruncate); } finally { popSession(); } } public int getUsers() { pushSession(); try { return delegate.getUsers(); } finally { popSession(); } } public int addUser() { pushSession(); try { return delegate.addUser(); } finally { popSession(); } } public void setSessionId(final String iServerURL, final int iSessionId, byte[] iToken) { serverURL = iServerURL; sessionId = iSessionId; token = iToken; delegate.setSessionId(serverURL, iSessionId, iToken); } public void reload() { pushSession(); try { delegate.reload(); } finally { popSession(); } } public boolean exists() { pushSession(); try { return delegate.exists(); } finally { popSession(); } } public int removeUser() { pushSession(); try { return delegate.removeUser(); } finally { popSession(); } } public void close() { pushSession(); try { delegate.close(); Orient.instance().unregisterStorage(this); } finally { popSession(); } } public void delete() { pushSession(); try { delegate.delete(); Orient.instance().unregisterStorage(this); } finally { popSession(); } } @Override public OStorage getUnderlying() { return delegate; } @Override public boolean isRemote() { return true; } public Set<String> getClusterNames() { pushSession(); try { return delegate.getClusterNames(); } finally { popSession(); } } @Override public List<String> backup(OutputStream out, Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iListener, int compressionLevel, int bufferSize) throws IOException { throw new UnsupportedOperationException("backup"); } @Override public void restore(InputStream in, Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iListener) throws IOException { throw new UnsupportedOperationException("restore"); } public OStorageOperationResult<OPhysicalPosition> createRecord(final ORecordId iRid, final byte[] iContent, ORecordVersion iRecordVersion, final byte iRecordType, final int iMode, ORecordCallback<Long> iCallback) { pushSession(); try { return delegate.createRecord(iRid, iContent, OVersionFactory.instance().createVersion(), iRecordType, iMode, iCallback); } finally { popSession(); } } public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache, ORecordCallback<ORawBuffer> iCallback) { pushSession(); try { return delegate.readRecord(iRid, iFetchPlan, iIgnoreCache, null); } finally { popSession(); } } @Override public OStorageOperationResult<ORawBuffer> readRecordIfVersionIsNotLatest(ORecordId rid, String fetchPlan, boolean ignoreCache, ORecordVersion recordVersion) throws ORecordNotFoundException { pushSession(); try { return delegate.readRecordIfVersionIsNotLatest(rid, fetchPlan, ignoreCache, recordVersion); } finally { popSession(); } } public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRid, boolean updateContent, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType, final int iMode, ORecordCallback<ORecordVersion> iCallback) { pushSession(); try { return delegate.updateRecord(iRid, updateContent, iContent, iVersion, iRecordType, iMode, iCallback); } finally { popSession(); } } public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRid, final ORecordVersion iVersion, final int iMode, ORecordCallback<Boolean> iCallback) { pushSession(); try { return delegate.deleteRecord(iRid, iVersion, iMode, iCallback); } finally { popSession(); } } @Override public OStorageOperationResult<Boolean> hideRecord(ORecordId recordId, int mode, ORecordCallback<Boolean> callback) { pushSession(); try { return delegate.hideRecord(recordId, mode, callback); } finally { popSession(); } } @Override public OCluster getClusterByName(String clusterName) { return delegate.getClusterByName(clusterName); } @Override public ORecordConflictStrategy getConflictStrategy() { throw new UnsupportedOperationException("getConflictStrategy"); } @Override public void setConflictStrategy(ORecordConflictStrategy iResolver) { throw new UnsupportedOperationException("setConflictStrategy"); } @Override public ORecordMetadata getRecordMetadata(ORID rid) { pushSession(); try { return delegate.getRecordMetadata(rid); } finally { popSession(); } } @Override public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) { pushSession(); try { return delegate.cleanOutRecord(recordId, recordVersion, iMode, callback); } finally { popSession(); } } public long count(final int iClusterId) { pushSession(); try { return delegate.count(iClusterId); } finally { popSession(); } } @Override public long count(int iClusterId, boolean countTombstones) { pushSession(); try { return delegate.count(iClusterId, countTombstones); } finally { popSession(); } } @Override public long count(int[] iClusterIds, boolean countTombstones) { pushSession(); try { return delegate.count(iClusterIds, countTombstones); } finally { popSession(); } } public String toString() { return delegate.toString(); } public long[] getClusterDataRange(final int iClusterId) { pushSession(); try { return delegate.getClusterDataRange(iClusterId); } finally { popSession(); } } @Override public OPhysicalPosition[] higherPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) { pushSession(); try { return delegate.higherPhysicalPositions(currentClusterId, physicalPosition); } finally { popSession(); } } @Override public OPhysicalPosition[] lowerPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) { pushSession(); try { return delegate.lowerPhysicalPositions(currentClusterId, physicalPosition); } finally { popSession(); } } @Override public OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) { pushSession(); try { return delegate.ceilingPhysicalPositions(clusterId, physicalPosition); } finally { popSession(); } } @Override public OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) { pushSession(); try { return delegate.floorPhysicalPositions(clusterId, physicalPosition); } finally { popSession(); } } public long getSize() { pushSession(); try { return delegate.getSize(); } finally { popSession(); } } public long countRecords() { pushSession(); try { return delegate.countRecords(); } finally { popSession(); } } public long count(final int[] iClusterIds) { pushSession(); try { return delegate.count(iClusterIds); } finally { popSession(); } } public Object command(final OCommandRequestText iCommand) { pushSession(); try { return delegate.command(iCommand); } finally { popSession(); } } public void commit(final OTransaction iTx, Runnable callback) { pushSession(); try { delegate.commit(iTx, null); } finally { popSession(); } } public void rollback(OTransaction iTx) { pushSession(); try { delegate.rollback(iTx); } finally { popSession(); } } public int getClusterIdByName(final String iClusterName) { pushSession(); try { return delegate.getClusterIdByName(iClusterName); } finally { popSession(); } } public int getDefaultClusterId() { pushSession(); try { return delegate.getDefaultClusterId(); } finally { popSession(); } } public void setDefaultClusterId(final int defaultClusterId) { pushSession(); try { delegate.setDefaultClusterId(defaultClusterId); } finally { popSession(); } } public int addCluster(final String iClusterName, boolean forceListBased, final Object... iArguments) { pushSession(); try { return delegate.addCluster(iClusterName, false, iArguments); } finally { popSession(); } } public int addCluster(String iClusterName, int iRequestedId, boolean forceListBased, Object... iParameters) { pushSession(); try { return delegate.addCluster(iClusterName, iRequestedId, forceListBased, iParameters); } finally { popSession(); } } public boolean dropCluster(final int iClusterId, final boolean iTruncate) { pushSession(); try { return delegate.dropCluster(iClusterId, iTruncate); } finally { popSession(); } } public void synch() { pushSession(); try { delegate.synch(); } finally { popSession(); } } public String getPhysicalClusterNameById(final int iClusterId) { pushSession(); try { return delegate.getPhysicalClusterNameById(iClusterId); } finally { popSession(); } } public int getClusters() { pushSession(); try { return delegate.getClusterMap(); } finally { popSession(); } } public Collection<OCluster> getClusterInstances() { pushSession(); try { return delegate.getClusterInstances(); } finally { popSession(); } } public OCluster getClusterById(final int iId) { pushSession(); try { return delegate.getClusterById(iId); } finally { popSession(); } } public long getVersion() { pushSession(); try { return delegate.getVersion(); } finally { popSession(); } } public boolean isPermanentRequester() { pushSession(); try { return delegate.isPermanentRequester(); } finally { popSession(); } } public void updateClusterConfiguration(final String iCurrentURL, final byte[] iContent) { pushSession(); try { delegate.updateClusterConfiguration(iCurrentURL, iContent); } finally { popSession(); } } public OStorageConfiguration getConfiguration() { pushSession(); try { return delegate.getConfiguration(); } finally { popSession(); } } public boolean isClosed() { return (sessionId < 0 && token == null) || delegate.isClosed(); } public boolean checkForRecordValidity(final OPhysicalPosition ppos) { pushSession(); try { return delegate.checkForRecordValidity(ppos); } finally { popSession(); } } @Override public boolean isAssigningClusterIds() { return false; } public String getName() { pushSession(); try { return delegate.getName(); } finally { popSession(); } } public String getURL() { return delegate.getURL(); } public void beginResponse(final OChannelBinaryAsynchClient iNetwork) throws IOException { pushSession(); try { delegate.beginResponse(iNetwork); } finally { popSession(); } } @Override public OCurrentStorageComponentsFactory getComponentsFactory() { return delegate.getComponentsFactory(); } @Override public long getLastOperationId() { return 0; } public boolean existsResource(final String iName) { return delegate.existsResource(iName); } public synchronized <T> T getResource(final String iName, final Callable<T> iCallback) { return (T) delegate.getResource(iName, iCallback); } public <T> T removeResource(final String iName) { return (T) delegate.removeResource(iName); } public ODocument getClusterConfiguration() { return delegate.getClusterConfiguration(); } public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { return delegate.callInLock(iCallable, iExclusiveLock); } public ORemoteServerEventListener getRemoteServerEventListener() { return delegate.getAsynchEventListener(); } public void setRemoteServerEventListener(final ORemoteServerEventListener iListener) { delegate.setAsynchEventListener(iListener); } public void removeRemoteServerEventListener() { delegate.removeRemoteServerEventListener(); } @Override public void checkForClusterPermissions(final String iClusterName) { delegate.checkForClusterPermissions(iClusterName); } public STATUS getStatus() { return delegate.getStatus(); } @Override public String getUserName() { return delegate.getUserName(); } @Override public Object indexGet(final String iIndexName, final Object iKey, final String iFetchPlan) { return delegate.indexGet(iIndexName, iKey, iFetchPlan); } @Override public void indexPut(final String iIndexName, Object iKey, final OIdentifiable iValue) { delegate.indexPut(iIndexName, iKey, iValue); } @Override public boolean indexRemove(final String iIndexName, final Object iKey) { return delegate.indexRemove(iIndexName, iKey); } @Override public String getType() { return delegate.getType(); } @Override public boolean equals(final Object iOther) { if (iOther instanceof OStorageRemoteThread) return iOther == this; if (iOther instanceof OStorageRemote) return iOther == delegate; return false; } protected void handleException(final OChannelBinaryAsynchClient iNetwork, final String iMessage, final Exception iException) { delegate.handleException(iNetwork, iMessage, iException); } protected void pushSession() { delegate.setSessionId(serverURL, sessionId, token); } protected void popSession() { serverURL = delegate.getServerURL(); sessionId = delegate.getSessionId(); token = delegate.getSessionToken(); // delegate.clearSession(); } }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~ // //// /// /// /// ////// //// // //// //// /// //// //// // //// //// /// //// ///// // /// /// //// ///// // //// ////// // /// ///// // //// //// // //// ///// // //// //// ///////////// //// //// //////////// /// /// ///// ///// //// //// ///// ///// //// ///// // //// //// /// ///// // ///// ///// //////////// //// //// //// //// // The Web framework with class. // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2013 Adam R. Nelson // // 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.sector91.wit.responders; import java.util.List; import org.simpleframework.http.Request; import org.simpleframework.http.Status; import com.sector91.wit.AlternateResponse; import com.sector91.wit.Responder; import com.sector91.wit.data.DataException; import com.sector91.wit.data.NotFoundException; import com.sector91.wit.data.Paginator; import com.sector91.wit.data.PaginatorParser; import com.sector91.wit.data.RestInterceptor; import com.sector91.wit.data.Store; import com.sector91.wit.data.StoreWithParams; import com.sector91.wit.http.HttpException; import com.sector91.wit.params.Arg; import com.sector91.wit.params.One; import com.sector91.wit.params.Params; import com.sector91.wit.params.Two; import com.sector91.wit.params.Zero; class ListResponder<T> extends ChainResponder<Zero, Two<List<T>, Paginator>> { private final PaginatorParser paginatorParser; private final Store<?, T> store; private final Iterable<? extends RestInterceptor<Zero, ?, T>> interceptors; ListResponder(Store<?, T> store, Iterable<? extends RestInterceptor<Zero, ?, T>> interceptors, PaginatorParser parser, Responder<? super Two<List<T>, Paginator>> next) { super(next); this.store = store; this.interceptors = interceptors; this.paginatorParser = parser; } @Override public Two<List<T>, Paginator> chain(Zero params, Request request) throws HttpException, AlternateResponse { for (RestInterceptor<Zero, ?, T> interceptor : interceptors) interceptor.beforeList(params, request); final Paginator paginator = paginatorParser.parse(request); final List<T> items; try { items = store.list(paginator); } catch (NotFoundException ex) { throw new HttpException(Status.NOT_FOUND, ex); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new Two<>(items, paginator); } } class ListResponderWithParams<P extends Params<?>, T> extends ChainResponder<P, Two<List<T>, Paginator>> { private final PaginatorParser paginatorParser; private final StoreWithParams<P, ?, T> store; private final Iterable<? extends RestInterceptor<P, ?, T>> interceptors; ListResponderWithParams(StoreWithParams<P, ?, T> store, Iterable<? extends RestInterceptor<P, ?, T>> interceptors, PaginatorParser parser, Responder<? super Two<List<T>, Paginator>> next) { super(next); this.store = store; this.interceptors = interceptors; this.paginatorParser = parser; } @Override public Two<List<T>, Paginator> chain(P params, Request request) throws HttpException, AlternateResponse { for (RestInterceptor<P, ?, T> interceptor : interceptors) interceptor.beforeList(params, request); final Paginator paginator = paginatorParser.parse(request); final List<T> items; try { items = store.list(params, paginator); } catch (NotFoundException ex) { throw new HttpException(Status.NOT_FOUND, ex); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new Two<>(items, paginator); } } class GetResponder<I extends Comparable<I>, T> extends ChainResponder<One<I>, One<T>> { private final Store<I, T> store; private final Iterable<RestInterceptor<Zero, I, T>> interceptors; public GetResponder(Store<I, T> store, Iterable<RestInterceptor<Zero, I, T>> interceptors, Responder<? super One<T>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<T> chain(One<I> params, Request request) throws HttpException, AlternateResponse { for (RestInterceptor<Zero, I, T> interceptor : interceptors) interceptor.beforeGet(Zero.ZERO, params.first(), request); final T item; try { item = store.read(params.first()); } catch (NotFoundException ex) { throw new HttpException(Status.NOT_FOUND, ex); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(item); } } class GetResponderWithParams <A extends Arg<?, ?>, P extends Params<? extends A>, I extends Comparable<I>, T> extends ChainResponder<Params<Arg<I, A>>, One<T>> { private final StoreWithParams<P, I, T> store; private final Iterable<RestInterceptor<P, I, T>> interceptors; public GetResponderWithParams(StoreWithParams<P, I, T> store, Iterable<RestInterceptor<P, I, T>> interceptors, Responder<? super One<T>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<T> chain(Params<Arg<I, A>> params, Request request) throws HttpException, AlternateResponse { final Arg<I, A> arg = params.asArgList(); final P tailParams = (P)arg.tail().asParams(); for (RestInterceptor<P, I, T> interceptor : interceptors) interceptor.beforeGet(tailParams, arg.head(), request); final T item; try { item = store.read(tailParams, arg.head()); } catch (NotFoundException ex) { throw new HttpException(Status.NOT_FOUND, ex); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(item); } } class PostResponder<I extends Comparable<I>, T> extends ChainResponder<One<T>, One<I>> { private final Store<I, T> store; private final Iterable<RestInterceptor<Zero, I, T>> interceptors; public PostResponder(Store<I, T> store, Iterable<RestInterceptor<Zero, I, T>> interceptors, Responder<? super One<I>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<I> chain(One<T> params, Request request) throws HttpException, AlternateResponse { for (RestInterceptor<Zero, I, T> interceptor : interceptors) interceptor.beforePost(Zero.ZERO, params.first(), request); final I id; try { id = store.create(params.first()); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(id); } } class PostResponderWithParams <A extends Arg<?, ?>, P extends Params<? extends A>, I extends Comparable<I>, T> extends ChainResponder<Params<Arg<T, A>>, One<I>> { private final StoreWithParams<P, I, T> store; private final Iterable<RestInterceptor<P, I, T>> interceptors; public PostResponderWithParams(StoreWithParams<P, I, T> store, Iterable<RestInterceptor<P, I, T>> interceptors, Responder<? super One<I>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<I> chain(Params<Arg<T, A>> params, Request request) throws HttpException, AlternateResponse { final Arg<T, A> arg = params.asArgList(); final P tailParams = (P)arg.tail().asParams(); for (RestInterceptor<P, I, T> interceptor : interceptors) interceptor.beforePost(tailParams, arg.head(), request); final I id; try { id = store.create(tailParams, arg.head()); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(id); } } class PutResponder<I extends Comparable<I>, T> extends ChainResponder<Two<I, T>, One<I>> { private final Store<I, T> store; private final Iterable<RestInterceptor<Zero, I, T>> interceptors; public PutResponder(Store<I, T> store, Iterable<RestInterceptor<Zero, I, T>> interceptors, Responder<? super One<I>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<I> chain(Two<I, T> params, Request request) throws HttpException, AlternateResponse { final I id = params.first(); for (RestInterceptor<Zero, I, T> interceptor : interceptors) interceptor.beforePut(Zero.ZERO, id, params.second(), request); try { store.update(id, params.second()); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(id); } } class PutResponderWithParams <A extends Arg<?, ?>, P extends Params<? extends A>, I extends Comparable<I>, T> extends ChainResponder<Params<Arg<T, Arg<I, A>>>, One<I>> { private final StoreWithParams<P, I, T> store; private final Iterable<RestInterceptor<P, I, T>> interceptors; public PutResponderWithParams(StoreWithParams<P, I, T> store, Iterable<RestInterceptor<P, I, T>> interceptors, Responder<? super One<I>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<I> chain(Params<Arg<T, Arg<I, A>>> params, Request request) throws HttpException, AlternateResponse { final Arg<T, Arg<I, A>> arg = params.asArgList(); final P tailParams = (P)arg.tail().tail().asParams(); final I id = arg.tail().head(); for (RestInterceptor<P, I, T> interceptor : interceptors) interceptor.beforePut(tailParams, id, arg.head(), request); try { store.update(tailParams, id, arg.head()); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(id); } } class DeleteResponder<I extends Comparable<I>> extends ChainResponder<One<I>, One<I>> { private final Store<I, ?> store; private final Iterable<? extends RestInterceptor<Zero, I, ?>> interceptors; public DeleteResponder(Store<I, ?> store, Iterable<? extends RestInterceptor<Zero, I, ?>> interceptors, Responder<? super One<I>> next){ super(next); this.store = store; this.interceptors = interceptors; } @Override public One<I> chain(One<I> params, Request request) throws HttpException, AlternateResponse { final I id = params.first(); for (RestInterceptor<Zero, I, ?> interceptor : interceptors) interceptor.beforeDelete(Zero.ZERO, id, request); try { store.delete(id); } catch (NotFoundException ex) { throw new HttpException(Status.NOT_FOUND, ex); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(id); } } class DeleteResponderWithParams <A extends Arg<?, ?>, P extends Params<? extends A>, I extends Comparable<I>> extends ChainResponder<Params<Arg<I, A>>, One<I>> { private final StoreWithParams<P, I, ?> store; private final Iterable<? extends RestInterceptor<P, I, ?>> interceptors; public DeleteResponderWithParams(StoreWithParams<P, I, ?> store, Iterable<? extends RestInterceptor<P, I, ?>> interceptors, Responder<? super One<I>> next) { super(next); this.store = store; this.interceptors = interceptors; } @Override public One<I> chain(Params<Arg<I, A>> params, Request request) throws HttpException, AlternateResponse { final Arg<I, A> arg = params.asArgList(); final I id = arg.head(); final P tailParams = (P)arg.tail().asParams(); for (RestInterceptor<P, I, ?> interceptor : interceptors) interceptor.beforeDelete(tailParams, id, request); try { store.delete(tailParams, id); } catch (NotFoundException ex) { throw new HttpException(Status.NOT_FOUND, ex); } catch (DataException ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } return new One<>(id); } }
/* * Copyright Terracotta, 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 org.terracotta.management.model.cluster; import org.terracotta.management.model.context.Context; import org.terracotta.management.model.context.Contextual; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Mathieu Carbou */ public final class Cluster implements Contextual { private static final long serialVersionUID = 2; private final Map<String, Client> clients = new TreeMap<>(); private final Map<String, Stripe> stripes = new TreeMap<>(); private Cluster() { } public boolean isEmpty() { return stripes.isEmpty(); } public Stream<Client> clientStream() { return clients.values().stream(); } public Stream<Stripe> stripeStream() { return stripes.values().stream(); } public Map<String, Client> getClients() { return clients; } public int getClientCount() { return clients.size(); } public Map<String, Stripe> getStripes() { return stripes; } public int getStripeCount() { return stripes.size(); } public Stripe getSingleStripe() throws NoSuchElementException { if (getStripeCount() != 1) { throw new NoSuchElementException(); } return stripeStream().findAny().get(); } public boolean addClient(Client client) { for (Client c : clients.values()) { if (c.getClientIdentifier().equals(client.getClientIdentifier())) { return false; } } if (clients.putIfAbsent(client.getId(), client) != null) { return false; } else { client.setParent(this); return true; } } public Optional<Client> getClient(Context context) { return getClient(context.get(Client.KEY)); } public Optional<Client> getClient(ClientIdentifier clientIdentifier) { return clientStream().filter(client -> client.getClientIdentifier().equals(clientIdentifier)).findAny(); } public Optional<Client> getClient(String id) { return id == null ? Optional.empty() : Optional.ofNullable(clients.get(id)); } public Optional<Client> removeClient(String id) { Optional<Client> client = getClient(id); client.ifPresent(c -> { if (clients.remove(id, c)) { c.detach(); } }); return client; } public boolean addStripe(Stripe stripe) { if (stripes.putIfAbsent(stripe.getId(), stripe) != null) { return false; } else { stripe.setParent(this); return true; } } public Optional<Stripe> getStripe(Context context) { return getStripe(context.get(Stripe.KEY)); } public Optional<Stripe> getStripe(String id) { return id == null ? Optional.empty() : Optional.ofNullable(stripes.get(id)); } public Optional<Stripe> removeStripe(String id) { Optional<Stripe> stripe = getStripe(id); stripe.ifPresent(s -> { if (stripes.remove(id, s)) { s.detach(); } }); return stripe; } public Optional<ServerEntity> getActiveServerEntity(Context context) { return getStripe(context).flatMap(s -> s.getActiveServerEntity(context)); } public Optional<ServerEntity> getServerEntity(Context context) { return getStripe(context).flatMap(s -> s.getServerEntity(context)); } public Optional<Server> getServer(Context context) { return getStripe(context).flatMap(s -> s.getServer(context)); } public List<? extends Node> getNodes(Context context) { List<Node> nodes = new LinkedList<>(); getStripe(context).ifPresent(stripe1 -> { nodes.add(stripe1); stripe1.getServer(context).ifPresent(server -> { nodes.add(server); server.getServerEntity(context).ifPresent(nodes::add); }); }); getClient(context).ifPresent(nodes::add); return nodes; } public String getPath(Context context) { List<? extends Node> nodes = getNodes(context); StringBuilder sb = new StringBuilder(nodes.isEmpty() ? "" : nodes.get(0).getId()); for (int i = 1; i < nodes.size(); i++) { sb.append("/").append(nodes.get(i)); } return sb.toString(); } public Stream<ServerEntity> serverEntityStream() { return stripeStream().flatMap(Stripe::serverEntityStream); } public Stream<ServerEntity> activeServerEntityStream() { return stripeStream().flatMap(Stripe::activeServerEntityStream); } public Stream<Server> serverStream() { return stripeStream().flatMap(Stripe::serverStream); } @Override public Context getContext() { return Context.empty(); } @Override public void setContext(Context context) { // do nothing: we do not change the context of a cluster object } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cluster cluster = (Cluster) o; if (!clients.equals(cluster.clients)) return false; return stripes.equals(cluster.stripes); } @Override public int hashCode() { int result = clients.hashCode(); result = 31 * result + stripes.hashCode(); return result; } @Override public String toString() { return toMap().toString(); } @SuppressWarnings("rawtypes") public Map<String, Object> toMap() { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("stripes", stripeStream().sorted(Comparator.comparing(AbstractNode::getId)).map(Stripe::toMap).collect(Collectors.toList())); map.put("clients", clientStream().sorted(Comparator.comparing(AbstractNode::getId)).map(Client::toMap).collect(Collectors.toList())); return map; } public static Cluster create() { return new Cluster(); } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2017 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.spider.parser; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.varia.NullAppender; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.parosproxy.paros.network.HttpHeader; import org.parosproxy.paros.network.HttpMalformedHeaderException; import org.parosproxy.paros.network.HttpMessage; import org.parosproxy.paros.network.HttpStatusCode; /** Unit test for {@link SpiderRedirectParser}. */ public class SpiderRedirectParserUnitTest extends SpiderParserTestUtils { private static final String ROOT_PATH = "/"; private static final int BASE_DEPTH = 0; private static final List<Integer> NON_REDIRECTION_STATUS_CODES; private static final List<Integer> REDIRECTION_STATUS_CODES; static { NON_REDIRECTION_STATUS_CODES = new ArrayList<>(); REDIRECTION_STATUS_CODES = new ArrayList<>(); Arrays.stream(HttpStatusCode.CODES) .forEach( code -> { if (HttpStatusCode.isRedirection(code)) { REDIRECTION_STATUS_CODES.add(code); } else { NON_REDIRECTION_STATUS_CODES.add(code); } }); } @BeforeAll public static void suppressLogging() { Logger.getRootLogger().addAppender(new NullAppender()); } @Test public void shouldFailToEvaluateAnUndefinedMessage() { // Given HttpMessage undefinedMessage = null; SpiderRedirectParser redirectParser = new SpiderRedirectParser(); // When / Then assertThrows( NullPointerException.class, () -> redirectParser.canParseResource(undefinedMessage, ROOT_PATH, false)); } @Test public void shouldNotParseNonRedirectionMessages() { // Given SpiderRedirectParser redirectParser = new SpiderRedirectParser(); for (int statusCode : NON_REDIRECTION_STATUS_CODES) { HttpMessage msg = createMessageWithStatusCode(statusCode); // When boolean canParse = redirectParser.canParseResource(msg, ROOT_PATH, false); // Then assertThat(Integer.toString(statusCode), canParse, is(equalTo(false))); } } @Test public void shouldParseRedirectionMessages() { // Given SpiderRedirectParser redirectParser = new SpiderRedirectParser(); for (int statusCode : REDIRECTION_STATUS_CODES) { HttpMessage msg = createMessageWithStatusCode(statusCode); // When boolean canParse = redirectParser.canParseResource(msg, ROOT_PATH, false); // Then assertThat(Integer.toString(statusCode), canParse, is(equalTo(true))); } } @Test public void shouldParseRedirectionMessageEvenIfAlreadyParsed() { // Given boolean alreadyParsed = true; SpiderRedirectParser redirectParser = new SpiderRedirectParser(); HttpMessage msg = createMessageWithStatusCode(HttpStatusCode.FOUND); // When boolean canParse = redirectParser.canParseResource(msg, ROOT_PATH, alreadyParsed); // Then assertThat(canParse, is(equalTo(true))); } @Test public void shouldFailToParseAnUndefinedMessage() { // Given HttpMessage undefinedMessage = null; SpiderRedirectParser redirectParser = new SpiderRedirectParser(); // When / Then assertThrows( NullPointerException.class, () -> redirectParser.parseResource(undefinedMessage, null, BASE_DEPTH)); } @Test public void shouldExtractUrlFromLocationHeader() { // Given String location = "http://example.com/redirection"; HttpMessage msg = createMessageWithLocationAndStatusCode(location, HttpStatusCode.FOUND); SpiderRedirectParser redirectParser = new SpiderRedirectParser(); TestSpiderParserListener listener = createAndAddTestSpiderParserListener(redirectParser); // When boolean parsed = redirectParser.parseResource(msg, null, BASE_DEPTH); // Then assertThat(parsed, is(equalTo(true))); assertThat(listener.getUrlsFound(), contains(location)); } @Test public void shouldExtractRelativeUrlFromLocationHeader() { // Given String location = "/rel/redirection"; HttpMessage msg = createMessageWithLocationAndStatusCode(location, HttpStatusCode.FOUND); SpiderRedirectParser redirectParser = new SpiderRedirectParser(); TestSpiderParserListener listener = createAndAddTestSpiderParserListener(redirectParser); // When boolean parsed = redirectParser.parseResource(msg, null, BASE_DEPTH); // Then assertThat(parsed, is(equalTo(true))); assertThat(listener.getUrlsFound(), contains("http://example.com" + location)); } @Test public void shouldNotExtractUrlIfLocationHeaderIsEmpty() { // Given String location = ""; HttpMessage msg = createMessageWithLocationAndStatusCode(location, HttpStatusCode.FOUND); SpiderRedirectParser redirectParser = new SpiderRedirectParser(); TestSpiderParserListener listener = createAndAddTestSpiderParserListener(redirectParser); // When boolean parsed = redirectParser.parseResource(msg, null, 0); // Then assertThat(parsed, is(equalTo(true))); assertThat(listener.getUrlsFound(), is(empty())); } @Test public void shouldNotExtractUrlIfLocationHeaderIsNotPresent() { // Given HttpMessage msg = createMessageWithStatusCode(HttpStatusCode.FOUND); SpiderRedirectParser redirectParser = new SpiderRedirectParser(); TestSpiderParserListener listener = createAndAddTestSpiderParserListener(redirectParser); // When boolean parsed = redirectParser.parseResource(msg, null, BASE_DEPTH); // Then assertThat(parsed, is(equalTo(true))); assertThat(listener.getUrlsFound(), is(empty())); } private static HttpMessage createMessageWithStatusCode(int statusCode) { HttpMessage msg = new HttpMessage(); try { msg.setRequestHeader("GET / HTTP/1.1\r\nHost: example.com\r\n"); msg.setResponseHeader("HTTP/1.1 " + statusCode + " Reason\r\n"); } catch (HttpMalformedHeaderException e) { throw new RuntimeException(e); } return msg; } private static HttpMessage createMessageWithLocationAndStatusCode( String location, int statusCode) { HttpMessage msg = createMessageWithStatusCode(statusCode); msg.getResponseHeader().addHeader(HttpHeader.LOCATION, location); return msg; } }
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ddmlib; import com.android.annotations.NonNull; import com.android.ddmlib.Log.LogLevel; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Thread.State; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.*; /** * A connection to the host-side android debug bridge (adb) * <p/>This is the central point to communicate with any devices, emulators, or the applications * running on them. * <p/><b>{@link #init(boolean)} must be called before anything is done.</b> */ public final class AndroidDebugBridge { /* * Minimum and maximum version of adb supported. This correspond to * ADB_SERVER_VERSION found in //device/tools/adb/adb.h */ private static final AdbVersion MIN_ADB_VERSION = AdbVersion.parseFrom("1.0.20"); private static final String ADB = "adb"; //$NON-NLS-1$ private static final String DDMS = "ddms"; //$NON-NLS-1$ private static final String SERVER_PORT_ENV_VAR = "ANDROID_ADB_SERVER_PORT"; //$NON-NLS-1$ // Where to find the ADB bridge. static final String DEFAULT_ADB_HOST = "127.0.0.1"; //$NON-NLS-1$ static final int DEFAULT_ADB_PORT = 5037; /** Port where adb server will be started **/ private static int sAdbServerPort = 0; private static InetAddress sHostAddr; private static InetSocketAddress sSocketAddr; private static AndroidDebugBridge sThis; private static boolean sInitialized = false; private static boolean sClientSupport; /** Full path to adb. */ private String mAdbOsLocation = null; private boolean mVersionCheck; private boolean mStarted = false; private DeviceMonitor mDeviceMonitor; private static final ArrayList<IDebugBridgeChangeListener> sBridgeListeners = new ArrayList<IDebugBridgeChangeListener>(); private static final ArrayList<IDeviceChangeListener> sDeviceListeners = new ArrayList<IDeviceChangeListener>(); private static final ArrayList<IClientChangeListener> sClientListeners = new ArrayList<IClientChangeListener>(); // lock object for synchronization private static final Object sLock = sBridgeListeners; /** * Classes which implement this interface provide a method that deals * with {@link AndroidDebugBridge} changes. */ public interface IDebugBridgeChangeListener { /** * Sent when a new {@link AndroidDebugBridge} is connected. * <p/> * This is sent from a non UI thread. * @param bridge the new {@link AndroidDebugBridge} object. */ void bridgeChanged(AndroidDebugBridge bridge); } /** * Classes which implement this interface provide methods that deal * with {@link IDevice} addition, deletion, and changes. */ public interface IDeviceChangeListener { /** * Sent when the a device is connected to the {@link AndroidDebugBridge}. * <p/> * This is sent from a non UI thread. * @param device the new device. */ void deviceConnected(IDevice device); /** * Sent when the a device is connected to the {@link AndroidDebugBridge}. * <p/> * This is sent from a non UI thread. * @param device the new device. */ void deviceDisconnected(IDevice device); /** * Sent when a device data changed, or when clients are started/terminated on the device. * <p/> * This is sent from a non UI thread. * @param device the device that was updated. * @param changeMask the mask describing what changed. It can contain any of the following * values: {@link IDevice#CHANGE_BUILD_INFO}, {@link IDevice#CHANGE_STATE}, * {@link IDevice#CHANGE_CLIENT_LIST} */ void deviceChanged(IDevice device, int changeMask); } /** * Classes which implement this interface provide methods that deal * with {@link Client} changes. */ public interface IClientChangeListener { /** * Sent when an existing client information changed. * <p/> * This is sent from a non UI thread. * @param client the updated client. * @param changeMask the bit mask describing the changed properties. It can contain * any of the following values: {@link Client#CHANGE_INFO}, * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE}, * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE}, * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA} */ void clientChanged(Client client, int changeMask); } /** * Initialized the library only if needed. * * @param clientSupport Indicates whether the library should enable the monitoring and * interaction with applications running on the devices. * * @see #init(boolean) */ public static synchronized void initIfNeeded(boolean clientSupport) { if (sInitialized) { return; } init(clientSupport); } /** * Initializes the <code>ddm</code> library. * <p/>This must be called once <b>before</b> any call to * {@link #createBridge(String, boolean)}. * <p>The library can be initialized in 2 ways: * <ul> * <li>Mode 1: <var>clientSupport</var> == <code>true</code>.<br>The library monitors the * devices and the applications running on them. It will connect to each application, as a * debugger of sort, to be able to interact with them through JDWP packets.</li> * <li>Mode 2: <var>clientSupport</var> == <code>false</code>.<br>The library only monitors * devices. The applications are left untouched, letting other tools built on * <code>ddmlib</code> to connect a debugger to them.</li> * </ul> * <p/><b>Only one tool can run in mode 1 at the same time.</b> * <p/>Note that mode 1 does not prevent debugging of applications running on devices. Mode 1 * lets debuggers connect to <code>ddmlib</code> which acts as a proxy between the debuggers and * the applications to debug. See {@link Client#getDebuggerListenPort()}. * <p/>The preferences of <code>ddmlib</code> should also be initialized with whatever default * values were changed from the default values. * <p/>When the application quits, {@link #terminate()} should be called. * @param clientSupport Indicates whether the library should enable the monitoring and * interaction with applications running on the devices. * @see AndroidDebugBridge#createBridge(String, boolean) * @see DdmPreferences */ public static synchronized void init(boolean clientSupport) { if (sInitialized) { throw new IllegalStateException("AndroidDebugBridge.init() has already been called."); } sInitialized = true; sClientSupport = clientSupport; // Determine port and instantiate socket address. initAdbSocketAddr(); MonitorThread monitorThread = MonitorThread.createInstance(); monitorThread.start(); HandleHello.register(monitorThread); HandleAppName.register(monitorThread); HandleTest.register(monitorThread); HandleThread.register(monitorThread); HandleHeap.register(monitorThread); HandleWait.register(monitorThread); HandleProfiling.register(monitorThread); HandleNativeHeap.register(monitorThread); HandleViewDebug.register(monitorThread); } /** * Terminates the ddm library. This must be called upon application termination. */ public static synchronized void terminate() { // kill the monitoring services if (sThis != null && sThis.mDeviceMonitor != null) { sThis.mDeviceMonitor.stop(); sThis.mDeviceMonitor = null; } MonitorThread monitorThread = MonitorThread.getInstance(); if (monitorThread != null) { monitorThread.quit(); } sInitialized = false; } /** * Returns whether the ddmlib is setup to support monitoring and interacting with * {@link Client}s running on the {@link IDevice}s. */ static boolean getClientSupport() { return sClientSupport; } /** * Returns the socket address of the ADB server on the host. */ public static InetSocketAddress getSocketAddress() { return sSocketAddr; } /** * Creates a {@link AndroidDebugBridge} that is not linked to any particular executable. * <p/>This bridge will expect adb to be running. It will not be able to start/stop/restart * adb. * <p/>If a bridge has already been started, it is directly returned with no changes (similar * to calling {@link #getBridge()}). * @return a connected bridge. */ public static AndroidDebugBridge createBridge() { synchronized (sLock) { if (sThis != null) { return sThis; } try { sThis = new AndroidDebugBridge(); sThis.start(); } catch (InvalidParameterException e) { sThis = null; } // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray( new IDebugBridgeChangeListener[sBridgeListeners.size()]); // notify the listeners of the change for (IDebugBridgeChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.bridgeChanged(sThis); } catch (Exception e) { Log.e(DDMS, e); } } return sThis; } } /** * Creates a new debug bridge from the location of the command line tool. * <p/> * Any existing server will be disconnected, unless the location is the same and * <code>forceNewBridge</code> is set to false. * @param osLocation the location of the command line tool 'adb' * @param forceNewBridge force creation of a new bridge even if one with the same location * already exists. * @return a connected bridge. */ public static AndroidDebugBridge createBridge(String osLocation, boolean forceNewBridge) { synchronized (sLock) { if (sThis != null) { if (sThis.mAdbOsLocation != null && sThis.mAdbOsLocation.equals(osLocation) && !forceNewBridge) { return sThis; } else { // stop the current server sThis.stop(); } } try { sThis = new AndroidDebugBridge(osLocation); sThis.start(); } catch (InvalidParameterException e) { sThis = null; } // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray( new IDebugBridgeChangeListener[sBridgeListeners.size()]); // notify the listeners of the change for (IDebugBridgeChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.bridgeChanged(sThis); } catch (Exception e) { Log.e(DDMS, e); } } return sThis; } } /** * Returns the current debug bridge. Can be <code>null</code> if none were created. */ public static AndroidDebugBridge getBridge() { return sThis; } /** * Disconnects the current debug bridge, and destroy the object. * <p/>This also stops the current adb host server. * <p/> * A new object will have to be created with {@link #createBridge(String, boolean)}. */ public static void disconnectBridge() { synchronized (sLock) { if (sThis != null) { sThis.stop(); sThis = null; // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray( new IDebugBridgeChangeListener[sBridgeListeners.size()]); // notify the listeners. for (IDebugBridgeChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.bridgeChanged(sThis); } catch (Exception e) { Log.e(DDMS, e); } } } } } /** * Adds the listener to the collection of listeners who will be notified when a new * {@link AndroidDebugBridge} is connected, by sending it one of the messages defined * in the {@link IDebugBridgeChangeListener} interface. * @param listener The listener which should be notified. */ public static void addDebugBridgeChangeListener(IDebugBridgeChangeListener listener) { synchronized (sLock) { if (!sBridgeListeners.contains(listener)) { sBridgeListeners.add(listener); if (sThis != null) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.bridgeChanged(sThis); } catch (Exception e) { Log.e(DDMS, e); } } } } } /** * Removes the listener from the collection of listeners who will be notified when a new * {@link AndroidDebugBridge} is started. * @param listener The listener which should no longer be notified. */ public static void removeDebugBridgeChangeListener(IDebugBridgeChangeListener listener) { synchronized (sLock) { sBridgeListeners.remove(listener); } } /** * Adds the listener to the collection of listeners who will be notified when a {@link IDevice} * is connected, disconnected, or when its properties or its {@link Client} list changed, * by sending it one of the messages defined in the {@link IDeviceChangeListener} interface. * @param listener The listener which should be notified. */ public static void addDeviceChangeListener(IDeviceChangeListener listener) { synchronized (sLock) { if (!sDeviceListeners.contains(listener)) { sDeviceListeners.add(listener); } } } /** * Removes the listener from the collection of listeners who will be notified when a * {@link IDevice} is connected, disconnected, or when its properties or its {@link Client} * list changed. * @param listener The listener which should no longer be notified. */ public static void removeDeviceChangeListener(IDeviceChangeListener listener) { synchronized (sLock) { sDeviceListeners.remove(listener); } } /** * Adds the listener to the collection of listeners who will be notified when a {@link Client} * property changed, by sending it one of the messages defined in the * {@link IClientChangeListener} interface. * @param listener The listener which should be notified. */ public static void addClientChangeListener(IClientChangeListener listener) { synchronized (sLock) { if (!sClientListeners.contains(listener)) { sClientListeners.add(listener); } } } /** * Removes the listener from the collection of listeners who will be notified when a * {@link Client} property changed. * @param listener The listener which should no longer be notified. */ public static void removeClientChangeListener(IClientChangeListener listener) { synchronized (sLock) { sClientListeners.remove(listener); } } /** * Returns the devices. * @see #hasInitialDeviceList() */ public IDevice[] getDevices() { synchronized (sLock) { if (mDeviceMonitor != null) { return mDeviceMonitor.getDevices(); } } return new IDevice[0]; } /** * Returns whether the bridge has acquired the initial list from adb after being created. * <p/>Calling {@link #getDevices()} right after {@link #createBridge(String, boolean)} will * generally result in an empty list. This is due to the internal asynchronous communication * mechanism with <code>adb</code> that does not guarantee that the {@link IDevice} list has been * built before the call to {@link #getDevices()}. * <p/>The recommended way to get the list of {@link IDevice} objects is to create a * {@link IDeviceChangeListener} object. */ public boolean hasInitialDeviceList() { if (mDeviceMonitor != null) { return mDeviceMonitor.hasInitialDeviceList(); } return false; } /** * Sets the client to accept debugger connection on the custom "Selected debug port". * @param selectedClient the client. Can be null. */ public void setSelectedClient(Client selectedClient) { MonitorThread monitorThread = MonitorThread.getInstance(); if (monitorThread != null) { monitorThread.setSelectedClient(selectedClient); } } /** * Returns whether the {@link AndroidDebugBridge} object is still connected to the adb daemon. */ public boolean isConnected() { MonitorThread monitorThread = MonitorThread.getInstance(); if (mDeviceMonitor != null && monitorThread != null) { return mDeviceMonitor.isMonitoring() && monitorThread.getState() != State.TERMINATED; } return false; } /** * Returns the number of times the {@link AndroidDebugBridge} object attempted to connect * to the adb daemon. */ public int getConnectionAttemptCount() { if (mDeviceMonitor != null) { return mDeviceMonitor.getConnectionAttemptCount(); } return -1; } /** * Returns the number of times the {@link AndroidDebugBridge} object attempted to restart * the adb daemon. */ public int getRestartAttemptCount() { if (mDeviceMonitor != null) { return mDeviceMonitor.getRestartAttemptCount(); } return -1; } /** * Creates a new bridge. * @param osLocation the location of the command line tool * @throws InvalidParameterException */ private AndroidDebugBridge(String osLocation) throws InvalidParameterException { if (osLocation == null || osLocation.isEmpty()) { throw new InvalidParameterException(); } mAdbOsLocation = osLocation; try { checkAdbVersion(); } catch (IOException e) { throw new IllegalArgumentException(e); } } /** * Creates a new bridge not linked to any particular adb executable. */ private AndroidDebugBridge() { } /** * Queries adb for its version number and checks that it is atleast {@link #MIN_ADB_VERSION}. */ private void checkAdbVersion() throws IOException { // default is bad check mVersionCheck = false; if (mAdbOsLocation == null) { return; } File adb = new File(mAdbOsLocation); ListenableFuture<AdbVersion> future = getAdbVersion(adb); AdbVersion version; try { version = future.get(5, TimeUnit.SECONDS); } catch (InterruptedException e) { return; } catch (java.util.concurrent.TimeoutException e) { String msg = "Unable to obtain result of 'adb version'"; Log.logAndDisplay(LogLevel.ERROR, ADB, msg); return; } catch (ExecutionException e) { Log.logAndDisplay(LogLevel.ERROR, ADB, e.getCause().getMessage()); Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); return; } if (version.compareTo(MIN_ADB_VERSION) > 0) { mVersionCheck = true; } else { String message = String.format( "Required minimum version of adb: %1$s." + "Current version is %2$s", MIN_ADB_VERSION, version); Log.logAndDisplay(LogLevel.ERROR, ADB, message); } } public static ListenableFuture<AdbVersion> getAdbVersion(@NonNull final File adb) { final SettableFuture<AdbVersion> future = SettableFuture.create(); new Thread(new Runnable() { @Override public void run() { ProcessBuilder pb = new ProcessBuilder(adb.getPath(), "version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); } catch (IOException e) { future.setException(e); return; } StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); try { String line; while ((line = br.readLine()) != null) { AdbVersion version = AdbVersion.parseFrom(line); if (version != AdbVersion.UNKNOWN) { future.set(version); return; } sb.append(line); sb.append('\n'); } } catch (IOException e) { future.setException(e); return; } finally { try { br.close(); } catch (IOException e) { future.setException(e); } } future.setException(new RuntimeException( "Unable to detect adb version, adb output: " + sb.toString())); } }, "Obtaining adb version").start(); return future; } /** * Starts the debug bridge. * * @return true if success. */ boolean start() { if (mAdbOsLocation != null && sAdbServerPort != 0 && (!mVersionCheck || !startAdb())) { return false; } mStarted = true; // now that the bridge is connected, we start the underlying services. mDeviceMonitor = new DeviceMonitor(this); mDeviceMonitor.start(); return true; } /** * Kills the debug bridge, and the adb host server. * @return true if success */ boolean stop() { // if we haven't started we return false; if (!mStarted) { return false; } // kill the monitoring services if (mDeviceMonitor != null) { mDeviceMonitor.stop(); mDeviceMonitor = null; } if (!stopAdb()) { return false; } mStarted = false; return true; } /** * Restarts adb, but not the services around it. * @return true if success. */ public boolean restart() { if (mAdbOsLocation == null) { Log.e(ADB, "Cannot restart adb when AndroidDebugBridge is created without the location of adb."); //$NON-NLS-1$ return false; } if (sAdbServerPort == 0) { Log.e(ADB, "ADB server port for restarting AndroidDebugBridge is not set."); //$NON-NLS-1$ return false; } if (!mVersionCheck) { Log.logAndDisplay(LogLevel.ERROR, ADB, "Attempting to restart adb, but version check failed!"); //$NON-NLS-1$ return false; } synchronized (this) { stopAdb(); boolean restart = startAdb(); if (restart && mDeviceMonitor == null) { mDeviceMonitor = new DeviceMonitor(this); mDeviceMonitor.start(); } return restart; } } /** * Notify the listener of a new {@link IDevice}. * <p/> * The notification of the listeners is done in a synchronized block. It is important to * expect the listeners to potentially access various methods of {@link IDevice} as well as * {@link #getDevices()} which use internal locks. * <p/> * For this reason, any call to this method from a method of {@link DeviceMonitor}, * {@link IDevice} which is also inside a synchronized block, should first synchronize on * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}. * @param device the new <code>IDevice</code>. * @see #getLock() */ void deviceConnected(IDevice device) { // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IDeviceChangeListener[] listenersCopy = null; synchronized (sLock) { listenersCopy = sDeviceListeners.toArray( new IDeviceChangeListener[sDeviceListeners.size()]); } // Notify the listeners for (IDeviceChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.deviceConnected(device); } catch (Exception e) { Log.e(DDMS, e); } } } /** * Notify the listener of a disconnected {@link IDevice}. * <p/> * The notification of the listeners is done in a synchronized block. It is important to * expect the listeners to potentially access various methods of {@link IDevice} as well as * {@link #getDevices()} which use internal locks. * <p/> * For this reason, any call to this method from a method of {@link DeviceMonitor}, * {@link IDevice} which is also inside a synchronized block, should first synchronize on * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}. * @param device the disconnected <code>IDevice</code>. * @see #getLock() */ void deviceDisconnected(IDevice device) { // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IDeviceChangeListener[] listenersCopy = null; synchronized (sLock) { listenersCopy = sDeviceListeners.toArray( new IDeviceChangeListener[sDeviceListeners.size()]); } // Notify the listeners for (IDeviceChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.deviceDisconnected(device); } catch (Exception e) { Log.e(DDMS, e); } } } /** * Notify the listener of a modified {@link IDevice}. * <p/> * The notification of the listeners is done in a synchronized block. It is important to * expect the listeners to potentially access various methods of {@link IDevice} as well as * {@link #getDevices()} which use internal locks. * <p/> * For this reason, any call to this method from a method of {@link DeviceMonitor}, * {@link IDevice} which is also inside a synchronized block, should first synchronize on * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}. * @param device the modified <code>IDevice</code>. * @see #getLock() */ void deviceChanged(IDevice device, int changeMask) { // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IDeviceChangeListener[] listenersCopy = null; synchronized (sLock) { listenersCopy = sDeviceListeners.toArray( new IDeviceChangeListener[sDeviceListeners.size()]); } // Notify the listeners for (IDeviceChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.deviceChanged(device, changeMask); } catch (Exception e) { Log.e(DDMS, e); } } } /** * Notify the listener of a modified {@link Client}. * <p/> * The notification of the listeners is done in a synchronized block. It is important to * expect the listeners to potentially access various methods of {@link IDevice} as well as * {@link #getDevices()} which use internal locks. * <p/> * For this reason, any call to this method from a method of {@link DeviceMonitor}, * {@link IDevice} which is also inside a synchronized block, should first synchronize on * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}. * @param client the modified <code>Client</code>. * @param changeMask the mask indicating what changed in the <code>Client</code> * @see #getLock() */ void clientChanged(Client client, int changeMask) { // because the listeners could remove themselves from the list while processing // their event callback, we make a copy of the list and iterate on it instead of // the main list. // This mostly happens when the application quits. IClientChangeListener[] listenersCopy = null; synchronized (sLock) { listenersCopy = sClientListeners.toArray( new IClientChangeListener[sClientListeners.size()]); } // Notify the listeners for (IClientChangeListener listener : listenersCopy) { // we attempt to catch any exception so that a bad listener doesn't kill our // thread try { listener.clientChanged(client, changeMask); } catch (Exception e) { Log.e(DDMS, e); } } } /** * Returns the {@link DeviceMonitor} object. */ DeviceMonitor getDeviceMonitor() { return mDeviceMonitor; } /** * Starts the adb host side server. * @return true if success */ synchronized boolean startAdb() { if (mAdbOsLocation == null) { Log.e(ADB, "Cannot start adb when AndroidDebugBridge is created without the location of adb."); //$NON-NLS-1$ return false; } if (sAdbServerPort == 0) { Log.w(ADB, "ADB server port for starting AndroidDebugBridge is not set."); //$NON-NLS-1$ return false; } Process proc; int status = -1; String[] command = getAdbLaunchCommand("start-server"); String commandString = Joiner.on(',').join(command); try { Log.d(DDMS, String.format("Launching '%1$s' to ensure ADB is running.", commandString)); ProcessBuilder processBuilder = new ProcessBuilder(command); if (DdmPreferences.getUseAdbHost()) { String adbHostValue = DdmPreferences.getAdbHostValue(); if (adbHostValue != null && !adbHostValue.isEmpty()) { //TODO : check that the String is a valid IP address Map<String, String> env = processBuilder.environment(); env.put("ADBHOST", adbHostValue); } } proc = processBuilder.start(); ArrayList<String> errorOutput = new ArrayList<String>(); ArrayList<String> stdOutput = new ArrayList<String>(); status = grabProcessOutput(proc, errorOutput, stdOutput, false /* waitForReaders */); } catch (IOException ioe) { Log.e(DDMS, "Unable to run 'adb': " + ioe.getMessage()); //$NON-NLS-1$ // we'll return false; } catch (InterruptedException ie) { Log.e(DDMS, "Unable to run 'adb': " + ie.getMessage()); //$NON-NLS-1$ // we'll return false; } if (status != 0) { Log.e(DDMS, String.format("'%1$s' failed -- run manually if necessary", commandString)); //$NON-NLS-1$ return false; } else { Log.d(DDMS, String.format("'%1$s' succeeded", commandString)); //$NON-NLS-1$ return true; } } private String[] getAdbLaunchCommand(String option) { List<String> command = new ArrayList<String>(4); command.add(mAdbOsLocation); if (sAdbServerPort != DEFAULT_ADB_PORT) { command.add("-P"); //$NON-NLS-1$ command.add(Integer.toString(sAdbServerPort)); } command.add(option); return command.toArray(new String[command.size()]); } /** * Stops the adb host side server. * * @return true if success */ private synchronized boolean stopAdb() { if (mAdbOsLocation == null) { Log.e(ADB, "Cannot stop adb when AndroidDebugBridge is created without the location of adb."); return false; } if (sAdbServerPort == 0) { Log.e(ADB, "ADB server port for restarting AndroidDebugBridge is not set"); return false; } Process proc; int status = -1; String[] command = getAdbLaunchCommand("kill-server"); //$NON-NLS-1$ try { proc = Runtime.getRuntime().exec(command); status = proc.waitFor(); } catch (IOException ioe) { // we'll return false; } catch (InterruptedException ie) { // we'll return false; } String commandString = Joiner.on(',').join(command); if (status != 0) { Log.w(DDMS, String.format("'%1$s' failed -- run manually if necessary", commandString)); return false; } else { Log.d(DDMS, String.format("'%1$s' succeeded", commandString)); return true; } } /** * Get the stderr/stdout outputs of a process and return when the process is done. * Both <b>must</b> be read or the process will block on windows. * @param process The process to get the output from * @param errorOutput The array to store the stderr output. cannot be null. * @param stdOutput The array to store the stdout output. cannot be null. * @param waitForReaders if true, this will wait for the reader threads. * @return the process return code. * @throws InterruptedException */ private int grabProcessOutput(final Process process, final ArrayList<String> errorOutput, final ArrayList<String> stdOutput, boolean waitForReaders) throws InterruptedException { assert errorOutput != null; assert stdOutput != null; // read the lines as they come. if null is returned, it's // because the process finished Thread t1 = new Thread("") { //$NON-NLS-1$ @Override public void run() { // create a buffer to read the stderr output InputStreamReader is = new InputStreamReader(process.getErrorStream()); BufferedReader errReader = new BufferedReader(is); try { while (true) { String line = errReader.readLine(); if (line != null) { Log.e(ADB, line); errorOutput.add(line); } else { break; } } } catch (IOException e) { // do nothing. } } }; Thread t2 = new Thread("") { //$NON-NLS-1$ @Override public void run() { InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader outReader = new BufferedReader(is); try { while (true) { String line = outReader.readLine(); if (line != null) { Log.d(ADB, line); stdOutput.add(line); } else { break; } } } catch (IOException e) { // do nothing. } } }; t1.start(); t2.start(); // it looks like on windows process#waitFor() can return // before the thread have filled the arrays, so we wait for both threads and the // process itself. if (waitForReaders) { try { t1.join(); } catch (InterruptedException e) { } try { t2.join(); } catch (InterruptedException e) { } } // get the return code from the process return process.waitFor(); } /** * Returns the singleton lock used by this class to protect any access to the listener. * <p/> * This includes adding/removing listeners, but also notifying listeners of new bridges, * devices, and clients. */ static Object getLock() { return sLock; } /** * Instantiates sSocketAddr with the address of the host's adb process. */ private static void initAdbSocketAddr() { try { sAdbServerPort = getAdbServerPort(); sHostAddr = InetAddress.getByName(DEFAULT_ADB_HOST); sSocketAddr = new InetSocketAddress(sHostAddr, sAdbServerPort); } catch (UnknownHostException e) { // localhost should always be known. } } /** * Returns the port where adb server should be launched. This looks at: * <ol> * <li>The system property ANDROID_ADB_SERVER_PORT</li> * <li>The environment variable ANDROID_ADB_SERVER_PORT</li> * <li>Defaults to {@link #DEFAULT_ADB_PORT} if neither the system property nor the env var * are set.</li> * </ol> * * @return The port number where the host's adb should be expected or started. */ private static int getAdbServerPort() { // check system property Integer prop = Integer.getInteger(SERVER_PORT_ENV_VAR); if (prop != null) { try { return validateAdbServerPort(prop.toString()); } catch (IllegalArgumentException e) { String msg = String.format( "Invalid value (%1$s) for ANDROID_ADB_SERVER_PORT system property.", prop); Log.w(DDMS, msg); } } // when system property is not set or is invalid, parse environment property try { String env = System.getenv(SERVER_PORT_ENV_VAR); if (env != null) { return validateAdbServerPort(env); } } catch (SecurityException ex) { // A security manager has been installed that doesn't allow access to env vars. // So an environment variable might have been set, but we can't tell. // Let's log a warning and continue with ADB's default port. // The issue is that adb would be started (by the forked process having access // to the env vars) on the desired port, but within this process, we can't figure out // what that port is. However, a security manager not granting access to env vars // but allowing to fork is a rare and interesting configuration, so the right // thing seems to be to continue using the default port, as forking is likely to // fail later on in the scenario of the security manager. Log.w(DDMS, "No access to env variables allowed by current security manager. " + "If you've set ANDROID_ADB_SERVER_PORT: it's being ignored."); } catch (IllegalArgumentException e) { String msg = String.format( "Invalid value (%1$s) for ANDROID_ADB_SERVER_PORT environment variable (%2$s).", prop, e.getMessage()); Log.w(DDMS, msg); } // use default port if neither are set return DEFAULT_ADB_PORT; } /** * Returns the integer port value if it is a valid value for adb server port * @param adbServerPort adb server port to validate * @return {@code adbServerPort} as a parsed integer * @throws IllegalArgumentException when {@code adbServerPort} is not bigger than 0 or it is * not a number at all */ private static int validateAdbServerPort(@NonNull String adbServerPort) throws IllegalArgumentException { try { // C tools (adb, emulator) accept hex and octal port numbers, so need to accept them too int port = Integer.decode(adbServerPort); if (port <= 0 || port >= 65535) { throw new IllegalArgumentException("Should be > 0 and < 65535"); } return port; } catch (NumberFormatException e) { throw new IllegalArgumentException("Not a valid port number"); } } }
/* * Copyright 2014 Basis Technology Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basistech.tclre; /** * from regc_lex.c * Note that this continues the pattern of all the state living * in the 'Compiler' object. */ class Lex { /* lexical contexts */ private static final int L_ERE = 1; /* mainline ERE/ARE */ private static final int L_BRE = 2; /* mainline BRE */ private static final int L_Q = 3; /* Flags.REG_QUOTE */ private static final int L_EBND = 4; /* ERE/ARE bound */ private static final int L_BBND = 5; /* BRE bound */ private static final int L_BRACK = 6; /* brackets */ private static final int L_CEL = 7; /* collating element */ private static final int L_ECL = 8; /* equivalence class */ private static final int L_CCL = 9; /* character class */ /* * string constants to interpolate as expansions of things like \d */ //CHECKSTYLE:OFF private static final char backd[] = { /* \d */ '[', '[', ':', 'd', 'i', 'g', 'i', 't', ':', ']', ']' }; private static final char backD[] = { /* \D */ '[', '^', '[', ':', 'd', 'i', 'g', 'i', 't', ':', ']', ']' }; private static final char brbackd[] = { /* \d within brackets */ '[', ':', 'd', 'i', 'g', 'i', 't', ':', ']' }; private static final char backs[] = { /* \s */ '[', '[', ':', 's', 'p', 'a', 'c', 'e', ':', ']', ']' }; private static final char backS[] = { /* \S */ '[', '^', '[', ':', 's', 'p', 'a', 'c', 'e', ':', ']', ']' }; private static final char brbacks[] = { /* \s within brackets */ '[', ':', 's', 'p', 'a', 'c', 'e', ':', ']' }; private static final char backw[] = { /* \w */ '[', '[', ':', 'a', 'l', 'n', 'u', 'm', ':', ']', '_', ']' }; private static final char backW[] = { /* \W */ '[', '^', '[', ':', 'a', 'l', 'n', 'u', 'm', ':', ']', '_', ']' }; private static final char brbackw[] = { /* \w within brackets */ '[', ':', 'a', 'l', 'n', 'u', 'm', ':', ']', '_' }; //CHECKSTYLE:ON private Compiler v; Lex(Compiler v) { this.v = v; } boolean see(int t) { return v.nexttype == t; } private char charAt(int index) { return v.pattern[index]; } private char charAtNow() { return charAt(v.now); } private char charAtNowAdvance() { return charAt(v.now++); } private char charAtNowPlus(int offset) { return charAt(v.now + offset); } /* scanning macros (know about v) */ boolean ateos() { return v.now >= v.stop; } boolean have(int n) { return v.stop - v.now >= n; } boolean next1(char c) { return !ateos() && charAtNow() == c; } boolean next2(char a, char b) { return have(2) && charAtNow() == a && charAtNowPlus(1) == b; } boolean next3(char a, char b, char c) { return have(3) && charAtNow() == a && charAtNowPlus(1) == b && charAtNowPlus(2) == c; } void set(int c) { v.nexttype = c; } void set(int c, int n) { v.nexttype = c; v.nextvalue = n; } boolean ret(int c) { set(c); return true; } boolean retv(int c, int n) { set(c, n); return true; } boolean lasttype(int t) { return v.lasttype == t; } void intocon(int c) { v.lexcon = c; } boolean incon(int c) { return v.lexcon == c; } /** * lexstart - set up lexical stuff, scan leading options */ void lexstart() throws RegexException { prefixes(); /* may turn on new type bits etc. */ if (0 != (v.cflags & Flags.REG_QUOTE)) { assert 0 == (v.cflags & (Flags.REG_ADVANCED | Flags.REG_EXPANDED | Flags.REG_NEWLINE)); intocon(L_Q); } else if (0 != (v.cflags & Flags.REG_EXTENDED)) { assert 0 == (v.cflags & Flags.REG_QUOTE); intocon(L_ERE); } else { assert 0 == (v.cflags & (Flags.REG_QUOTE | Flags.REG_ADVF)); intocon(L_BRE); } v.nexttype = Compiler.EMPTY; /* remember we were at the start */ next(); /* set up the first token */ } boolean iscalpha(char c) { return c < 0x80 && Character.isLetter(c); } boolean iscdigit(char x) { return x < 0x80 && Character.isDigit(x); } boolean iscalnum(char x) { return x < 0x80 && Character.isLetterOrDigit(x); } boolean iscspace(char x) { return x < 0x80 && Character.isSpaceChar(x); } /** * prefixes - implement various special prefixes */ void prefixes() throws RegexException { /* literal string doesn't get any of this stuff */ if (0 != (v.cflags & Flags.REG_QUOTE)) { return; } /* initial "***" gets special things */ if (have(4) && next3('*', '*', '*')) { switch (charAtNowPlus(3)) { case '?': /* "***?" error, msg shows version */ throw new RegexException("REG_BADPAT"); case '=': /* "***=" shifts to literal string */ v.note(Flags.REG_UNONPOSIX); v.cflags |= Flags.REG_QUOTE; v.cflags &= ~(Flags.REG_ADVANCED | Flags.REG_EXPANDED | Flags.REG_NEWLINE); v.now += 4; return; /* and there can be no more prefixes */ case ':': /* "***:" shifts to AREs */ v.note(Flags.REG_UNONPOSIX); v.cflags |= Flags.REG_ADVANCED; v.now += 4; break; default: /* otherwise *** is just an error */ throw new RegexException("REG_BADRPT"); } } /* BREs and EREs don't get embedded options */ if ((v.cflags & Flags.REG_ADVANCED) != Flags.REG_ADVANCED) { return; } /* embedded options (AREs only) */ if (have(3) && next2('(', '?') && iscalpha(charAtNowPlus(2))) { v.note(Flags.REG_UNONPOSIX); v.now += 2; for (; !ateos() && iscalpha(charAtNow()); v.now++) { switch (charAtNow()) { case 'b': /* BREs (but why???) */ v.cflags &= ~(Flags.REG_ADVANCED | Flags.REG_QUOTE); break; case 'c': /* case sensitive */ v.cflags &= ~Flags.REG_ICASE; break; case 'e': /* plain EREs */ v.cflags |= Flags.REG_EXTENDED; v.cflags &= ~(Flags.REG_ADVF | Flags.REG_QUOTE); break; case 'i': /* case insensitive */ v.cflags |= Flags.REG_ICASE; break; case 'm': /* Perloid synonym for n */ case 'n': /* \n affects ^ $ . [^ */ v.cflags |= Flags.REG_NEWLINE; break; case 'p': /* ~Perl, \n affects . [^ */ v.cflags |= Flags.REG_NLSTOP; v.cflags &= ~Flags.REG_NLANCH; break; case 'q': /* literal string */ v.cflags |= Flags.REG_QUOTE; v.cflags &= ~Flags.REG_ADVANCED; break; case 's': /* single line, \n ordinary */ v.cflags &= ~Flags.REG_NEWLINE; break; case 't': /* tight syntax */ v.cflags &= ~Flags.REG_EXPANDED; break; case 'w': /* weird, \n affects ^ $ only */ v.cflags &= ~Flags.REG_NLSTOP; v.cflags |= Flags.REG_NLANCH; break; case 'x': /* expanded syntax */ v.cflags |= Flags.REG_EXPANDED; break; default: throw new RegexException("REG_BADOPT"); } } if (!next1(')')) { throw new RegexException("REG_BADOPT"); } v.now++; if (0 != (v.cflags & Flags.REG_QUOTE)) { v.cflags &= ~(Flags.REG_EXPANDED | Flags.REG_NEWLINE); } } } /** * lexnest - "call a subroutine", interpolating string at the lexical level * Note, this is not a very general facility. There are a number of * implicit assumptions about what sorts of strings can be subroutines. */ void lexnest(char[] interpolated) { assert v.savepattern == null; /* only one level of nesting */ v.savepattern = v.pattern; v.savenow = v.now; v.savestop = v.stop; v.savenow = v.now; v.pattern = interpolated; v.now = 0; v.stop = v.pattern.length; } /** * lexword - interpolate a bracket expression for word characters * Possibly ought to inquire whether there is a "word" character class. */ void lexword() { lexnest(backw); } int digitval(char c) { return c - '0'; } void note(long n) { v.note(n); } //CHECKSTYLE:OFF /** * next - get next token */ boolean next() throws RegexException { char c; /* remember flavor of last token */ v.lasttype = v.nexttype; /* REG_BOSONLY */ if (v.nexttype == Compiler.EMPTY && (0 != (v.cflags & Flags.REG_BOSONLY))) { /* at start of a REG_BOSONLY RE */ return retv(Compiler.SBEGIN, (char)0); /* same as \A */ } /* if we're nested and we've hit end, return to outer level */ if (v.savepattern != null && ateos()) { v.now = v.savenow; v.stop = v.savestop; v.savenow = -1; v.savestop = -1; v.pattern = v.savepattern; v.savepattern = null; // mark that it's not saved. } /* skip white space etc. if appropriate (not in literal or []) */ if (0 != (v.cflags & Flags.REG_EXPANDED)) { switch (v.lexcon) { case L_ERE: case L_BRE: case L_EBND: case L_BBND: skip(); break; } } /* handle EOS, depending on context */ if (ateos()) { switch (v.lexcon) { case L_ERE: case L_BRE: case L_Q: return ret(Compiler.EOS); case L_EBND: case L_BBND: throw new RegexException("Unbalanced braces."); case L_BRACK: case L_CEL: case L_ECL: case L_CCL: throw new RegexException("Unbalanced brackets."); } assert false; } /* okay, time to actually get a character */ c = charAtNowAdvance(); /* deal with the easy contexts, punt EREs to code below */ switch (v.lexcon) { case L_BRE: /* punt BREs to separate function */ return brenext(c); case L_ERE: /* see below */ break; case L_Q: /* literal strings are easy */ return retv(Compiler.PLAIN, c); case L_BBND: /* bounds are fairly simple */ case L_EBND: switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return retv(Compiler.DIGIT, digitval(c)); case ',': return ret(','); case '}': /* ERE bound ends with } */ if (incon(L_EBND)) { intocon(L_ERE); if (0 != (v.cflags & Flags.REG_ADVF) && next1('?')) { v.now++; note(Flags.REG_UNONPOSIX); return retv('}', 0); } return retv('}', 1); } else { throw new RegexException("Errors.REG_BADBR"); } case '\\': /* BRE bound ends with \} */ if (incon(L_BBND) && next1('}')) { v.now++; intocon(L_BRE); return ret('}'); } else { throw new RegexException("Errors.REG_BADBR"); } default: throw new RegexException("Errors.REG_BADBR"); } case L_BRACK: /* brackets are not too hard */ switch (c) { case ']': if (lasttype('[')) { return retv(Compiler.PLAIN, c); } else { intocon(0 != (v.cflags & Flags.REG_EXTENDED) ? L_ERE : L_BRE); return ret(']'); } case '\\': note(Flags.REG_UBBS); if (0 == (v.cflags & Flags.REG_ADVF)) { return retv(Compiler.PLAIN, c); } note(Flags.REG_UNONPOSIX); if (ateos()) { throw new RegexException("REG_EESCAPE"); } lexescape(); switch (v.nexttype) { /* not all escapes okay here */ case Compiler.PLAIN: return true; case Compiler.CCLASS: switch (v.nextvalue) { case 'd': lexnest(brbackd); break; case 's': lexnest(brbacks); break; case 'w': lexnest(brbackw); break; default: throw new RegexException("Errors.REG_EESCAPE"); } /* lexnest done, back up and try again */ v.nexttype = v.lasttype; return next(); } /* not one of the acceptable escapes */ throw new RegexException("Errors.REG_EESCAPE"); case '-': if (lasttype('[') || next1(']')) { return retv(Compiler.PLAIN, c); } else { return retv(Compiler.RANGE, c); } case '[': if (ateos()) { throw new RegexException("Errors.REG_EBRACK"); } switch (charAtNowAdvance()) { case '.': intocon(L_CEL); /* might or might not be locale-specific */ return ret(Compiler.COLLEL); case '=': intocon(L_ECL); note(Flags.REG_ULOCALE); return ret(Compiler.ECLASS); case ':': intocon(L_CCL); note(Flags.REG_ULOCALE); return ret(Compiler.CCLASS); default: /* oops */ v.now--; return retv(Compiler.PLAIN, c); } default: return retv(Compiler.PLAIN, c); } case L_CEL: /* collating elements are easy */ if (c == '.' && next1(']')) { v.now++; intocon(L_BRACK); return retv(Compiler.END, '.'); } else { return retv(Compiler.PLAIN, c); } case L_ECL: /* ditto equivalence classes */ if (c == '=' && next1(']')) { v.now++; intocon(L_BRACK); return retv(Compiler.END, '='); } else { return retv(Compiler.PLAIN, c); } case L_CCL: /* ditto character classes */ if (c == ':' && next1(']')) { v.now++; intocon(L_BRACK); return retv(Compiler.END, ':'); } else { return retv(Compiler.PLAIN, c); } default: assert false; break; } /* that got rid of everything except EREs and AREs */ assert incon(L_ERE); /* deal with EREs and AREs, except for backslashes */ switch (c) { case '|': return ret('|'); case '*': if (0 != (v.cflags & Flags.REG_ADVF) && next1('?')) { v.now++; note(Flags.REG_UNONPOSIX); return retv('*', 0); } return retv('*', 1); case '+': if (0 != (v.cflags & Flags.REG_ADVF) && next1('?')) { v.now++; note(Flags.REG_UNONPOSIX); return retv('+', 0); } return retv('+', 1); case '?': if (0 != (v.cflags & Flags.REG_ADVF) && next1('?')) { v.now++; note(Flags.REG_UNONPOSIX); return retv('?', 0); } return retv('?', 1); case '{': /* bounds start or plain character */ if (0 != (v.cflags & Flags.REG_EXPANDED)) { skip(); } if (ateos() || !iscdigit(charAtNow())) { note(Flags.REG_UBRACES); note(Flags.REG_UUNSPEC); return retv(Compiler.PLAIN, c); } else { note(Flags.REG_UBOUNDS); intocon(L_EBND); return ret('{'); } case '(': /* parenthesis, or advanced extension */ if (0 != (v.cflags & Flags.REG_ADVF) && next1('?')) { note(Flags.REG_UNONPOSIX); v.now++; char flagChar = charAtNowAdvance(); switch (flagChar) { case ':': /* non-capturing paren */ return retv('(', 0); case '#': /* comment */ while (!ateos() && charAtNow() != ')') { v.now++; } if (!ateos()) { v.now++; } assert v.nexttype == v.lasttype; return next(); case '=': /* positive lookahead */ note(Flags.REG_ULOOKAHEAD); return retv(Compiler.LACON, 1); case '!': /* negative lookahead */ note(Flags.REG_ULOOKAHEAD); return retv(Compiler.LACON, 0); default: throw new RegexException(String.format("Invalid flag after '(?': %c", flagChar)); } } if (0 != (v.cflags & Flags.REG_NOSUB) || 0 != (v.cflags & Flags.REG_NOCAPT)) { return retv('(', 0); /* all parens non-capturing */ } else { return retv('(', 1); } case ')': if (lasttype('(')) { note(Flags.REG_UUNSPEC); } return retv(')', c); case '[': /* easy except for [[:<:]] and [[:>:]] */ if (have(6) && charAtNow() == '[' && charAtNowPlus(1) == ':' && (charAtNowPlus(2) == '<' || charAtNowPlus(2) == '>') && charAtNowPlus(3) == ':' && charAtNowPlus(4) == ']' && charAtNowPlus(5) == ']') { c = charAtNowPlus(2); v.now += 6; note(Flags.REG_UNONPOSIX); return ret((c == '<') ? '<' : '>'); } intocon(L_BRACK); if (next1('^')) { v.now++; return retv('[', 0); } return retv('[', 1); case '.': return ret('.'); case '^': return ret('^'); case '$': return ret('$'); case '\\': /* mostly punt backslashes to code below */ if (ateos()) { throw new RegexException("REG_EESCAPE"); } break; default: /* ordinary character */ return retv(Compiler.PLAIN, c); } /* ERE/ARE backslash handling; backslash already eaten */ assert !ateos(); if (0 == (v.cflags & Flags.REG_ADVF)) { /* only AREs have non-trivial escapes */ if (iscalnum(charAtNow())) { note(Flags.REG_UBSALNUM); note(Flags.REG_UUNSPEC); } return retv(Compiler.PLAIN, charAtNowAdvance()); } lexescape(); if (v.nexttype == Compiler.CCLASS) { /* fudge at lexical level */ switch (v.nextvalue) { case 'd': lexnest(backd); break; case 'D': lexnest(backD); break; case 's': lexnest(backs); break; case 'S': lexnest(backS); break; case 'w': lexnest(backw); break; case 'W': lexnest(backW); break; default: throw new RuntimeException("Invalid escape " + Character.toString((char)v.nextvalue)); } /* lexnest done, back up and try again */ v.nexttype = v.lasttype; return next(); } /* otherwise, lexescape has already done the work */ return true; } //CHECKSTYLE:ON /** * brenext - get next BRE token * This is much like EREs except for all the stupid backslashes and the */ boolean brenext(char pc) throws RegexException { char c = pc; switch (c) { case '*': if (lasttype(Compiler.EMPTY) || lasttype('(') || lasttype('^')) { return retv(Compiler.PLAIN, c); } return ret('*'); case '[': //CHECKSTYLE:OFF if (have(6) && charAtNow() == '[' && charAtNowPlus(1) == ':' && (charAtNowPlus(2) == '<' || charAtNowPlus(2) == '>') && charAtNowPlus(3) == ':' && charAtNowPlus(4) == ']' && charAtNowPlus(5) == ']') { c = charAtNowPlus(2); v.now += 6; note(Flags.REG_UNONPOSIX); return ret((c == '<') ? '<' : '>'); //CHECKSTYLE:ON } intocon(L_BRACK); if (next1('^')) { v.now++; return retv('[', 0); } return retv('[', 1); case '.': return ret('.'); case '^': if (lasttype(Compiler.EMPTY)) { return ret('^'); } if (lasttype('(')) { note(Flags.REG_UUNSPEC); return ret('^'); } return retv(Compiler.PLAIN, c); case '$': if (0 != (v.cflags & Flags.REG_EXPANDED)) { skip(); } if (ateos()) { return ret('$'); } if (next2('\\', ')')) { note(Flags.REG_UUNSPEC); return ret('$'); } return retv(Compiler.PLAIN, c); case '\\': break; /* see below */ default: return retv(Compiler.PLAIN, c); } assert c == '\\'; if (ateos()) { throw new RegexException("REG_EESCAPE"); } c = charAtNowAdvance(); switch (c) { case '{': intocon(L_BBND); note(Flags.REG_UBOUNDS); return ret('{'); case '(': return retv('(', 1); case ')': return retv(')', c); case '<': note(Flags.REG_UNONPOSIX); return ret('<'); case '>': note(Flags.REG_UNONPOSIX); return ret('>'); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': note(Flags.REG_UBACKREF); return retv(Compiler.BACKREF, digitval(c)); default: if (iscalnum(c)) { note(Flags.REG_UBSALNUM); note(Flags.REG_UUNSPEC); } return retv(Compiler.PLAIN, c); } } void skip() { int start = v.now; assert 0 != (v.cflags & Flags.REG_EXPANDED); for (;;) { while (!ateos() && iscspace(charAtNow())) { v.now++; } if (ateos() || charAtNow() != '#') { break; /* NOTE BREAK OUT */ } assert next1('#'); while (!ateos() && charAtNow() != '\n') { v.now++; } /* leave the newline to be picked up by the iscspace loop */ } if (v.now != start) { note(Flags.REG_UNONPOSIX); } } /** * lexescape - parse an ARE backslash escape (backslash already eaten) * Note slightly nonstandard use of the CCLASS type code. */ //CHECKSTYLE:OFF boolean lexescape() throws RegexException { int c; int save; assert 0 != (v.cflags & Flags.REG_ADVF); assert !ateos(); c = charAtNowAdvance(); if (!iscalnum((char)c)) { return retv(Compiler.PLAIN, c); } note(Flags.REG_UNONPOSIX); switch (c) { case 'a': return retv(Compiler.PLAIN, '\007'); case 'A': return retv(Compiler.SBEGIN, 0); case 'b': return retv(Compiler.PLAIN, '\b'); case 'B': return retv(Compiler.PLAIN, '\\'); case 'c': if (ateos()) { throw new RegexException("Incomplete \\c escape."); } return retv(Compiler.PLAIN, (char)(charAtNowAdvance() & 037)); case 'd': note(Flags.REG_ULOCALE); return retv(Compiler.CCLASS, 'd'); case 'D': note(Flags.REG_ULOCALE); return retv(Compiler.CCLASS, 'D'); case 'e': return retv(Compiler.PLAIN, '\033'); case 'f': return retv(Compiler.PLAIN, '\f'); case 'm': return ret('<'); case 'M': return ret('>'); case 'n': return retv(Compiler.PLAIN, '\n'); case 'r': return retv(Compiler.PLAIN, '\r'); case 's': note(Flags.REG_ULOCALE); return retv(Compiler.CCLASS, 's'); case 'S': note(Flags.REG_ULOCALE); return retv(Compiler.CCLASS, 'S'); case 't': return retv(Compiler.PLAIN, '\t'); case 'u': c = lexdigits(16, 4, 4); return retv(Compiler.PLAIN, c); case 'U': c = lexdigits(16, 8, 8); // This escape is for UTF-32 characters. There are, ahem, certain requirements. if (c > Character.MAX_CODE_POINT) { throw new RegexException("Invalid UTF-32 escape."); } return retv(Compiler.PLAIN, c); case 'v': return retv(Compiler.PLAIN, '\u000b'); case 'w': note(Flags.REG_ULOCALE); return retv(Compiler.CCLASS, 'w'); case 'W': note(Flags.REG_ULOCALE); return retv(Compiler.CCLASS, 'W'); case 'x': c = lexdigits(16, 1, 255); /* REs >255 long outside spec */ return retv(Compiler.PLAIN, c); case 'y': note(Flags.REG_ULOCALE); return retv(Compiler.WBDRY, 0); case 'Y': note(Flags.REG_ULOCALE); return retv(Compiler.NWBDRY, 0); case 'Z': return retv(Compiler.SEND, 0); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': save = v.now; v.now--; /* put first digit back */ c = lexdigits(10, 1, 255); /* REs >255 long outside spec */ /* ugly heuristic (first test is "exactly 1 digit?") */ if (v.now - save == 0 || c <= v.getSubs().size()) { note(Flags.REG_UBACKREF); return retv(Compiler.BACKREF, (char)c); } /* oops, doesn't look like it's a backref after all... */ v.now = save; /* and fall through into octal number */ case '0': v.now--; /* put first digit back */ c = lexdigits(8, 1, 3); return retv(Compiler.PLAIN, c); default: throw new RegexException("Invalid escape"); // unknown escape. } } //CHECKSTYLE:ON /* - lexdigits - slurp up digits and return codepoint value */ /* chr value; errors signalled via ERR */ private int lexdigits(int base, int minlen, int maxlen) throws RegexException { int n; /* unsigned to avoid overflow misbehavior */ int len; int c; int d; final char ub = (char)base; n = 0; for (len = 0; len < maxlen && !ateos(); len++) { c = charAtNowAdvance(); switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': d = digitval((char)c); break; case 'a': case 'A': d = 10; break; case 'b': case 'B': d = 11; break; case 'c': case 'C': d = 12; break; case 'd': case 'D': d = 13; break; case 'e': case 'E': d = 14; break; case 'f': case 'F': d = 15; break; default: v.now--; /* oops, not a digit at all */ d = -1; break; } if (d >= base) { /* not a plausible digit */ v.now--; d = -1; } if (d < 0) { break; /* NOTE BREAK OUT */ } n = n * ub + d; } if (len < minlen) { throw new RegexException("Not enough digits."); } return n; } }
/* * 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.eigenbase.util; import java.lang.reflect.*; import java.nio.*; import java.util.*; import com.google.common.collect.ImmutableList; /** * Static utilities for Java reflection. */ public abstract class ReflectUtil { //~ Static fields/initializers --------------------------------------------- private static Map<Class, Class> primitiveToBoxingMap; private static Map<Class, Method> primitiveToByteBufferReadMethod; private static Map<Class, Method> primitiveToByteBufferWriteMethod; static { primitiveToBoxingMap = new HashMap<Class, Class>(); primitiveToBoxingMap.put(Boolean.TYPE, Boolean.class); primitiveToBoxingMap.put(Byte.TYPE, Byte.class); primitiveToBoxingMap.put(Character.TYPE, Character.class); primitiveToBoxingMap.put(Double.TYPE, Double.class); primitiveToBoxingMap.put(Float.TYPE, Float.class); primitiveToBoxingMap.put(Integer.TYPE, Integer.class); primitiveToBoxingMap.put(Long.TYPE, Long.class); primitiveToBoxingMap.put(Short.TYPE, Short.class); primitiveToByteBufferReadMethod = new HashMap<Class, Method>(); primitiveToByteBufferWriteMethod = new HashMap<Class, Method>(); Method[] methods = ByteBuffer.class.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { Method method = methods[i]; Class[] paramTypes = method.getParameterTypes(); if (method.getName().startsWith("get")) { if (!method.getReturnType().isPrimitive()) { continue; } if (paramTypes.length != 1) { continue; } primitiveToByteBufferReadMethod.put( method.getReturnType(), method); // special case for Boolean: treat as byte if (method.getReturnType().equals(Byte.TYPE)) { primitiveToByteBufferReadMethod.put(Boolean.TYPE, method); } } else if (method.getName().startsWith("put")) { if (paramTypes.length != 2) { continue; } if (!paramTypes[1].isPrimitive()) { continue; } primitiveToByteBufferWriteMethod.put(paramTypes[1], method); // special case for Boolean: treat as byte if (paramTypes[1].equals(Byte.TYPE)) { primitiveToByteBufferWriteMethod.put(Boolean.TYPE, method); } } } } //~ Methods ---------------------------------------------------------------- /** * Uses reflection to find the correct java.nio.ByteBuffer "absolute get" * method for a given primitive type. * * @param clazz the Class object representing the primitive type * @return corresponding method */ public static Method getByteBufferReadMethod(Class clazz) { assert clazz.isPrimitive(); return primitiveToByteBufferReadMethod.get(clazz); } /** * Uses reflection to find the correct java.nio.ByteBuffer "absolute put" * method for a given primitive type. * * @param clazz the Class object representing the primitive type * @return corresponding method */ public static Method getByteBufferWriteMethod(Class clazz) { assert clazz.isPrimitive(); return primitiveToByteBufferWriteMethod.get(clazz); } /** * Gets the Java boxing class for a primitive class. * * @param primitiveClass representative class for primitive (e.g. * java.lang.Integer.TYPE) * @return corresponding boxing Class (e.g. java.lang.Integer) */ public static Class getBoxingClass(Class primitiveClass) { assert primitiveClass.isPrimitive(); return primitiveToBoxingMap.get(primitiveClass); } /** * Gets the name of a class with no package qualifiers; if it's an inner * class, it will still be qualified by the containing class (X$Y). * * @param c the class of interest * @return the unqualified name */ public static String getUnqualifiedClassName(Class c) { String className = c.getName(); int lastDot = className.lastIndexOf('.'); if (lastDot < 0) { return className; } return className.substring(lastDot + 1); } /** * Composes a string representing a human-readable method name (with neither * exception nor return type information). * * @param declaringClass class on which method is defined * @param methodName simple name of method without signature * @param paramTypes method parameter types * @return unmangled method name */ public static String getUnmangledMethodName( Class declaringClass, String methodName, Class[] paramTypes) { StringBuilder sb = new StringBuilder(); sb.append(declaringClass.getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramTypes.length; ++i) { if (i > 0) { sb.append(", "); } sb.append(paramTypes[i].getName()); } sb.append(")"); return sb.toString(); } /** * Composes a string representing a human-readable method name (with neither * exception nor return type information). * * @param method method whose name is to be generated * @return unmangled method name */ public static String getUnmangledMethodName( Method method) { return getUnmangledMethodName( method.getDeclaringClass(), method.getName(), method.getParameterTypes()); } /** * Implements the {@link Glossary#VISITOR_PATTERN} via reflection. The basic * technique is taken from <a * href="http://www.javaworld.com/javaworld/javatips/jw-javatip98.html">a * Javaworld article</a>. For an example of how to use it, see {@code * ReflectVisitorTest}. Visit method lookup follows the same rules as if * compile-time resolution for VisitorClass.visit(VisiteeClass) were * performed. An ambiguous match due to multiple interface inheritance * results in an IllegalArgumentException. A non-match is indicated by * returning false. * * @param visitor object whose visit method is to be invoked * @param visitee object to be passed as a parameter to the visit * method * @param hierarchyRoot if non-null, visitor method will only be invoked if * it takes a parameter whose type is a subtype of * hierarchyRoot * @param visitMethodName name of visit method, e.g. "visit" * @return true if a matching visit method was found and invoked */ public static boolean invokeVisitor( ReflectiveVisitor visitor, Object visitee, Class hierarchyRoot, String visitMethodName) { return invokeVisitorInternal( visitor, visitee, hierarchyRoot, visitMethodName); } /** * Shared implementation of the two forms of invokeVisitor. * * @param visitor object whose visit method is to be invoked * @param visitee object to be passed as a parameter to the visit * method * @param hierarchyRoot if non-null, visitor method will only be invoked if * it takes a parameter whose type is a subtype of * hierarchyRoot * @param visitMethodName name of visit method, e.g. "visit" * @return true if a matching visit method was found and invoked */ private static boolean invokeVisitorInternal( Object visitor, Object visitee, Class hierarchyRoot, String visitMethodName) { Class<?> visitorClass = visitor.getClass(); Class visiteeClass = visitee.getClass(); Method method = lookupVisitMethod( visitorClass, visiteeClass, visitMethodName); if (method == null) { return false; } if (hierarchyRoot != null) { Class paramType = method.getParameterTypes()[0]; if (!hierarchyRoot.isAssignableFrom(paramType)) { return false; } } try { method.invoke( visitor, visitee); } catch (IllegalAccessException ex) { throw Util.newInternal(ex); } catch (InvocationTargetException ex) { // visit methods aren't allowed to have throws clauses, // so the only exceptions which should come // to us are RuntimeExceptions and Errors Throwable t = ex.getTargetException(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new AssertionError(t.getClass().getName()); } } return true; } /** * Looks up a visit method. * * @param visitorClass class of object whose visit method is to be invoked * @param visiteeClass class of object to be passed as a parameter to the * visit method * @param visitMethodName name of visit method * @return method found, or null if none found */ public static Method lookupVisitMethod( Class<?> visitorClass, Class<?> visiteeClass, String visitMethodName) { return lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, Collections.<Class>emptyList()); } /** * Looks up a visit method taking additional parameters beyond the * overloaded visitee type. * * @param visitorClass class of object whose visit method is to be * invoked * @param visiteeClass class of object to be passed as a parameter * to the visit method * @param visitMethodName name of visit method * @param additionalParameterTypes list of additional parameter types * @return method found, or null if none found * @see #createDispatcher(Class, Class) */ public static Method lookupVisitMethod( Class<?> visitorClass, Class<?> visiteeClass, String visitMethodName, List<Class> additionalParameterTypes) { // Prepare an array to re-use in recursive calls. The first argument // will have the visitee class substituted into it. Class<?>[] paramTypes = new Class[1 + additionalParameterTypes.size()]; int iParam = 0; paramTypes[iParam++] = null; for (Class<?> paramType : additionalParameterTypes) { paramTypes[iParam++] = paramType; } // Cache Class to candidate Methods, to optimize the case where // the original visiteeClass has a diamond-shaped interface inheritance // graph. (This is common, for example, in JMI.) The idea is to avoid // iterating over a single interface's method more than once in a call. Map<Class<?>, Method> cache = new HashMap<Class<?>, Method>(); return lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, paramTypes, cache); } private static Method lookupVisitMethod( final Class<?> visitorClass, final Class<?> visiteeClass, final String visitMethodName, final Class<?>[] paramTypes, final Map<Class<?>, Method> cache) { // Use containsKey since the result for a Class might be null. if (cache.containsKey(visiteeClass)) { return cache.get(visiteeClass); } Method candidateMethod = null; paramTypes[0] = visiteeClass; try { candidateMethod = visitorClass.getMethod( visitMethodName, paramTypes); cache.put(visiteeClass, candidateMethod); return candidateMethod; } catch (NoSuchMethodException ex) { // not found: carry on with lookup } Class<?> superClass = visiteeClass.getSuperclass(); if (superClass != null) { candidateMethod = lookupVisitMethod( visitorClass, superClass, visitMethodName, paramTypes, cache); } Class<?>[] interfaces = visiteeClass.getInterfaces(); for (int i = 0; i < interfaces.length; ++i) { Method method = lookupVisitMethod( visitorClass, interfaces[i], visitMethodName, paramTypes, cache); if (method != null) { if (candidateMethod != null) { if (!method.equals(candidateMethod)) { Class<?> c1 = method.getParameterTypes()[0]; Class<?> c2 = candidateMethod.getParameterTypes()[0]; if (c1.isAssignableFrom(c2)) { // c2 inherits from c1, so keep candidateMethod // (which is more specific than method) continue; } else if (c2.isAssignableFrom(c1)) { // c1 inherits from c2 (method is more specific // than candidate method), so fall through // to set candidateMethod = method } else { // c1 and c2 are not directly related throw new IllegalArgumentException( "dispatch ambiguity between " + candidateMethod + " and " + method); } } } candidateMethod = method; } } cache.put(visiteeClass, candidateMethod); return candidateMethod; } /** * Creates a dispatcher for calls to {@link #lookupVisitMethod}. The * dispatcher caches methods between invocations. * * @param visitorBaseClazz Visitor base class * @param visiteeBaseClazz Visitee base class * @return cache of methods */ public static <R extends ReflectiveVisitor, E> ReflectiveVisitDispatcher<R, E> createDispatcher( final Class<R> visitorBaseClazz, final Class<E> visiteeBaseClazz) { assert ReflectiveVisitor.class.isAssignableFrom(visitorBaseClazz); assert Object.class.isAssignableFrom(visiteeBaseClazz); return new ReflectiveVisitDispatcher<R, E>() { final Map<List<Object>, Method> map = new HashMap<List<Object>, Method>(); public Method lookupVisitMethod( Class<? extends R> visitorClass, Class<? extends E> visiteeClass, String visitMethodName) { return lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, Collections.<Class>emptyList()); } public Method lookupVisitMethod( Class<? extends R> visitorClass, Class<? extends E> visiteeClass, String visitMethodName, List<Class> additionalParameterTypes) { final List<Object> key = ImmutableList.of( visitorClass, visiteeClass, visitMethodName, additionalParameterTypes); Method method = map.get(key); if (method == null) { if (map.containsKey(key)) { // We already looked for the method and found nothing. } else { method = ReflectUtil.lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, additionalParameterTypes); map.put(key, method); } } return method; } public boolean invokeVisitor( R visitor, E visitee, String visitMethodName) { return ReflectUtil.invokeVisitor( visitor, visitee, visiteeBaseClazz, visitMethodName); } }; } /** * Creates a dispatcher for calls to a single multi-method on a particular * object. * * <p>Calls to that multi-method are resolved by looking for a method on * the runtime type of that object, with the required name, and with * the correct type or a subclass for the first argument, and precisely the * same types for other arguments. * * <p>For instance, a dispatcher created for the method * * <blockquote>String foo(Vehicle, int, List)</blockquote> * * could be used to call the methods * * <blockquote>String foo(Car, int, List)<br> * String foo(Bus, int, List)</blockquote> * * (because Car and Bus are subclasses of Vehicle, and they occur in the * polymorphic first argument) but not the method * * <blockquote>String foo(Car, int, ArrayList)</blockquote> * * (only the first argument is polymorphic). * * <p>You must create an implementation of the method for the base class. * Otherwise throws {@link IllegalArgumentException}. * * @param returnClazz Return type of method * @param visitor Object on which to invoke the method * @param methodName Name of method * @param arg0Clazz Base type of argument zero * @param otherArgClasses Types of remaining arguments */ public static <E, T> MethodDispatcher<T> createMethodDispatcher( final Class<T> returnClazz, final ReflectiveVisitor visitor, final String methodName, final Class<E> arg0Clazz, final Class... otherArgClasses) { final List<Class> otherArgClassList = ImmutableList.copyOf(otherArgClasses); @SuppressWarnings({"unchecked" }) final ReflectiveVisitDispatcher<ReflectiveVisitor, E> dispatcher = createDispatcher( (Class<ReflectiveVisitor>) visitor.getClass(), arg0Clazz); return new MethodDispatcher<T>() { public T invoke(Object... args) { Method method = lookupMethod(args[0]); try { final Object o = method.invoke(visitor, args); return returnClazz.cast(o); } catch (IllegalAccessException e) { throw Util.newInternal( e, "While invoking method '" + method + "'"); } catch (InvocationTargetException e) { throw Util.newInternal( e, "While invoking method '" + method + "'"); } } private Method lookupMethod(final Object arg0) { if (!arg0Clazz.isInstance(arg0)) { throw new IllegalArgumentException(); } Method method = dispatcher.lookupVisitMethod( visitor.getClass(), (Class<? extends E>) arg0.getClass(), methodName, otherArgClassList); if (method == null) { List<Class> classList = new ArrayList<Class>(); classList.add(arg0Clazz); classList.addAll(otherArgClassList); throw new IllegalArgumentException( "Method not found: " + methodName + "(" + classList + ")"); } return method; } }; } //~ Inner Classes ---------------------------------------------------------- /** * Can invoke a method on an object of type E with return type T. * * @param <T> Return type of method */ public interface MethodDispatcher<T> { /** * Invokes method on an object with a given set of arguments. * * @param args Arguments to method * @return Return value of method */ T invoke(Object... args); } } // End ReflectUtil.java
package org.apache.lucene.index; /** * 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 java.io.File; import java.io.IOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.WhitespaceTokenizer; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.Directory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; public class TestPayloads extends LuceneTestCase { // Simple tests to test the Payload class public void testPayload() throws Exception { byte[] testData = "This is a test!".getBytes(); Payload payload = new Payload(testData); assertEquals("Wrong payload length.", testData.length, payload.length()); // test copyTo() byte[] target = new byte[testData.length - 1]; try { payload.copyTo(target, 0); fail("Expected exception not thrown"); } catch (Exception expected) { // expected exception } target = new byte[testData.length + 3]; payload.copyTo(target, 3); for (int i = 0; i < testData.length; i++) { assertEquals(testData[i], target[i + 3]); } // test toByteArray() target = payload.toByteArray(); assertByteArrayEquals(testData, target); // test byteAt() for (int i = 0; i < testData.length; i++) { assertEquals(payload.byteAt(i), testData[i]); } try { payload.byteAt(testData.length + 1); fail("Expected exception not thrown"); } catch (Exception expected) { // expected exception } Payload clone = (Payload) payload.clone(); assertEquals(payload.length(), clone.length()); for (int i = 0; i < payload.length(); i++) { assertEquals(payload.byteAt(i), clone.byteAt(i)); } } // Tests whether the DocumentWriter and SegmentMerger correctly enable the // payload bit in the FieldInfo public void testPayloadFieldBit() throws Exception { Directory ram = newDirectory(); PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(ram, newIndexWriterConfig( TEST_VERSION_CURRENT, analyzer)); Document d = new Document(); // this field won't have any payloads d.add(newField("f1", "This field has no payloads", Field.Store.NO, Field.Index.ANALYZED)); // this field will have payloads in all docs, however not for all term positions, // so this field is used to check if the DocumentWriter correctly enables the payloads bit // even if only some term positions have payloads d.add(newField("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); d.add(newField("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); // this field is used to verify if the SegmentMerger enables payloads for a field if it has payloads // enabled in only some documents d.add(newField("f3", "This field has payloads in some docs", Field.Store.NO, Field.Index.ANALYZED)); // only add payload data for field f2 analyzer.setPayloadData("f2", 1, "somedata".getBytes(), 0, 1); writer.addDocument(d); // flush writer.close(); SegmentReader reader = SegmentReader.getOnlySegmentReader(ram); FieldInfos fi = reader.getFieldInfos(); assertFalse("Payload field bit should not be set.", fi.fieldInfo("f1").storePayloads); assertTrue("Payload field bit should be set.", fi.fieldInfo("f2").storePayloads); assertFalse("Payload field bit should not be set.", fi.fieldInfo("f3").storePayloads); reader.close(); // now we add another document which has payloads for field f3 and verify if the SegmentMerger // enabled payloads for that field writer = new IndexWriter(ram, newIndexWriterConfig( TEST_VERSION_CURRENT, analyzer).setOpenMode(OpenMode.CREATE)); d = new Document(); d.add(newField("f1", "This field has no payloads", Field.Store.NO, Field.Index.ANALYZED)); d.add(newField("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); d.add(newField("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); d.add(newField("f3", "This field has payloads in some docs", Field.Store.NO, Field.Index.ANALYZED)); // add payload data for field f2 and f3 analyzer.setPayloadData("f2", "somedata".getBytes(), 0, 1); analyzer.setPayloadData("f3", "somedata".getBytes(), 0, 3); writer.addDocument(d); // force merge writer.forceMerge(1); // flush writer.close(); reader = SegmentReader.getOnlySegmentReader(ram); fi = reader.getFieldInfos(); assertFalse("Payload field bit should not be set.", fi.fieldInfo("f1").storePayloads); assertTrue("Payload field bit should be set.", fi.fieldInfo("f2").storePayloads); assertTrue("Payload field bit should be set.", fi.fieldInfo("f3").storePayloads); reader.close(); ram.close(); } // Tests if payloads are correctly stored and loaded using both RamDirectory and FSDirectory public void testPayloadsEncoding() throws Exception { // first perform the test using a RAMDirectory Directory dir = newDirectory(); performTest(dir); dir.close(); // now use a FSDirectory and repeat same test File dirName = _TestUtil.getTempDir("test_payloads"); dir = newFSDirectory(dirName); performTest(dir); _TestUtil.rmDir(dirName); dir.close(); } // builds an index with payloads in the given Directory and performs // different tests to verify the payload encoding private void performTest(Directory dir) throws Exception { PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, analyzer) .setOpenMode(OpenMode.CREATE) .setMergePolicy(newLogMergePolicy())); // should be in sync with value in TermInfosWriter final int skipInterval = 16; final int numTerms = 5; final String fieldName = "f1"; int numDocs = skipInterval + 1; // create content for the test documents with just a few terms Term[] terms = generateTerms(fieldName, numTerms); StringBuilder sb = new StringBuilder(); for (int i = 0; i < terms.length; i++) { sb.append(terms[i].text); sb.append(" "); } String content = sb.toString(); int payloadDataLength = numTerms * numDocs * 2 + numTerms * numDocs * (numDocs - 1) / 2; byte[] payloadData = generateRandomData(payloadDataLength); Document d = new Document(); d.add(newField(fieldName, content, Field.Store.NO, Field.Index.ANALYZED)); // add the same document multiple times to have the same payload lengths for all // occurrences within two consecutive skip intervals int offset = 0; for (int i = 0; i < 2 * numDocs; i++) { analyzer.setPayloadData(fieldName, payloadData, offset, 1); offset += numTerms; writer.addDocument(d); } // make sure we create more than one segment to test merging writer.commit(); // now we make sure to have different payload lengths next at the next skip point for (int i = 0; i < numDocs; i++) { analyzer.setPayloadData(fieldName, payloadData, offset, i); offset += i * numTerms; writer.addDocument(d); } writer.forceMerge(1); // flush writer.close(); /* * Verify the index * first we test if all payloads are stored correctly */ IndexReader reader = IndexReader.open(dir, true); byte[] verifyPayloadData = new byte[payloadDataLength]; offset = 0; TermPositions[] tps = new TermPositions[numTerms]; for (int i = 0; i < numTerms; i++) { tps[i] = reader.termPositions(terms[i]); } while (tps[0].next()) { for (int i = 1; i < numTerms; i++) { tps[i].next(); } int freq = tps[0].freq(); for (int i = 0; i < freq; i++) { for (int j = 0; j < numTerms; j++) { tps[j].nextPosition(); if (tps[j].isPayloadAvailable()) { tps[j].getPayload(verifyPayloadData, offset); offset += tps[j].getPayloadLength(); } } } } for (int i = 0; i < numTerms; i++) { tps[i].close(); } assertByteArrayEquals(payloadData, verifyPayloadData); /* * test lazy skipping */ TermPositions tp = reader.termPositions(terms[0]); tp.next(); tp.nextPosition(); // now we don't read this payload tp.nextPosition(); assertEquals("Wrong payload length.", 1, tp.getPayloadLength()); byte[] payload = tp.getPayload(null, 0); assertEquals(payload[0], payloadData[numTerms]); tp.nextPosition(); // we don't read this payload and skip to a different document tp.skipTo(5); tp.nextPosition(); assertEquals("Wrong payload length.", 1, tp.getPayloadLength()); payload = tp.getPayload(null, 0); assertEquals(payload[0], payloadData[5 * numTerms]); /* * Test different lengths at skip points */ tp.seek(terms[1]); tp.next(); tp.nextPosition(); assertEquals("Wrong payload length.", 1, tp.getPayloadLength()); tp.skipTo(skipInterval - 1); tp.nextPosition(); assertEquals("Wrong payload length.", 1, tp.getPayloadLength()); tp.skipTo(2 * skipInterval - 1); tp.nextPosition(); assertEquals("Wrong payload length.", 1, tp.getPayloadLength()); tp.skipTo(3 * skipInterval - 1); tp.nextPosition(); assertEquals("Wrong payload length.", 3 * skipInterval - 2 * numDocs - 1, tp.getPayloadLength()); /* * Test multiple call of getPayload() */ tp.getPayload(null, 0); try { // it is forbidden to call getPayload() more than once // without calling nextPosition() tp.getPayload(null, 0); fail("Expected exception not thrown"); } catch (Exception expected) { // expected exception } reader.close(); // test long payload analyzer = new PayloadAnalyzer(); writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, analyzer).setOpenMode(OpenMode.CREATE)); String singleTerm = "lucene"; d = new Document(); d.add(newField(fieldName, singleTerm, Field.Store.NO, Field.Index.ANALYZED)); // add a payload whose length is greater than the buffer size of BufferedIndexOutput payloadData = generateRandomData(2000); analyzer.setPayloadData(fieldName, payloadData, 100, 1500); writer.addDocument(d); writer.forceMerge(1); // flush writer.close(); reader = IndexReader.open(dir, true); tp = reader.termPositions(new Term(fieldName, singleTerm)); tp.next(); tp.nextPosition(); verifyPayloadData = new byte[tp.getPayloadLength()]; tp.getPayload(verifyPayloadData, 0); byte[] portion = new byte[1500]; System.arraycopy(payloadData, 100, portion, 0, 1500); assertByteArrayEquals(portion, verifyPayloadData); reader.close(); } private void generateRandomData(byte[] data) { // this test needs the random data to be valid unicode String s = _TestUtil.randomFixedByteLengthUnicodeString(random, data.length); byte b[]; try { b = s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } assert b.length == data.length; System.arraycopy(b, 0, data, 0, b.length); } private byte[] generateRandomData(int n) { byte[] data = new byte[n]; generateRandomData(data); return data; } private Term[] generateTerms(String fieldName, int n) { int maxDigits = (int) (Math.log(n) / Math.log(10)); Term[] terms = new Term[n]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.setLength(0); sb.append("t"); int zeros = maxDigits - (int) (Math.log(i) / Math.log(10)); for (int j = 0; j < zeros; j++) { sb.append("0"); } sb.append(i); terms[i] = new Term(fieldName, sb.toString()); } return terms; } void assertByteArrayEquals(byte[] b1, byte[] b2) { if (b1.length != b2.length) { fail("Byte arrays have different lengths: " + b1.length + ", " + b2.length); } for (int i = 0; i < b1.length; i++) { if (b1[i] != b2[i]) { fail("Byte arrays different at index " + i + ": " + b1[i] + ", " + b2[i]); } } } /** * This Analyzer uses an WhitespaceTokenizer and PayloadFilter. */ private static class PayloadAnalyzer extends Analyzer { Map<String,PayloadData> fieldToData = new HashMap<String,PayloadData>(); void setPayloadData(String field, byte[] data, int offset, int length) { fieldToData.put(field, new PayloadData(0, data, offset, length)); } void setPayloadData(String field, int numFieldInstancesToSkip, byte[] data, int offset, int length) { fieldToData.put(field, new PayloadData(numFieldInstancesToSkip, data, offset, length)); } @Override public TokenStream tokenStream(String fieldName, Reader reader) { PayloadData payload = fieldToData.get(fieldName); TokenStream ts = new WhitespaceTokenizer(TEST_VERSION_CURRENT, reader); if (payload != null) { if (payload.numFieldInstancesToSkip == 0) { ts = new PayloadFilter(ts, payload.data, payload.offset, payload.length); } else { payload.numFieldInstancesToSkip--; } } return ts; } private static class PayloadData { byte[] data; int offset; int length; int numFieldInstancesToSkip; PayloadData(int skip, byte[] data, int offset, int length) { numFieldInstancesToSkip = skip; this.data = data; this.offset = offset; this.length = length; } } } /** * This Filter adds payloads to the tokens. */ private static class PayloadFilter extends TokenFilter { private byte[] data; private int length; private int offset; private int startOffset; PayloadAttribute payloadAtt; public PayloadFilter(TokenStream in, byte[] data, int offset, int length) { super(in); this.data = data; this.length = length; this.offset = offset; this.startOffset = offset; payloadAtt = addAttribute(PayloadAttribute.class); } @Override public boolean incrementToken() throws IOException { boolean hasNext = input.incrementToken(); if (hasNext) { if (offset + length <= data.length) { Payload p = new Payload(); payloadAtt.setPayload(p); p.setData(data, offset, length); offset += length; } else { payloadAtt.setPayload(null); } } return hasNext; } @Override public void reset() throws IOException { super.reset(); this.offset = startOffset; } } public void testThreadSafety() throws Exception { final int numThreads = 5; final int numDocs = atLeast(50); final ByteArrayPool pool = new ByteArrayPool(numThreads, 5); Directory dir = newDirectory(); final IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random))); final String field = "test"; Thread[] ingesters = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { ingesters[i] = new Thread() { @Override public void run() { try { for (int j = 0; j < numDocs; j++) { Document d = new Document(); d.add(new Field(field, new PoolingPayloadTokenStream(pool))); writer.addDocument(d); } } catch (Exception e) { e.printStackTrace(); fail(e.toString()); } } }; ingesters[i].start(); } for (int i = 0; i < numThreads; i++) { ingesters[i].join(); } writer.close(); IndexReader reader = IndexReader.open(dir, true); TermEnum terms = reader.terms(); while (terms.next()) { TermPositions tp = reader.termPositions(terms.term()); while(tp.next()) { int freq = tp.freq(); for (int i = 0; i < freq; i++) { tp.nextPosition(); byte payload[] = new byte[5]; tp.getPayload(payload, 0); assertEquals(terms.term().text, new String(payload, 0, payload.length, "UTF-8")); } } tp.close(); } terms.close(); reader.close(); dir.close(); assertEquals(pool.size(), numThreads); } private class PoolingPayloadTokenStream extends TokenStream { private byte[] payload; private boolean first; private ByteArrayPool pool; private String term; CharTermAttribute termAtt; PayloadAttribute payloadAtt; PoolingPayloadTokenStream(ByteArrayPool pool) { this.pool = pool; payload = pool.get(); generateRandomData(payload); try { term = new String(payload, 0, payload.length, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } first = true; payloadAtt = addAttribute(PayloadAttribute.class); termAtt = addAttribute(CharTermAttribute.class); } @Override public boolean incrementToken() throws IOException { if (!first) return false; first = false; clearAttributes(); termAtt.append(term); payloadAtt.setPayload(new Payload(payload)); return true; } @Override public void close() throws IOException { pool.release(payload); } } private static class ByteArrayPool { private List<byte[]> pool; ByteArrayPool(int capacity, int size) { pool = new ArrayList<byte[]>(); for (int i = 0; i < capacity; i++) { pool.add(new byte[size]); } } synchronized byte[] get() { return pool.remove(0); } synchronized void release(byte[] b) { pool.add(b); } synchronized int size() { return pool.size(); } } public void testAcrossFields() throws Exception { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, dir, new MockAnalyzer(random, MockTokenizer.WHITESPACE, true)); Document doc = new Document(); doc.add(new Field("hasMaybepayload", "here we go", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); writer.close(); writer = new RandomIndexWriter(random, dir, new MockAnalyzer(random, MockTokenizer.WHITESPACE, true)); doc = new Document(); doc.add(new Field("hasMaybepayload2", "here we go", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); writer.addDocument(doc); writer.forceMerge(1); writer.close(); dir.close(); } }
package fr.inria.anhalytics.index; import fr.inria.anhalytics.commons.managers.MongoFileManager; import fr.inria.anhalytics.commons.utilities.Utilities; /*import org.codehaus.jackson.*; import org.codehaus.jackson.node.*; import org.codehaus.jackson.map.ObjectMapper;*/ import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.List; import java.util.Arrays; import java.util.*; import java.text.SimpleDateFormat; /** * Additional Java pre-processing of the JSON string. * * First, the TEI structure in JSON is expanded to put some attributes like @lang and @type * for certain elements in the json path in order to make possible ElasticSearch queries * with these attributes. All the structures of the TEI will be searchable with TEI paths * expressed in JSON. Those TEI/JSON paths can be used to query the ElasticSearch indexes * so that there is no need to learn and define an additional index structure * for full text. * * Second, some part of the annotations we want to use for searching documents by combining * of the annotations and the TEI full text structures are injected in the standoff node. * */ public class IndexingPreprocess { private static final Logger logger = LoggerFactory.getLogger(IndexingPreprocess.class); // this is the list of elements for which the text nodes should be expanded with an additional json // node capturing the nesting xml:lang attribute name/value pair static final public List<String> expandable = Arrays.asList("$title", "$p", "$item", "$figDesc", "$head", "$meeting", "$div", "$abstract"); // this is the list of elements to be locally enriched with annotations for the purpose of // presentation of the annotated text static final public List<String> annotated = Arrays.asList("$title", "$abstract", "term"); private MongoFileManager mm = null; public IndexingPreprocess(MongoFileManager mm) { this.mm = mm; } // maximum number of annotations to be indexed in combination with the full text TEI structure private static final int MAX_INDEXED_KEYTERM = 20; private static final int MAX_INDEXED_CONCEPT = 20; private static final int MAX_INDEXED_NERD = 50; private static int MAX_NERD_INDEXED_PARAGRAPHS = 10; private static int MAX_QUANTITIES_INDEXED_PARAGRAPHS = 200; private static final int MAX_INDEXED_QUANTITIES = 500; /** * Format jsonStr to fit with ES structure. */ public String process(String jsonStr, String repositoryDocId, String anhalyticsId) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode jsonRoot = mapper.readTree(jsonStr); // root node is the TEI node, we add as a child the "light" annotations in a // standoff element ((ObjectNode) jsonRoot).put("repositoryDocId", repositoryDocId); JsonNode teiRoot = jsonRoot.findPath("$teiCorpus"); JsonNode tei = jsonRoot.findPath("$TEI"); //check if fulltext is there.. if (tei.isNull()) { logger.info(repositoryDocId + ": <tei> element is null -> " + tei.toString()); return null; } if ((teiRoot != null) && (!teiRoot.isMissingNode())) { JsonNode standoffNode = getStandoffNerd(mapper, anhalyticsId); standoffNode = getStandoffKeyTerm(mapper, anhalyticsId, standoffNode); standoffNode = getStandoffQuantities(mapper, anhalyticsId, standoffNode); if (standoffNode != null) { ((ArrayNode) teiRoot).add(standoffNode); } } // here recursive modification of the json document via Jackson jsonRoot = process(jsonRoot, mapper, null, false, false, false, anhalyticsId); if (!filterDocuments(jsonRoot)) { return null; } return jsonRoot.toString(); } /** * Process subJson Node and iterate through sub-nodes. */ private JsonNode process(JsonNode subJson, ObjectMapper mapper, String currentLang, boolean fromArray, boolean expandLang, boolean isDate, String anhalyticsId) throws Exception { if (subJson.isContainerNode()) { if (subJson.isObject()) { Iterator<String> fields = ((ObjectNode) subJson).fieldNames(); JsonNode theSchemeNode = null; JsonNode theClassCodeNode = null; JsonNode theTypeNode = null; JsonNode theUnitNode = null; JsonNode thePersonNode = null; JsonNode theItemNode = null; JsonNode theKeywordsNode = null; JsonNode theDateNode = null; JsonNode theIdnoNode = null; JsonNode theBiblScopeNode = null; JsonNode theWhenNode = null; JsonNode theTermNode = null; JsonNode theNNode = null; JsonNode divNode = null; JsonNode theTitleNode = null; JsonNode theXmlIdNode = null; JsonNode theLevelNode = null; while (fields.hasNext()) { String field = fields.next(); if (field.startsWith("$")) { if (expandable.contains(field)) { expandLang = true; } else { expandLang = false; } } // we add the full name in order to index it directly without more time consuming // script and concatenation at facet creation time if (field.equals("$author")) { JsonNode theChild = subJson.path("$author"); // this child is an array String content = ""; if (theChild.isArray()) { String fullname = ""; String authorAnhalyticsId = ""; Iterator<JsonNode> ite = theChild.elements(); String idnoType = ""; while (ite.hasNext()) { JsonNode temp = ite.next(); if (temp.isObject()) { if (temp.fieldNames().next().equals("$persName")) { JsonNode persName = temp.path("$persName"); // this child is an array fullname = addFullName(persName, mapper); } else if (temp.fieldNames().next().equals("type")) { idnoType = temp.path("type").textValue(); if (idnoType.equals("anhalyticsID")) { authorAnhalyticsId = temp.path("$idno").elements().next().textValue(); } } } } if (!authorAnhalyticsId.isEmpty() && !fullname.isEmpty()) { content = authorAnhalyticsId + "_" + fullname; } } if (!content.isEmpty()) { JsonNode newIdNode = mapper.createObjectNode(); JsonNode newIdNode1 = mapper.createObjectNode(); JsonNode newtextNode = mapper.createArrayNode(); JsonNode tcontentnode = new TextNode(content); ((ArrayNode) newtextNode).add(tcontentnode); ((ObjectNode) newIdNode).put("$type_authorAnhalyticsID", tcontentnode); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(newIdNode); ((ObjectNode) newIdNode1).put("$idno", arrayNode); // update value ((ArrayNode) theChild).add(newIdNode1); } } else if (field.equals("$org")) { JsonNode theChild = subJson.path("$org"); // this child is an array String content = ""; if (theChild.isArray()) { String orgName = ""; String orgAnhalyticsId = ""; Iterator<JsonNode> ite = theChild.elements(); String idnoType = ""; while (ite.hasNext()) { JsonNode temp = ite.next(); if (temp.isObject()) { if (temp.fieldNames().next().equals("$orgName")) { JsonNode persName = temp.path("$orgName"); // this child is an array if (!orgName.isEmpty()) { orgName += "_" + persName.elements().next().textValue(); } else { orgName += persName.elements().next().textValue(); } } else if (temp.fieldNames().next().equals("type")) { idnoType = temp.path("type").textValue(); if (idnoType.equals("anhalyticsID")) { orgAnhalyticsId = temp.path("$idno").elements().next().textValue(); } } } } if (!orgAnhalyticsId.isEmpty() && !orgName.isEmpty()) { content = orgAnhalyticsId + "_" + orgName; } } if (!content.isEmpty()) { JsonNode newIdNode = mapper.createObjectNode(); JsonNode newIdNode1 = mapper.createObjectNode(); JsonNode newtextNode = mapper.createArrayNode(); JsonNode tcontentnode = new TextNode(content); ((ArrayNode) newtextNode).add(tcontentnode); ((ObjectNode) newIdNode).put("$type_orgAnhalyticsID", tcontentnode); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(newIdNode); ((ObjectNode) newIdNode1).put("$idno", arrayNode); // update value ((ArrayNode) theChild).add(newIdNode1); } } else if (field.equals("$classCode")) { theClassCodeNode = subJson.path("$classCode"); } else if (field.equals("level")) { theLevelNode = subJson.path("level"); } else if (field.equals("$title")) { theTitleNode = subJson.path("$title"); // we add a canonical copy of the title under $first, which allows to // query easily the title of an article without knowing the language JsonNode newNode = mapper.createObjectNode(); JsonNode textNode = mapper.createArrayNode(); String titleString = null; Iterator<JsonNode> ite2 = theTitleNode.elements(); while (ite2.hasNext()) { JsonNode temp2 = ite2.next(); titleString = temp2.textValue(); break; } JsonNode tnode = new TextNode(titleString); ((ArrayNode) textNode).add(tnode); ((ObjectNode) newNode).put("$title-first", textNode); ((ArrayNode) theTitleNode).add(newNode); //same for abstract //return subJson; } else if (field.equals("n")) { theNNode = subJson.path("n"); } else if (field.equals("$person")) { thePersonNode = subJson.path("$person"); } else if (field.equals("$div")) { divNode = subJson.path("$div"); } else if (field.equals("$item")) { theItemNode = subJson.path("$item"); } else if (field.equals("$date")) { theDateNode = subJson.path("$date"); //} else if (field.equals("$orgname")) { } else if (field.equals("$keywords")) { theKeywordsNode = subJson.path("$keywords"); String keywords = ""; //raw Iterator<JsonNode> ite2 = theKeywordsNode.elements(); /*if(theKeywordsNode.get(0).isTextual()){ System.out.println(theKeywordsNode.toString()); }*/ while (ite2.hasNext()) { JsonNode temp2 = ite2.next(); if (temp2.isTextual()) { // To avoid ambiguity, we wrap the text directy contained into keywords in a text element (otherwise ES doesnt like it) keywords += temp2.textValue(); /*String xml_id = fields.next(); JsonNode xml_idNode = subJson.path(xml_id); */ ((ArrayNode) theKeywordsNode).remove(0); JsonNode newNode = mapper.createObjectNode(); JsonNode textNode = mapper.createArrayNode(); JsonNode tnode = new TextNode(keywords); ((ArrayNode) textNode).add(tnode); ((ObjectNode) newNode).put("$raw", textNode); theKeywordsNode = subJson.path("$keywords"); ((ArrayNode) theKeywordsNode).add(newNode); } break; } } else if (field.equals("$idno")) { theIdnoNode = subJson.path("$idno"); } else if (field.equals("$biblScope")) { theBiblScopeNode = subJson.path("$biblScope"); } else if (field.equals("scheme")) { theSchemeNode = subJson.path("scheme"); } else if (field.equals("type")) { theTypeNode = subJson.path("type"); } else if (field.equals("unit")) { theUnitNode = subJson.path("unit"); } else if (field.equals("when")) { theWhenNode = subJson.path("when"); } else if (field.equals("$term")) { theTermNode = subJson.path("$term"); } else if (field.equals("xml:lang")) { JsonNode theNode = subJson.path("xml:lang"); currentLang = theNode.textValue(); } else if (field.equals("lang")) { JsonNode theNode = subJson.path("lang"); currentLang = theNode.textValue(); } else if (field.equals("xml:id")) { theXmlIdNode = subJson.path("xml:id"); } } if ((theSchemeNode != null) && (theClassCodeNode != null)) { JsonNode schemeNode = mapper.createObjectNode(); ((ObjectNode) schemeNode).put("$scheme_" + theSchemeNode.textValue(), process(theClassCodeNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); if (theNNode != null) { ((ObjectNode) schemeNode).put("$scheme_" + theSchemeNode.textValue() + "_abbrev", process(theNNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); } JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(schemeNode); ((ObjectNode) subJson).put("$classCode", arrayNode); // update value return subJson; } else if ((theTypeNode != null) && (thePersonNode != null)) { JsonNode typeNode = mapper.createObjectNode(); ((ObjectNode) typeNode).put("$type_" + theTypeNode.textValue(), process(thePersonNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$person", arrayNode); // update value return subJson; } else if ((theTypeNode != null) && (theItemNode != null)) { JsonNode typeNode = mapper.createObjectNode(); ((ObjectNode) typeNode).put("$type_" + theTypeNode.textValue(), process(theItemNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$item", arrayNode); // update value return subJson; } else if ((theTypeNode != null) && (divNode != null)) { JsonNode typeNode = mapper.createObjectNode(); ((ObjectNode) typeNode).put("$type_" + theTypeNode.textValue(), process(divNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$div", arrayNode); // update value return subJson; } else if ((theSchemeNode != null && theSchemeNode.textValue().equals("author")) && theKeywordsNode != null) { // we need to set a default "author" type JsonNode typeNode = mapper.createObjectNode(); ((ObjectNode) typeNode).put("$type_author", process(theKeywordsNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$keywords", arrayNode); // update value return subJson; } else if ((theTypeNode != null) && (theIdnoNode != null)) { JsonNode typeNode = mapper.createObjectNode(); ((ObjectNode) typeNode).put("$type_" + theTypeNode.textValue(), process(theIdnoNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$idno", arrayNode); // update value return subJson; } else if ((theTypeNode != null) && (theDateNode != null)) { JsonNode typeNode = mapper.createObjectNode(); if (theWhenNode != null) { JsonNode theWhenNode2 = mapper.createArrayNode(); ((ArrayNode) theWhenNode2).add(theWhenNode); ((ObjectNode) typeNode).put("$type_" + theTypeNode.textValue(), process(theWhenNode2, mapper, currentLang, false, expandLang, true, anhalyticsId)); ((ObjectNode) subJson).remove("when"); } else { ((ObjectNode) typeNode).put("$type_" + theTypeNode.textValue(), process(theDateNode, mapper, currentLang, false, expandLang, true, anhalyticsId)); } JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); //System.out.println(typeNode.toString()); ((ObjectNode) subJson).put("$date", arrayNode); // update value return subJson; } else if ((theTypeNode == null) && (theDateNode != null)) { JsonNode typeNode = mapper.createObjectNode(); if (theWhenNode != null) { JsonNode theWhenNode2 = mapper.createArrayNode(); ((ArrayNode) theWhenNode2).add(theWhenNode); ((ObjectNode) typeNode).put("$type_unknown", process(theWhenNode2, mapper, currentLang, false, expandLang, true, anhalyticsId)); ((ObjectNode) subJson).remove("when"); } else { ((ObjectNode) typeNode).put("$type_unknown", process(theDateNode, mapper, currentLang, false, expandLang, true, anhalyticsId)); } JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$date", arrayNode); // update value return subJson; } else if ((theUnitNode != null) && (theBiblScopeNode != null)) { JsonNode typeNode = mapper.createObjectNode(); ((ObjectNode) typeNode).put("$unit_" + theUnitNode.textValue(), process(theBiblScopeNode, mapper, currentLang, false, expandLang, false, anhalyticsId)); JsonNode arrayNode = mapper.createArrayNode(); ((ArrayNode) arrayNode).add(typeNode); ((ObjectNode) subJson).put("$biblScope", arrayNode); // update value return subJson; } } JsonNode newNode = null; if (subJson.isArray()) { newNode = mapper.createArrayNode(); Iterator<JsonNode> ite = subJson.elements(); while (ite.hasNext()) { JsonNode temp = ite.next(); ((ArrayNode) newNode).add(process(temp, mapper, currentLang, true, expandLang, isDate, anhalyticsId)); } } else if (subJson.isObject()) { newNode = mapper.createObjectNode(); Iterator<String> fields = subJson.fieldNames(); while (fields.hasNext()) { String field = fields.next(); /*if (field.equals("when")) { ((ObjectNode) newNode).put(field, process(subJson.path(field), mapper, currentLang, false, expandLang, true, anhalyticsId)); if(anhalyticsId.equals("57140e99a8267aefa7851325")) System.out.println(newNode.toString()); } else { */ ((ObjectNode) newNode).put(field, process(subJson.path(field), mapper, currentLang, false, expandLang, false, anhalyticsId)); //} } } return newNode; } else if (subJson.isTextual() && fromArray && expandLang) { JsonNode langNode = mapper.createObjectNode(); String langField = "$lang_"; if (currentLang == null) { langField += "unknown"; } else { langField += currentLang; } ArrayNode langArrayNode = mapper.createArrayNode(); langArrayNode.add(subJson); ((ObjectNode) langNode).put(langField, langArrayNode); return langNode; } else if (subJson.isTextual() && isDate) { String val = null; String date = subJson.textValue(); if (date.length() == 4) { val = date + "-12-31"; } else if ((date.length() == 7) || (date.length() == 6)) { int ind = date.indexOf("-"); String month = date.substring(ind + 1, date.length()); if (month.length() == 1) { month = "0" + month; } if (month.equals("02")) { val = date.substring(0, 4) + "-" + month + "-28"; } else if ((month.equals("04")) || (month.equals("06")) || (month.equals("09")) || (month.equals("11"))) { val = date.substring(0, 4) + "-" + month + "-30"; } else { val = date.substring(0, 4) + "-" + month + "-31"; } } else { val = date.trim(); val = Utilities.completeDate(val); // we have the "lazy programmer" case where the month is 00, e.g. 2012-00-31 // which means the month is unknown ///val = val.replace("-00-", "-12-"); } val = val.replace(" ", "T"); // this is for the dateOptionalTime elasticSearch format JsonNode tnode = new TextNode(val); return tnode; } else { return subJson; } } /** * Get the (N)ERD annotations and inject them in the document structure in a standoff node */ public JsonNode getStandoffNerd(ObjectMapper mapper, String anhalyticsId) throws Exception { JsonNode standoffNode = null; String annotation = mm.getNerdAnnotations(anhalyticsId) != null ? mm.getNerdAnnotations(anhalyticsId).getJson():null; if ((annotation != null) && (annotation.trim().length() > 0)) { JsonNode jsonAnnotation = mapper.readTree(annotation); if ((jsonAnnotation != null) && (!jsonAnnotation.isMissingNode())) { Iterator<JsonNode> iter0 = jsonAnnotation.elements(); JsonNode annotNode = mapper.createArrayNode(); int n = 0; int m = 0; while (iter0.hasNext() && (n < MAX_NERD_INDEXED_PARAGRAPHS) && (m < MAX_INDEXED_NERD)) { JsonNode jsonLocalAnnotation = (JsonNode) iter0.next(); // we only get the concept IDs and the nerd confidence score JsonNode nerd = jsonLocalAnnotation.findPath("nerd"); JsonNode entities = nerd.findPath("entities"); if ((entities != null) && (!entities.isMissingNode())) { Iterator<JsonNode> iter = entities.elements(); while (iter.hasNext()) { JsonNode piece = (JsonNode) iter.next(); JsonNode nerd_scoreN = piece.findValue("nerd_score"); JsonNode preferredTermN = piece.findValue("preferredTerm"); JsonNode wikipediaExternalRefN = piece.findValue("wikipediaExternalRef"); JsonNode freeBaseExternalRefN = piece.findValue("freeBaseExternalRef"); String nerd_score = nerd_scoreN.textValue(); String wikipediaExternalRef = null; if ((wikipediaExternalRefN != null) && (!wikipediaExternalRefN.isMissingNode())) { wikipediaExternalRef = wikipediaExternalRefN.textValue(); } String preferredTerm = null; if ((preferredTermN != null) && (!preferredTermN.isMissingNode())) { preferredTerm = preferredTermN.textValue(); } String freeBaseExternalRef = null; if ((freeBaseExternalRefN != null) && (!freeBaseExternalRefN.isMissingNode())) { freeBaseExternalRef = freeBaseExternalRefN.textValue(); } JsonNode newNode = mapper.createArrayNode(); JsonNode nerdScoreNode = mapper.createObjectNode(); ((ObjectNode) nerdScoreNode).put("nerd_score", nerd_score); ((ArrayNode) newNode).add(nerdScoreNode); if (wikipediaExternalRef != null) { JsonNode wikiNode = mapper.createObjectNode(); ((ObjectNode) wikiNode).put("wikipediaExternalRef", wikipediaExternalRef); ((ArrayNode) newNode).add(wikiNode); } if (preferredTerm != null) { JsonNode preferredTermNode = mapper.createObjectNode(); ((ObjectNode) preferredTermNode).put("preferredTerm", preferredTerm); ((ArrayNode) newNode).add(preferredTermNode); } if (freeBaseExternalRef != null) { JsonNode freeBaseNode = mapper.createObjectNode(); ((ObjectNode) freeBaseNode).put("freeBaseExternalRef", freeBaseExternalRef); ((ArrayNode) newNode).add(freeBaseNode); } ((ArrayNode) annotNode).add(newNode); m++; } } n++; } JsonNode nerdStandoffNode = mapper.createObjectNode(); ((ObjectNode) nerdStandoffNode).put("$nerd", annotNode); JsonNode annotationArrayNode = mapper.createArrayNode(); ((ArrayNode) annotationArrayNode).add(nerdStandoffNode); standoffNode = mapper.createObjectNode(); ((ObjectNode) standoffNode).put("$standoff", annotationArrayNode); } } return standoffNode; } /** * Get the grobid-keyterm annotations and inject them in the document structure in a standoff node */ public JsonNode getStandoffKeyTerm(ObjectMapper mapper, String anhalyticsId, JsonNode standoffNode) throws Exception { String annotation = mm.getKeytermAnnotations(anhalyticsId) != null? mm.getKeytermAnnotations(anhalyticsId).getJson():null; if ((annotation != null) && (annotation.trim().length() > 0)) { JsonNode jsonAnnotation = mapper.readTree(annotation); JsonNode keytermNode = jsonAnnotation.findPath("keyterm"); if ((keytermNode != null) && (!keytermNode.isMissingNode())) { // check language - only english is valid here and indexed JsonNode languageNode = keytermNode.findPath("language"); if ((languageNode != null) && (!languageNode.isMissingNode())) { JsonNode langNode = keytermNode.findPath("lang"); if ((langNode != null) && (!langNode.isMissingNode())) { String lang = langNode.textValue(); if (!lang.equals("en")) { return standoffNode; } } } // the keyterms JsonNode keytermsNode = keytermNode.findPath("keyterms"); if ((keytermsNode != null) && (!keytermsNode.isMissingNode())) { Iterator<JsonNode> iter0 = keytermsNode.elements(); JsonNode annotNode = mapper.createArrayNode(); int n = 0; while (iter0.hasNext() && (n < MAX_INDEXED_KEYTERM)) { JsonNode jsonLocalKeyterm = (JsonNode) iter0.next(); JsonNode termNode = jsonLocalKeyterm.findPath("term"); JsonNode scoreNode = jsonLocalKeyterm.findPath("score"); String term = termNode.textValue(); double score = scoreNode.doubleValue(); JsonNode newNode = mapper.createArrayNode(); JsonNode keytermScoreNode = mapper.createObjectNode(); ((ObjectNode) keytermScoreNode).put("keyterm_score", score); ((ArrayNode) newNode).add(keytermScoreNode); JsonNode ktermNode = mapper.createObjectNode(); ((ObjectNode) ktermNode).put("keyterm", term); ((ArrayNode) newNode).add(ktermNode); // do we have a concept (wikipedia/freebase id) JsonNode entitiesNode = jsonLocalKeyterm.findPath("entities"); if ((entitiesNode != null) && (!entitiesNode.isMissingNode())) { Iterator<JsonNode> iter1 = entitiesNode.elements(); if (iter1.hasNext()) { JsonNode entityNode = (JsonNode) iter1.next(); JsonNode nerd_scoreN = entityNode.findValue("nerd_score"); JsonNode preferredTermN = entityNode.findValue("preferredTerm"); JsonNode wikipediaExternalRefN = entityNode.findValue("wikipediaExternalRef"); JsonNode freeBaseExternalRefN = entityNode.findValue("freeBaseExternalRef"); String nerd_score = nerd_scoreN.textValue(); String wikipediaExternalRef = null; if ((wikipediaExternalRefN != null) && (!wikipediaExternalRefN.isMissingNode())) { wikipediaExternalRef = wikipediaExternalRefN.textValue(); } String preferredTerm = null; if ((preferredTermN != null) && (!preferredTermN.isMissingNode())) { preferredTerm = preferredTermN.textValue(); } String freeBaseExternalRef = null; if ((freeBaseExternalRefN != null) && (!freeBaseExternalRefN.isMissingNode())) { freeBaseExternalRef = freeBaseExternalRefN.textValue(); } JsonNode nerdScoreNode = mapper.createObjectNode(); ((ObjectNode) nerdScoreNode).put("nerd_score", nerd_score); ((ArrayNode) newNode).add(nerdScoreNode); if (wikipediaExternalRef != null) { JsonNode wikiNode = mapper.createObjectNode(); ((ObjectNode) wikiNode).put("wikipediaExternalRef", wikipediaExternalRef); ((ArrayNode) newNode).add(wikiNode); } if (preferredTerm != null) { JsonNode preferredTermNode = mapper.createObjectNode(); ((ObjectNode) preferredTermNode).put("preferredTerm", preferredTerm); ((ArrayNode) newNode).add(preferredTermNode); } if (freeBaseExternalRef != null) { JsonNode freeBaseNode = mapper.createObjectNode(); ((ObjectNode) freeBaseNode).put("freeBaseExternalRef", freeBaseExternalRef); ((ArrayNode) newNode).add(freeBaseNode); } } } ((ArrayNode) annotNode).add(newNode); n++; } JsonNode keytermStandoffNode = mapper.createObjectNode(); ((ObjectNode) keytermStandoffNode).put("$keyterm", annotNode); if (standoffNode == null) { standoffNode = mapper.createObjectNode(); JsonNode annotationArrayNode = mapper.createArrayNode(); ((ArrayNode) annotationArrayNode).add(keytermStandoffNode); ((ObjectNode) standoffNode).put("$standoff", annotationArrayNode); } else { JsonNode annotationArrayNode = standoffNode.findValue("$standoff"); ((ArrayNode) annotationArrayNode).add(keytermStandoffNode); } } // document categories - the categorization is based on Wikipedia categories JsonNode categoriesNode = keytermNode.findPath("global_categories"); if ((categoriesNode != null) && (!categoriesNode.isMissingNode())) { Iterator<JsonNode> iter0 = categoriesNode.elements(); JsonNode annotNode = mapper.createArrayNode(); int n = 0; while (iter0.hasNext()) { JsonNode jsonLocalCategory = (JsonNode) iter0.next(); String category = null; int pageId = -1; double weight = 0.0; JsonNode catNode = jsonLocalCategory.findPath("category"); if ((catNode != null) && (!catNode.isMissingNode())) { category = catNode.textValue(); } JsonNode pageNode = jsonLocalCategory.findPath("page_id"); if ((pageNode != null) && (!pageNode.isMissingNode())) { pageId = pageNode.intValue(); } JsonNode weightNode = jsonLocalCategory.findPath("weight"); if ((weightNode != null) && (!weightNode.isMissingNode())) { weight = weightNode.doubleValue(); } if ((category != null) && (pageId != -1) && (weight != 0.0)) { JsonNode newNode = mapper.createArrayNode(); JsonNode categoryNode = mapper.createObjectNode(); ((ObjectNode) categoryNode).put("category", category); ((ArrayNode) newNode).add(categoryNode); JsonNode wikiNode = mapper.createObjectNode(); ((ObjectNode) wikiNode).put("wikipediaExternalRef", pageId); ((ArrayNode) newNode).add(wikiNode); JsonNode scoreNode = mapper.createObjectNode(); ((ObjectNode) scoreNode).put("score", weight); ((ArrayNode) newNode).add(scoreNode); ((ArrayNode) annotNode).add(newNode); n++; } } JsonNode categoriesStandoffNode = mapper.createObjectNode(); ((ObjectNode) categoriesStandoffNode).put("$category", annotNode); if (standoffNode == null) { standoffNode = mapper.createArrayNode(); JsonNode annotationArrayNode = mapper.createArrayNode(); ((ArrayNode) annotationArrayNode).add(categoriesStandoffNode); ((ObjectNode) standoffNode).put("$standoff", annotationArrayNode); } else { JsonNode annotationArrayNode = standoffNode.findValue("$standoff"); ((ArrayNode) annotationArrayNode).add(categoriesStandoffNode); } } } } return standoffNode; } /** * Get the grobid quantities annotations and inject them in the document structure in a standoff node */ public JsonNode getStandoffQuantities(ObjectMapper mapper, String anhalyticsId, JsonNode standoffNode) throws Exception { String annotation = mm.getQuantitiesAnnotations(anhalyticsId) != null ? mm.getQuantitiesAnnotations(anhalyticsId).getJson():null; if ((annotation != null) && (annotation.trim().length() > 0)) { JsonNode jsonAnnotation = mapper.readTree(annotation); if ((jsonAnnotation != null) && (!jsonAnnotation.isMissingNode())) { JsonNode annotationNode = jsonAnnotation.findPath("annotation"); if ((annotationNode == null) || (annotationNode.isMissingNode())) return standoffNode; Iterator<JsonNode> iter0 = annotationNode.elements(); JsonNode annotNode = mapper.createArrayNode(); int n = 0; int m = 0; while (iter0.hasNext() //&& (n < MAX_QUANTITIES_INDEXED_PARAGRAPHS) && (m < MAX_INDEXED_QUANTITIES)) { JsonNode jsonLocalAnnotation = (JsonNode) iter0.next(); // we only get what should be searched together with the document metadata and content // so ignoring coordinates, offsets, ... // JsonNode quantities = jsonLocalAnnotation.findPath("quantities"); // if ((quantities == null) || (quantities.isMissingNode())) // continue; // JsonNode measurements = jsonLocalAnnotation.findPath("measurements"); // if ((measurements == null) || (measurements.isMissingNode())) // continue; // measurements is an array Iterator<JsonNode> iter = jsonLocalAnnotation.elements(); while (iter.hasNext()) { JsonNode piece = (JsonNode) iter.next(); //logger.info(piece.toString()); JsonNode typeNode = piece.findPath("type"); if ((typeNode == null) || (typeNode.isMissingNode())) continue; String type = typeNode.textValue(); //logger.info("type is " + type + " / " + piece.toString()); if (type.equals("value")) { JsonNode quantity = piece.findPath("quantity"); if ((quantity == null) || (quantity.isMissingNode())) continue; JsonNode typeMeasure = quantity.findPath("type"); //if no quantity type we move on. if ((typeMeasure == null) || (typeMeasure.isMissingNode())) continue; String valueTypeMeasure = typeMeasure.textValue(); JsonNode normalizedQuantity = quantity.findPath("normalizedQuantity"); //if no normalized value we continue over. if ((normalizedQuantity == null) || (normalizedQuantity.isMissingNode())) continue; Double val = normalizedQuantity.doubleValue(); JsonNode newNode = mapper.createObjectNode(); ((ObjectNode) newNode).put(valueTypeMeasure.replace(" ", "_"), val); ((ArrayNode) annotNode).add(newNode); //logger.info("type is " + type + " / " + annotNode.toString()); } else if (type.equals("interval")) { //logger.info("type is " + type + " / " + piece.toString()); JsonNode quantityMost = piece.findPath("quantityMost"); JsonNode quantityLeast = piece.findPath("quantityLeast"); String valueTypeMeasure = null; JsonNode range = null; Double valLeast; Double valMost; //System.out.println("interval"); if ((quantityMost != null) && (!quantityMost.isMissingNode())) { JsonNode typeMeasure = quantityMost.findPath("type"); if ((typeMeasure == null) || (typeMeasure.isMissingNode())) continue; valueTypeMeasure = typeMeasure.textValue(); JsonNode normalizedQuantityMost = quantityMost.findPath("normalizedQuantity"); if ((normalizedQuantityMost != null) && (!normalizedQuantityMost.isMissingNode())) { if (range == null) range = mapper.createObjectNode(); valMost = normalizedQuantityMost.doubleValue(); ((ObjectNode) range).put("lte", valMost); } } if ((quantityLeast != null) && (!quantityLeast.isMissingNode())) { JsonNode typeMeasure = quantityLeast.findPath("type"); typeMeasure = quantityLeast.findPath("type"); if ((typeMeasure == null) || (typeMeasure.isMissingNode())) continue; valueTypeMeasure = typeMeasure.textValue(); JsonNode normalizedQuantityLeast = quantityLeast.findPath("normalizedQuantity"); if ((normalizedQuantityLeast != null) && (!normalizedQuantityLeast.isMissingNode())) { if (range == null) range = mapper.createObjectNode(); valLeast = normalizedQuantityLeast.doubleValue(); ((ObjectNode) range).put("gte", valLeast); } } if (range != null) { JsonNode newNode = mapper.createObjectNode(); ((ObjectNode) newNode).put(valueTypeMeasure.replace(" ", "_")+"_range", range); ((ArrayNode) annotNode).add(newNode); //logger.info("type is " + type + " / " + annotNode.toString()); } } else if (type.equals("listc")) { JsonNode quantitiesList = piece.findPath("quantities"); if ((quantitiesList == null) || (quantitiesList.isMissingNode())) continue; // quantitiesList here is a list with a list of quantity values } m++; } //n++; } JsonNode quantitiesStandoffNode = mapper.createObjectNode(); ((ObjectNode) quantitiesStandoffNode).put("$quantities", annotNode); //JsonNode annotationArrayNode = mapper.createArrayNode(); //((ArrayNode) annotationArrayNode).add(quantitiesStandoffNode); //((ObjectNode) standoffNode).put("$standoff", annotationArrayNode); if (m > 0) { if (standoffNode == null) { standoffNode = mapper.createObjectNode(); JsonNode annotationArrayNode = mapper.createArrayNode(); ((ArrayNode) annotationArrayNode).add(quantitiesStandoffNode); ((ObjectNode) standoffNode).put("$standoff", annotationArrayNode); } else { JsonNode annotationArrayNode = standoffNode.findValue("$standoff"); ((ArrayNode) annotationArrayNode).add(quantitiesStandoffNode); } } } } return standoffNode; } private boolean filterDocuments(JsonNode jsonRoot) { // we want to filter out documents in the future... // paths are $TEI.$teiHeader.$sourceDesc.$biblStruct.$monogr.$imprint.$date // or $TEI.$teiHeader.$editionStmt.$edition.$date // now a piece of art of progamming : ;) boolean ok = true; JsonNode teiHeader = jsonRoot.findPath("$teiCorpus.$teiHeader"); if ((teiHeader != null) && (!teiHeader.isMissingNode())) { JsonNode sourceDesc = teiHeader.findPath("$sourceDesc"); if ((sourceDesc != null) && (!sourceDesc.isMissingNode())) { JsonNode biblStruct = sourceDesc.findPath("$biblStruct"); if ((biblStruct != null) && (!biblStruct.isMissingNode())) { JsonNode monogr = biblStruct.findPath("$monogr"); if ((monogr != null) && (!monogr.isMissingNode())) { JsonNode imprint = monogr.findPath("$imprint"); if ((imprint != null) && (!imprint.isMissingNode())) { JsonNode date = imprint.findPath("$date"); if ((date != null) && (!date.isMissingNode())) { if (date.isArray()) { Iterator<JsonNode> ite = ((ArrayNode) date).elements(); if (ite.hasNext()) { JsonNode dateVal = (JsonNode) ite.next(); String dateStr = dateVal.textValue(); try { Date theDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); Date today = new Date(); if (theDate.compareTo(today) > 0) { ok = false; } } catch (Exception e) { e.printStackTrace(); } } } } } } } } else { JsonNode editionStmt = teiHeader.findPath("$editionStmt"); if ((editionStmt != null) && (!editionStmt.isMissingNode())) { JsonNode edition = editionStmt.findPath("$edition"); if ((edition != null) && (!edition.isMissingNode())) { JsonNode date = edition.findPath("$date"); if ((date != null) && (!date.isMissingNode())) { if (date.isArray()) { Iterator<JsonNode> ite = ((ArrayNode) date).elements(); if (ite.hasNext()) { JsonNode dateVal = (JsonNode) ite.next(); String dateStr = dateVal.textValue(); try { Date theDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); Date today = new Date(); if (theDate.compareTo(today) > 0) { ok = false; } } catch (Exception e) { e.printStackTrace(); } } } } } } } } return ok; } /** * adds fullname node. */ private String addFullName(JsonNode theChild, ObjectMapper mapper) { String fullName = ""; if (theChild.isArray()) { String forename = ""; String surname = ""; Iterator<JsonNode> ite = theChild.elements(); while (ite.hasNext()) { JsonNode temp = ite.next(); if (temp.isObject()) { // get the text value of the array Iterator<JsonNode> ite2 = temp.path("$forename").elements(); while (ite2.hasNext()) { JsonNode temp2 = ite2.next(); if (forename != null) { forename += " " + temp2.textValue(); } else { forename = temp2.textValue(); } break; } // get the text value of the array ite2 = temp.path("$surname").elements(); while (ite2.hasNext()) { JsonNode temp2 = ite2.next(); surname = temp2.textValue(); break; } } } if (forename != null) { fullName = forename; } if (surname != null) { fullName += " " + surname; } if (fullName != null) { fullName = fullName.trim(); JsonNode newNode = mapper.createObjectNode(); JsonNode textNode = mapper.createArrayNode(); JsonNode tnode = new TextNode(fullName); ((ArrayNode) textNode).add(tnode); ((ObjectNode) newNode).put("$fullName", textNode); ((ArrayNode) theChild).add(newNode); } } return fullName; } }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * KDTreeNodeSplitter.java * Copyright (C) 1999-2007 University of Waikato */ package weka.core.neighboursearch.kdtrees; import weka.core.EuclideanDistance; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.RevisionHandler; import weka.core.RevisionUtils; import java.io.Serializable; import java.util.Enumeration; import java.util.Vector; /** * Class that splits up a KDTreeNode. * * @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz) * @version $Revision: 1.2 $ */ public abstract class KDTreeNodeSplitter implements Serializable, OptionHandler, RevisionHandler { /** The instances that'll be used for tree construction. */ protected Instances m_Instances; /** The distance function used for building the tree. */ protected EuclideanDistance m_EuclideanDistance; /** * The master index array that'll be reshuffled as nodes * are split and the tree is constructed. */ protected int[] m_InstList; /** * Stores whether if the width of a KDTree * node is normalized or not. */ protected boolean m_NormalizeNodeWidth; // Constants /** Index of min value in an array of attributes' range. */ public static final int MIN = EuclideanDistance.R_MIN; /** Index of max value in an array of attributes' range. */ public static final int MAX = EuclideanDistance.R_MAX; /** Index of width value (max-min) in an array of attributes' range. */ public static final int WIDTH = EuclideanDistance.R_WIDTH; /** * default constructor. */ public KDTreeNodeSplitter() { } /** * Creates a new instance of KDTreeNodeSplitter. * @param instList Reference of the master index array. * @param insts The set of training instances on which * the tree is built. * @param e The EuclideanDistance object that is used * in tree contruction. */ public KDTreeNodeSplitter(int[] instList, Instances insts, EuclideanDistance e) { m_InstList = instList; m_Instances = insts; m_EuclideanDistance = e; } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { return new Vector().elements(); } /** * Parses a given list of options. * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { } /** * Gets the current settings of the object. * * @return an array of strings suitable for passing to setOptions */ public String[] getOptions() { return new String[0]; } /** * Checks whether an object of this class has been correctly * initialized. Performs checks to see if all the necessary * things (master index array, training instances, distance * function) have been supplied or not. * @throws Exception If the object has not been correctly * initialized. */ protected void correctlyInitialized() throws Exception { if(m_Instances==null) throw new Exception("No instances supplied."); else if(m_InstList==null) throw new Exception("No instance list supplied."); else if(m_EuclideanDistance==null) throw new Exception("No Euclidean distance function supplied."); else if(m_Instances.numInstances() != m_InstList.length) throw new Exception("The supplied instance list doesn't seem to match " + "the supplied instances"); } /** * Splits a node into two. After splitting two new nodes are created * and correctly initialised. And, node.left and node.right are * set appropriately. * @param node The node to split. * @param numNodesCreated The number of nodes that so far have been * created for the tree, so that the newly created nodes are * assigned correct/meaningful node numbers/ids. * @param nodeRanges The attributes' range for the points inside * the node that is to be split. * @param universe The attributes' range for the whole * point-space. * @throws Exception If there is some problem in splitting the * given node. */ public abstract void splitNode(KDTreeNode node, int numNodesCreated, double[][] nodeRanges, double[][] universe) throws Exception; /** * Sets the training instances on which the tree is (or is * to be) built. * @param inst The training instances. */ public void setInstances(Instances inst) { m_Instances = inst; } /** * Sets the master index array containing indices of the * training instances. This array will be rearranged as * the tree is built, so that each node is assigned a * portion in this array which contain the instances * insides the node's region. * @param instList The master index array. */ public void setInstanceList(int[] instList) { m_InstList = instList; } /** * Sets the EuclideanDistance object to use for * splitting nodes. * @param func The EuclideanDistance object. */ public void setEuclideanDistanceFunction(EuclideanDistance func) { m_EuclideanDistance = func; } /** * Sets whether if a nodes region is normalized * or not. If set to true then, when selecting * the widest attribute/dimension for splitting, * the width of each attribute/dimension, * of the points inside the node's region, is * divided by the width of that * attribute/dimension for the whole point-space. * Thus, each attribute/dimension of that node * is normalized. * * @param normalize Should be true if * normalization is required. */ public void setNodeWidthNormalization(boolean normalize) { m_NormalizeNodeWidth = normalize; } /** * Returns the widest dimension. The width of each * dimension (for the points inside the node) is * normalized, if m_NormalizeNodeWidth is set to * true. * @param nodeRanges The attributes' range of the * points inside the node that is to be split. * @param universe The attributes' range for the * whole point-space. * @return The index of the attribute/dimension * in which the points of the node have widest * spread. */ protected int widestDim(double[][] nodeRanges, double[][] universe) { final int classIdx = m_Instances.classIndex(); double widest = 0.0; int w = -1; if (m_NormalizeNodeWidth) { for (int i = 0; i < nodeRanges.length; i++) { double newWidest = nodeRanges[i][WIDTH] / universe[i][WIDTH]; if (newWidest > widest) { if (i == classIdx) continue; widest = newWidest; w = i; } } } else { for (int i = 0; i < nodeRanges.length; i++) { if (nodeRanges[i][WIDTH] > widest) { if (i == classIdx) continue; widest = nodeRanges[i][WIDTH]; w = i; } } } return w; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 1.2 $"); } }
/** * 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.thrift; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.nio.ByteBuffer; import org.apache.thrift.protocol.TField; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.protocol.TStruct; public abstract class TUnion<T extends TUnion, F extends TFieldIdEnum> implements TBase<T, F> { protected Object value_; protected F setField_; protected TUnion() { setField_ = null; value_ = null; } protected TUnion(F setField, Object value) { setFieldValue(setField, value); } protected TUnion(TUnion<T, F> other) { if (!other.getClass().equals(this.getClass())) { throw new ClassCastException(); } setField_ = other.setField_; value_ = deepCopyObject(other.value_); } private static Object deepCopyObject(Object o) { if (o instanceof TBase) { return ((TBase)o).deepCopy(); } else if (o instanceof ByteBuffer) { return TBaseHelper.copyBinary((ByteBuffer)o); } else if (o instanceof List) { return deepCopyList((List)o); } else if (o instanceof Set) { return deepCopySet((Set)o); } else if (o instanceof Map) { return deepCopyMap((Map)o); } else { return o; } } private static Map deepCopyMap(Map<Object, Object> map) { Map copy = new HashMap(); for (Map.Entry<Object, Object> entry : map.entrySet()) { copy.put(deepCopyObject(entry.getKey()), deepCopyObject(entry.getValue())); } return copy; } private static Set deepCopySet(Set set) { Set copy = new HashSet(); for (Object o : set) { copy.add(deepCopyObject(o)); } return copy; } private static List deepCopyList(List list) { List copy = new ArrayList(list.size()); for (Object o : list) { copy.add(deepCopyObject(o)); } return copy; } public F getSetField() { return setField_; } public Object getFieldValue() { return value_; } public Object getFieldValue(F fieldId) { if (fieldId != setField_) { throw new IllegalArgumentException("Cannot get the value of field " + fieldId + " because union's set field is " + setField_); } return getFieldValue(); } public Object getFieldValue(int fieldId) { return getFieldValue(enumForId((short)fieldId)); } public boolean isSet() { return setField_ != null; } public boolean isSet(F fieldId) { return setField_ == fieldId; } public boolean isSet(int fieldId) { return isSet(enumForId((short)fieldId)); } public void read(TProtocol iprot) throws TException { setField_ = null; value_ = null; iprot.readStructBegin(); TField field = iprot.readFieldBegin(); value_ = readValue(iprot, field); if (value_ != null) { setField_ = enumForId(field.id); } iprot.readFieldEnd(); // this is so that we will eat the stop byte. we could put a check here to // make sure that it actually *is* the stop byte, but it's faster to do it // this way. iprot.readFieldBegin(); iprot.readStructEnd(); } public void setFieldValue(F fieldId, Object value) { checkType(fieldId, value); setField_ = fieldId; value_ = value; } public void setFieldValue(int fieldId, Object value) { setFieldValue(enumForId((short)fieldId), value); } public void write(TProtocol oprot) throws TException { if (getSetField() == null || getFieldValue() == null) { throw new TProtocolException("Cannot write a TUnion with no set value!"); } oprot.writeStructBegin(getStructDesc()); oprot.writeFieldBegin(getFieldDesc(setField_)); writeValue(oprot); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } /** * Implementation should be generated so that we can efficiently type check * various values. * @param setField * @param value */ protected abstract void checkType(F setField, Object value) throws ClassCastException; /** * Implementation should be generated to read the right stuff from the wire * based on the field header. * @param field * @return */ protected abstract Object readValue(TProtocol iprot, TField field) throws TException; protected abstract void writeValue(TProtocol oprot) throws TException; protected abstract TStruct getStructDesc(); protected abstract TField getFieldDesc(F setField); protected abstract F enumForId(short id); @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<"); sb.append(this.getClass().getSimpleName()); sb.append(" "); if (getSetField() != null) { Object v = getFieldValue(); sb.append(getFieldDesc(getSetField()).name); sb.append(":"); if(v instanceof ByteBuffer) { TBaseHelper.toString((ByteBuffer)v, sb); } else { sb.append(v.toString()); } } sb.append(">"); return sb.toString(); } public final void clear() { this.setField_ = null; this.value_ = null; } }
package co.edu.usbcali.presentation.backingBeans; import java.io.Serializable; import java.util.List; import java.util.TimeZone; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.event.ActionEvent; import org.primefaces.component.commandbutton.CommandButton; import org.primefaces.component.inputtext.InputText; import org.primefaces.event.RowEditEvent; import co.edu.usbcali.exceptions.ZMessManager; import co.edu.usbcali.modelo.Anexos; import co.edu.usbcali.modelo.dto.AnexosDTO; import co.edu.usbcali.presentation.businessDelegate.IBusinessDelegatorView; import co.edu.usbcali.utilities.FacesUtils; /** * @author Zathura Code Generator http://code.google.com/p/zathura * www.zathuracode.org * */ @ManagedBean @ViewScoped public class AnexosView implements Serializable { private static final long serialVersionUID = 1L; private InputText txtArchivo; private InputText txtFormato; private InputText txtNombre; private InputText txtUrl; private InputText txtCodigoArti_Articulos; private InputText txtCodigoAnexo; private CommandButton btnSave; private CommandButton btnModify; private CommandButton btnDelete; private CommandButton btnClear; private List<AnexosDTO> data; private AnexosDTO selectedAnexos; private Anexos entity; private boolean showDialog; @ManagedProperty(value = "#{BusinessDelegatorView}") private IBusinessDelegatorView businessDelegatorView; public AnexosView() { super(); } public void rowEventListener(RowEditEvent e) { try { AnexosDTO anexosDTO = (AnexosDTO) e.getObject(); if (txtArchivo == null) { txtArchivo = new InputText(); } txtArchivo.setValue(anexosDTO.getArchivo()); if (txtFormato == null) { txtFormato = new InputText(); } txtFormato.setValue(anexosDTO.getFormato()); if (txtNombre == null) { txtNombre = new InputText(); } txtNombre.setValue(anexosDTO.getNombre()); if (txtUrl == null) { txtUrl = new InputText(); } txtUrl.setValue(anexosDTO.getUrl()); if (txtCodigoArti_Articulos == null) { txtCodigoArti_Articulos = new InputText(); } txtCodigoArti_Articulos.setValue(anexosDTO.getCodigoArti_Articulos()); if (txtCodigoAnexo == null) { txtCodigoAnexo = new InputText(); } txtCodigoAnexo.setValue(anexosDTO.getCodigoAnexo()); Long codigoAnexo = FacesUtils.checkLong(txtCodigoAnexo); entity = businessDelegatorView.getAnexos(codigoAnexo); action_modify(); } catch (Exception ex) { } } public String action_new() { action_clear(); selectedAnexos = null; setShowDialog(true); return ""; } public String action_clear() { entity = null; selectedAnexos = null; if (txtArchivo != null) { txtArchivo.setValue(null); txtArchivo.setDisabled(true); } if (txtFormato != null) { txtFormato.setValue(null); txtFormato.setDisabled(true); } if (txtNombre != null) { txtNombre.setValue(null); txtNombre.setDisabled(true); } if (txtUrl != null) { txtUrl.setValue(null); txtUrl.setDisabled(true); } if (txtCodigoArti_Articulos != null) { txtCodigoArti_Articulos.setValue(null); txtCodigoArti_Articulos.setDisabled(true); } if (txtCodigoAnexo != null) { txtCodigoAnexo.setValue(null); txtCodigoAnexo.setDisabled(false); } if (btnSave != null) { btnSave.setDisabled(true); } if (btnDelete != null) { btnDelete.setDisabled(true); } return ""; } public void listener_txtId() { try { Long codigoAnexo = FacesUtils.checkLong(txtCodigoAnexo); entity = (codigoAnexo != null) ? businessDelegatorView.getAnexos(codigoAnexo) : null; } catch (Exception e) { entity = null; } if (entity == null) { txtArchivo.setDisabled(false); txtFormato.setDisabled(false); txtNombre.setDisabled(false); txtUrl.setDisabled(false); txtCodigoArti_Articulos.setDisabled(false); txtCodigoAnexo.setDisabled(false); btnSave.setDisabled(false); } else { txtArchivo.setValue(entity.getArchivo()); txtArchivo.setDisabled(false); txtFormato.setValue(entity.getFormato()); txtFormato.setDisabled(false); txtNombre.setValue(entity.getNombre()); txtNombre.setDisabled(false); txtUrl.setValue(entity.getUrl()); txtUrl.setDisabled(false); txtCodigoArti_Articulos.setValue(entity.getArticulos() .getCodigoArti()); txtCodigoArti_Articulos.setDisabled(false); txtCodigoAnexo.setValue(entity.getCodigoAnexo()); txtCodigoAnexo.setDisabled(true); btnSave.setDisabled(false); if (btnDelete != null) { btnDelete.setDisabled(false); } } } public String action_edit(ActionEvent evt) { selectedAnexos = (AnexosDTO) (evt.getComponent().getAttributes() .get("selectedAnexos")); txtArchivo.setValue(selectedAnexos.getArchivo()); txtArchivo.setDisabled(false); txtFormato.setValue(selectedAnexos.getFormato()); txtFormato.setDisabled(false); txtNombre.setValue(selectedAnexos.getNombre()); txtNombre.setDisabled(false); txtUrl.setValue(selectedAnexos.getUrl()); txtUrl.setDisabled(false); txtCodigoArti_Articulos.setValue(selectedAnexos.getCodigoArti_Articulos()); txtCodigoArti_Articulos.setDisabled(false); txtCodigoAnexo.setValue(selectedAnexos.getCodigoAnexo()); txtCodigoAnexo.setDisabled(true); btnSave.setDisabled(false); setShowDialog(true); return ""; } public String action_save() { try { if ((selectedAnexos == null) && (entity == null)) { action_create(); } else { action_modify(); } data = null; } catch (Exception e) { FacesUtils.addErrorMessage(e.getMessage()); } return ""; } public String action_create() { try { entity = new Anexos(); Long codigoAnexo = FacesUtils.checkLong(txtCodigoAnexo); entity.setArchivo(FacesUtils.checkString(txtArchivo)); entity.setCodigoAnexo(codigoAnexo); entity.setFormato(FacesUtils.checkString(txtFormato)); entity.setNombre(FacesUtils.checkString(txtNombre)); entity.setUrl(FacesUtils.checkString(txtUrl)); entity.setArticulos((FacesUtils.checkLong(txtCodigoArti_Articulos) != null) ? businessDelegatorView.getArticulos(FacesUtils.checkLong( txtCodigoArti_Articulos)) : null); businessDelegatorView.saveAnexos(entity); FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYSAVED); action_clear(); } catch (Exception e) { entity = null; FacesUtils.addErrorMessage(e.getMessage()); } return ""; } public String action_modify() { try { if (entity == null) { Long codigoAnexo = new Long(selectedAnexos.getCodigoAnexo()); entity = businessDelegatorView.getAnexos(codigoAnexo); } entity.setArchivo(FacesUtils.checkString(txtArchivo)); entity.setFormato(FacesUtils.checkString(txtFormato)); entity.setNombre(FacesUtils.checkString(txtNombre)); entity.setUrl(FacesUtils.checkString(txtUrl)); entity.setArticulos((FacesUtils.checkLong(txtCodigoArti_Articulos) != null) ? businessDelegatorView.getArticulos(FacesUtils.checkLong( txtCodigoArti_Articulos)) : null); businessDelegatorView.updateAnexos(entity); FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED); } catch (Exception e) { data = null; FacesUtils.addErrorMessage(e.getMessage()); } return ""; } public String action_delete_datatable(ActionEvent evt) { try { selectedAnexos = (AnexosDTO) (evt.getComponent().getAttributes() .get("selectedAnexos")); Long codigoAnexo = new Long(selectedAnexos.getCodigoAnexo()); entity = businessDelegatorView.getAnexos(codigoAnexo); action_delete(); } catch (Exception e) { FacesUtils.addErrorMessage(e.getMessage()); } return ""; } public String action_delete_master() { try { Long codigoAnexo = FacesUtils.checkLong(txtCodigoAnexo); entity = businessDelegatorView.getAnexos(codigoAnexo); action_delete(); } catch (Exception e) { FacesUtils.addErrorMessage(e.getMessage()); } return ""; } public void action_delete() throws Exception { try { businessDelegatorView.deleteAnexos(entity); FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED); action_clear(); data = null; } catch (Exception e) { throw e; } } public String action_closeDialog() { setShowDialog(false); action_clear(); return ""; } public String actionDeleteDataTableEditable(ActionEvent evt) { try { selectedAnexos = (AnexosDTO) (evt.getComponent().getAttributes() .get("selectedAnexos")); Long codigoAnexo = new Long(selectedAnexos.getCodigoAnexo()); entity = businessDelegatorView.getAnexos(codigoAnexo); businessDelegatorView.deleteAnexos(entity); data.remove(selectedAnexos); FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED); action_clear(); } catch (Exception e) { FacesUtils.addErrorMessage(e.getMessage()); } return ""; } public String action_modifyWitDTO(String archivo, Long codigoAnexo, String formato, String nombre, String url, Long codigoArti_Articulos) throws Exception { try { entity.setArchivo(FacesUtils.checkString(archivo)); entity.setFormato(FacesUtils.checkString(formato)); entity.setNombre(FacesUtils.checkString(nombre)); entity.setUrl(FacesUtils.checkString(url)); businessDelegatorView.updateAnexos(entity); FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED); } catch (Exception e) { //renderManager.getOnDemandRenderer("AnexosView").requestRender(); FacesUtils.addErrorMessage(e.getMessage()); throw e; } return ""; } public InputText getTxtArchivo() { return txtArchivo; } public void setTxtArchivo(InputText txtArchivo) { this.txtArchivo = txtArchivo; } public InputText getTxtFormato() { return txtFormato; } public void setTxtFormato(InputText txtFormato) { this.txtFormato = txtFormato; } public InputText getTxtNombre() { return txtNombre; } public void setTxtNombre(InputText txtNombre) { this.txtNombre = txtNombre; } public InputText getTxtUrl() { return txtUrl; } public void setTxtUrl(InputText txtUrl) { this.txtUrl = txtUrl; } public InputText getTxtCodigoArti_Articulos() { return txtCodigoArti_Articulos; } public void setTxtCodigoArti_Articulos(InputText txtCodigoArti_Articulos) { this.txtCodigoArti_Articulos = txtCodigoArti_Articulos; } public InputText getTxtCodigoAnexo() { return txtCodigoAnexo; } public void setTxtCodigoAnexo(InputText txtCodigoAnexo) { this.txtCodigoAnexo = txtCodigoAnexo; } public List<AnexosDTO> getData() { try { if (data == null) { data = businessDelegatorView.getDataAnexos(); } } catch (Exception e) { e.printStackTrace(); } return data; } public void setData(List<AnexosDTO> anexosDTO) { this.data = anexosDTO; } public AnexosDTO getSelectedAnexos() { return selectedAnexos; } public void setSelectedAnexos(AnexosDTO anexos) { this.selectedAnexos = anexos; } public CommandButton getBtnSave() { return btnSave; } public void setBtnSave(CommandButton btnSave) { this.btnSave = btnSave; } public CommandButton getBtnModify() { return btnModify; } public void setBtnModify(CommandButton btnModify) { this.btnModify = btnModify; } public CommandButton getBtnDelete() { return btnDelete; } public void setBtnDelete(CommandButton btnDelete) { this.btnDelete = btnDelete; } public CommandButton getBtnClear() { return btnClear; } public void setBtnClear(CommandButton btnClear) { this.btnClear = btnClear; } public TimeZone getTimeZone() { return java.util.TimeZone.getDefault(); } public IBusinessDelegatorView getBusinessDelegatorView() { return businessDelegatorView; } public void setBusinessDelegatorView( IBusinessDelegatorView businessDelegatorView) { this.businessDelegatorView = businessDelegatorView; } public boolean isShowDialog() { return showDialog; } public void setShowDialog(boolean showDialog) { this.showDialog = showDialog; } }
/* * Copyright (c) 2016 Gridtec. 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 at.gridtec.lambda4j.function.tri.conversion; import at.gridtec.lambda4j.Lambda; import at.gridtec.lambda4j.consumer.tri.TriIntConsumer; import at.gridtec.lambda4j.function.bi.conversion.BiIntToLongFunction; import at.gridtec.lambda4j.function.conversion.BooleanToIntFunction; import at.gridtec.lambda4j.function.conversion.ByteToIntFunction; import at.gridtec.lambda4j.function.conversion.CharToIntFunction; import at.gridtec.lambda4j.function.conversion.FloatToIntFunction; import at.gridtec.lambda4j.function.conversion.IntToLongFunction2; import at.gridtec.lambda4j.function.conversion.LongToByteFunction; import at.gridtec.lambda4j.function.conversion.LongToCharFunction; import at.gridtec.lambda4j.function.conversion.LongToFloatFunction; import at.gridtec.lambda4j.function.conversion.LongToShortFunction; import at.gridtec.lambda4j.function.conversion.ShortToIntFunction; import at.gridtec.lambda4j.function.tri.TriFunction; import at.gridtec.lambda4j.function.tri.TriIntFunction; import at.gridtec.lambda4j.function.tri.to.ToLongTriFunction; import at.gridtec.lambda4j.operator.ternary.IntTernaryOperator; import at.gridtec.lambda4j.operator.ternary.LongTernaryOperator; import at.gridtec.lambda4j.predicate.tri.TriIntPredicate; import org.apache.commons.lang3.tuple.Triple; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.DoubleToIntFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.LongConsumer; import java.util.function.LongFunction; import java.util.function.LongPredicate; import java.util.function.LongToDoubleFunction; import java.util.function.LongToIntFunction; import java.util.function.LongUnaryOperator; import java.util.function.ToIntFunction; /** * Represents an operation that accepts three {@code int}-valued input arguments and produces a * {@code long}-valued result. * This is a primitive specialization of {@link TriFunction}. * <p> * This is a {@link FunctionalInterface} whose functional method is {@link #applyAsLong(int, int, int)}. * * @see TriFunction */ @SuppressWarnings("unused") @FunctionalInterface public interface TriIntToLongFunction extends Lambda { /** * Constructs a {@link TriIntToLongFunction} based on a lambda expression or a method reference. Thereby the given * lambda expression or method reference is returned on an as-is basis to implicitly transform it to the desired * type. With this method, it is possible to ensure that correct type is used from lambda expression or method * reference. * * @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method} * @return A {@code TriIntToLongFunction} from given lambda expression or method reference. * @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given, * {@code null} will be returned. * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax">Lambda * Expression</a> * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method Reference</a> */ static TriIntToLongFunction of(@Nullable final TriIntToLongFunction expression) { return expression; } /** * Calls the given {@link TriIntToLongFunction} with the given arguments and returns its result. * * @param function The function to be called * @param value1 The first argument to the function * @param value2 The second argument to the function * @param value3 The third argument to the function * @return The result from the given {@code TriIntToLongFunction}. * @throws NullPointerException If given argument is {@code null} */ static long call(@Nonnull final TriIntToLongFunction function, int value1, int value2, int value3) { Objects.requireNonNull(function); return function.applyAsLong(value1, value2, value3); } /** * Creates a {@link TriIntToLongFunction} which uses the {@code first} parameter of this one as argument for the * given {@link IntToLongFunction}. * * @param function The function which accepts the {@code first} parameter of this one * @return Creates a {@code TriIntToLongFunction} which uses the {@code first} parameter of this one as argument for * the given {@code IntToLongFunction}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull static TriIntToLongFunction onlyFirst(@Nonnull final IntToLongFunction function) { Objects.requireNonNull(function); return (value1, value2, value3) -> function.applyAsLong(value1); } /** * Creates a {@link TriIntToLongFunction} which uses the {@code second} parameter of this one as argument for the * given {@link IntToLongFunction}. * * @param function The function which accepts the {@code second} parameter of this one * @return Creates a {@code TriIntToLongFunction} which uses the {@code second} parameter of this one as argument * for the given {@code IntToLongFunction}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull static TriIntToLongFunction onlySecond(@Nonnull final IntToLongFunction function) { Objects.requireNonNull(function); return (value1, value2, value3) -> function.applyAsLong(value2); } /** * Creates a {@link TriIntToLongFunction} which uses the {@code third} parameter of this one as argument for the * given {@link IntToLongFunction}. * * @param function The function which accepts the {@code third} parameter of this one * @return Creates a {@code TriIntToLongFunction} which uses the {@code third} parameter of this one as argument for * the given {@code IntToLongFunction}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull static TriIntToLongFunction onlyThird(@Nonnull final IntToLongFunction function) { Objects.requireNonNull(function); return (value1, value2, value3) -> function.applyAsLong(value3); } /** * Creates a {@link TriIntToLongFunction} which always returns a given value. * * @param ret The return value for the constant * @return A {@code TriIntToLongFunction} which always returns a given value. */ @Nonnull static TriIntToLongFunction constant(long ret) { return (value1, value2, value3) -> ret; } /** * Applies this function to the given arguments. * * @param value1 The first argument to the function * @param value2 The second argument to the function * @param value3 The third argument to the function * @return The return value from the function, which is its result. */ long applyAsLong(int value1, int value2, int value3); /** * Applies this function partially to some arguments of this one, producing a {@link BiIntToLongFunction} as result. * * @param value1 The first argument to this function used to partially apply this function * @return A {@code BiIntToLongFunction} that represents this function partially applied the some arguments. */ @Nonnull default BiIntToLongFunction papplyAsLong(int value1) { return (value2, value3) -> this.applyAsLong(value1, value2, value3); } /** * Applies this function partially to some arguments of this one, producing a {@link IntToLongFunction2} as result. * * @param value1 The first argument to this function used to partially apply this function * @param value2 The second argument to this function used to partially apply this function * @return A {@code IntToLongFunction2} that represents this function partially applied the some arguments. */ @Nonnull default IntToLongFunction2 papplyAsLong(int value1, int value2) { return (value3) -> this.applyAsLong(value1, value2, value3); } /** * Returns the number of arguments for this function. * * @return The number of arguments for this function. * @implSpec The default implementation always returns {@code 3}. */ @Nonnegative default int arity() { return 3; } /** * Returns a composed {@link ToLongTriFunction} that first applies the {@code before} functions to its input, and * then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * * @param <A> The type of the argument to the first given function, and of composed function * @param <B> The type of the argument to the second given function, and of composed function * @param <C> The type of the argument to the third given function, and of composed function * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code ToLongTriFunction} that first applies the {@code before} functions to its input, and * then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is able to handle every type. */ @Nonnull default <A, B, C> ToLongTriFunction<A, B, C> compose(@Nonnull final ToIntFunction<? super A> before1, @Nonnull final ToIntFunction<? super B> before2, @Nonnull final ToIntFunction<? super C> before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (a, b, c) -> applyAsLong(before1.applyAsInt(a), before2.applyAsInt(b), before3.applyAsInt(c)); } /** * Returns a composed {@link TriBooleanToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code boolean} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriBooleanToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * boolean}. */ @Nonnull default TriBooleanToLongFunction composeFromBoolean(@Nonnull final BooleanToIntFunction before1, @Nonnull final BooleanToIntFunction before2, @Nonnull final BooleanToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriByteToLongFunction} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code byte} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriByteToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * byte}. */ @Nonnull default TriByteToLongFunction composeFromByte(@Nonnull final ByteToIntFunction before1, @Nonnull final ByteToIntFunction before2, @Nonnull final ByteToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriCharToLongFunction} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code char} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriCharToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * char}. */ @Nonnull default TriCharToLongFunction composeFromChar(@Nonnull final CharToIntFunction before1, @Nonnull final CharToIntFunction before2, @Nonnull final CharToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriDoubleToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code double} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriDoubleToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * double}. */ @Nonnull default TriDoubleToLongFunction composeFromDouble(@Nonnull final DoubleToIntFunction before1, @Nonnull final DoubleToIntFunction before2, @Nonnull final DoubleToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriFloatToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code float} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriFloatToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * float}. */ @Nonnull default TriFloatToLongFunction composeFromFloat(@Nonnull final FloatToIntFunction before1, @Nonnull final FloatToIntFunction before2, @Nonnull final FloatToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriIntToLongFunction} that first applies the {@code before} operators to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code int} input, * before this primitive function is executed. * * @param before1 The first operator to apply before this function is applied * @param before2 The second operator to apply before this function is applied * @param before3 The third operator to apply before this function is applied * @return A composed {@code TriIntToLongFunction} that first applies the {@code before} operators to its input, and * then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * int}. */ @Nonnull default TriIntToLongFunction composeFromInt(@Nonnull final IntUnaryOperator before1, @Nonnull final IntUnaryOperator before2, @Nonnull final IntUnaryOperator before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link LongTernaryOperator} that first applies the {@code before} functions to * its input, and then applies this function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * This method is just convenience, to provide the ability to execute an operation which accepts {@code long} input, * before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code LongTernaryOperator} that first applies the {@code before} functions to its input, and * then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * long}. */ @Nonnull default LongTernaryOperator composeFromLong(@Nonnull final LongToIntFunction before1, @Nonnull final LongToIntFunction before2, @Nonnull final LongToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriShortToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. If evaluation of either operation throws an exception, it is * relayed to the caller of the composed operation. This method is just convenience, to provide the ability to * execute an operation which accepts {@code short} input, before this primitive function is executed. * * @param before1 The first function to apply before this function is applied * @param before2 The second function to apply before this function is applied * @param before3 The third function to apply before this function is applied * @return A composed {@code TriShortToLongFunction} that first applies the {@code before} functions to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * short}. */ @Nonnull default TriShortToLongFunction composeFromShort(@Nonnull final ShortToIntFunction before1, @Nonnull final ShortToIntFunction before2, @Nonnull final ShortToIntFunction before3) { Objects.requireNonNull(before1); Objects.requireNonNull(before2); Objects.requireNonNull(before3); return (value1, value2, value3) -> applyAsLong(before1.applyAsInt(value1), before2.applyAsInt(value2), before3.applyAsInt(value3)); } /** * Returns a composed {@link TriIntFunction} that first applies this function to its input, and then applies the * {@code after} function to the result. * If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation. * * @param <S> The type of return value from the {@code after} function, and of the composed function * @param after The function to apply after this function is applied * @return A composed {@code TriIntFunction} that first applies this function to its input, and then applies the * {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is able to return every type. */ @Nonnull default <S> TriIntFunction<S> andThen(@Nonnull final LongFunction<? extends S> after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.apply(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntPredicate} that first applies this function to its input, and then applies the * {@code after} predicate to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code boolean}. * * @param after The predicate to apply after this function is applied * @return A composed {@code TriIntPredicate} that first applies this function to its input, and then applies the * {@code after} predicate to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * boolean}. */ @Nonnull default TriIntPredicate andThenToBoolean(@Nonnull final LongPredicate after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.test(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntToByteFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code byte}. * * @param after The function to apply after this function is applied * @return A composed {@code TriIntToByteFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * byte}. */ @Nonnull default TriIntToByteFunction andThenToByte(@Nonnull final LongToByteFunction after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsByte(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntToCharFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code char}. * * @param after The function to apply after this function is applied * @return A composed {@code TriIntToCharFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * char}. */ @Nonnull default TriIntToCharFunction andThenToChar(@Nonnull final LongToCharFunction after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsChar(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntToDoubleFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code double}. * * @param after The function to apply after this function is applied * @return A composed {@code TriIntToDoubleFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * double}. */ @Nonnull default TriIntToDoubleFunction andThenToDouble(@Nonnull final LongToDoubleFunction after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsDouble(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntToFloatFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code float}. * * @param after The function to apply after this function is applied * @return A composed {@code TriIntToFloatFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * float}. */ @Nonnull default TriIntToFloatFunction andThenToFloat(@Nonnull final LongToFloatFunction after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsFloat(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link IntTernaryOperator} that first applies this function to its input, and then applies the * {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to the * caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code int}. * * @param after The function to apply after this function is applied * @return A composed {@code IntTernaryOperator} that first applies this function to its input, and then applies the * {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * int}. */ @Nonnull default IntTernaryOperator andThenToInt(@Nonnull final LongToIntFunction after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsInt(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntToLongFunction} that first applies this function to its input, and then applies * the {@code after} operator to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code long}. * * @param after The operator to apply after this function is applied * @return A composed {@code TriIntToLongFunction} that first applies this function to its input, and then applies * the {@code after} operator to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * long}. */ @Nonnull default TriIntToLongFunction andThenToLong(@Nonnull final LongUnaryOperator after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsLong(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntToShortFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to * the caller of the composed operation. This method is just convenience, to provide the ability to transform this * primitive function to an operation returning {@code short}. * * @param after The function to apply after this function is applied * @return A composed {@code TriIntToShortFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * short}. */ @Nonnull default TriIntToShortFunction andThenToShort(@Nonnull final LongToShortFunction after) { Objects.requireNonNull(after); return (value1, value2, value3) -> after.applyAsShort(applyAsLong(value1, value2, value3)); } /** * Returns a composed {@link TriIntConsumer} that fist applies this function to its input, and then consumes the * result using the given {@link LongConsumer}. If evaluation of either operation throws an exception, it is relayed * to the caller of the composed operation. * * @param consumer The operation which consumes the result from this operation * @return A composed {@code TriIntConsumer} that first applies this function to its input, and then consumes the * result using the given {@code LongConsumer}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull default TriIntConsumer consume(@Nonnull final LongConsumer consumer) { Objects.requireNonNull(consumer); return (value1, value2, value3) -> consumer.accept(applyAsLong(value1, value2, value3)); } /** * Returns a memoized (caching) version of this {@link TriIntToLongFunction}. Whenever it is called, the mapping * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the * memoized value instead of computing the return value again. * <p> * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values * forever. * * @return A memoized (caching) version of this {@code TriIntToLongFunction}. * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the * resulting memoized function, as the cache used internally does not permit {@code null} keys or values. * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it * thread-safe. */ @Nonnull default TriIntToLongFunction memoized() { if (isMemoized()) { return this; } else { final Map<Triple<Integer, Integer, Integer>, Long> cache = new ConcurrentHashMap<>(); final Object lock = new Object(); return (TriIntToLongFunction & Memoized) (value1, value2, value3) -> { final long returnValue; synchronized (lock) { returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3), key -> applyAsLong(key.getLeft(), key.getMiddle(), key.getRight())); } return returnValue; }; } } /** * Returns a composed {@link TriFunction} which represents this {@link TriIntToLongFunction}. Thereby the primitive * input argument for this function is autoboxed. This method provides the possibility to use this * {@code TriIntToLongFunction} with methods provided by the {@code JDK}. * * @return A composed {@code TriFunction} which represents this {@code TriIntToLongFunction}. */ @Nonnull default TriFunction<Integer, Integer, Integer, Long> boxed() { return this::applyAsLong; } }
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jitsi.impl.neomedia.audiolevel; import javax.media.*; import org.jitsi.service.neomedia.event.*; /** * The class implements an audio level measurement thread. The thread will * measure new data every time it is added through the <tt>addData()</tt> method * and would then deliver it to a registered listener if any. (No measurement * would be performed until we have a <tt>levelListener</tt>). We use a * separate thread so that we could compute and deliver audio levels in a way * that won't delay the media processing thread. * <p> * Note that, for performance reasons this class is not 100% thread safe and you * should not modify add or remove audio listeners in this dispatcher in the * notification thread (i.e. in the thread where you were notified of an audio * level change). * * @author Damian Minkov * @author Emil Ivov * @author Lyubomir Marinov */ public class AudioLevelEventDispatcher { /** * The interval of time in milliseconds which the Thread of * AudioLevelEventDispatcher is to idly wait for data to be provided for * audio level calculation before it exits. */ private static final long IDLE_TIMEOUT = 30 * 1000; /** * The <tt>AudioLevelMap</tt> in which the audio calculations run by this * <tt>AudioLevelEventDispatcher</tt> are to be cached in addition to * dispatching them to {@link #listener}. */ private AudioLevelMap cache = null; /** * The data to process. */ private byte[] data = null; /** * The length of the data last recorded in the <tt>data</tt> array. */ private int dataLength = 0; /** * This is the last level we fired. */ private int lastLevel = 0; /** * The listener which is interested in audio level changes. */ private SimpleAudioLevelListener listener; /** * The SSRC of the stream we are measuring that we should use as a key for * entries of the levelMap level cache. */ private long ssrc = -1; /** * The <tt>Thread</tt> which runs the actual audio level calculations and * dispatches to {@link #listener}. */ private Thread thread; /** * The name of the <tt>Thread</tt> which is to run the actual audio level * calculations and to dispatch to {@link #listener}. */ private final String threadName; /** * Initializes a new <tt>AudioLevelEventDispatcher</tt> instance which is to * use a specific name for its <tt>Thread</tt> which is to run the actual * audio level calculations and to dispatch to its * <tt>SimpleAudioLevelListener</tt> * * @param threadName */ public AudioLevelEventDispatcher(String threadName) { this.threadName = threadName; } /** * Runs the actual audio level calculations and dispatches to the * {@link #listener}. */ private void run() { long idleTimeoutStart = -1; while (true) { SimpleAudioLevelListener listener; AudioLevelMap cache; long ssrc; byte[] data; int dataLength; synchronized(this) { if (!Thread.currentThread().equals(thread)) break; listener = this.listener; cache = this.cache; ssrc = this.ssrc; /* * If no one is interested in the audio level, do not even keep * the Thread waiting. */ if ((listener == null) && ((cache == null) || (ssrc == -1))) break; data = this.data; dataLength = this.dataLength; /* * If there is no data to calculate the audio level of, wait for * such data to be provided. */ if ((data == null) || (dataLength < 1)) { // The current thread is idle. if (idleTimeoutStart == -1) idleTimeoutStart = System.currentTimeMillis(); else if ((System.currentTimeMillis() - idleTimeoutStart) >= IDLE_TIMEOUT) break; boolean interrupted = false; try { wait(IDLE_TIMEOUT); } catch (InterruptedException ie) { interrupted = true; } if (interrupted) Thread.currentThread().interrupt(); continue; } // The values of data and dataLength seem valid so consume them. this.data = null; this.dataLength = 0; // The current thread is no longer idle. idleTimeoutStart = -1; } int newLevel = AudioLevelCalculator.calculateSoundPressureLevel( data, 0, dataLength, SimpleAudioLevelListener.MIN_LEVEL, SimpleAudioLevelListener.MAX_LEVEL, lastLevel); /* * In order to try to mitigate the issue with allocating data, try * to return the one which we have just calculated the audio level * of. */ synchronized (this) { if ((this.data == null) && (this.listener == null) && ((this.cache == null) || (this.ssrc == -1))) this.data = data; } try { // Cache the newLevel if requested. if ((cache != null) && (ssrc != -1)) cache.putLevel(ssrc, newLevel); // Notify the listener about the newLevel if requested. if (listener != null) listener.audioLevelChanged(newLevel); } finally { lastLevel = newLevel; } } } /** * Adds data to be processed. * * @param buffer the data that we'd like to queue for processing. */ public synchronized void addData(Buffer buffer) { /* * If no one is interested in the audio level, do not even add the * Buffer data. */ if ((listener == null) && ((cache == null) || (ssrc == -1))) return; dataLength = buffer.getLength(); if (dataLength > 0) { if((data == null) || (data.length < dataLength)) data = new byte[dataLength]; Object bufferData = buffer.getData(); if (bufferData != null) { System.arraycopy( bufferData, buffer.getOffset(), data, 0, dataLength); } if (thread == null) startThread(); else notify(); } } /** * Sets the new listener that will be gathering all events from this * dispatcher. * * @param listener the listener that we will be notifying or <tt>null</tt> * if we are to remove it. */ public synchronized void setAudioLevelListener( SimpleAudioLevelListener listener) { if (this.listener != listener) { this.listener = listener; startOrNotifyThread(); } } /** * Sets an <tt>AudioLevelMap</tt> that this dispatcher could use to cache * levels it's measuring in addition to simply delivering them to a * listener. * * @param cache the <tt>AudioLevelMap</tt> where this dispatcher should * cache measured results. * @param ssrc the SSRC key where entries should be logged */ public synchronized void setAudioLevelCache(AudioLevelMap cache, long ssrc) { if ((this.cache != cache) || (this.ssrc != ssrc)) { this.cache = cache; this.ssrc = ssrc; startOrNotifyThread(); } } /** * Starts the <tt>Thread</tt> which is to run the audio level calculations * and to dispatch to {@link #listener} if necessary or notifies it about a * change it the state on which it depends. */ private synchronized void startOrNotifyThread() { if ((this.listener == null) && ((cache == null) || (ssrc == -1))) { thread = null; notify(); } else if ((data != null) && (dataLength > 0)) { if (thread == null) startThread(); else notify(); } } /** * Starts the <tt>Thread</tt> which is to run the audio level calculations * and to dispatch to {@link #listener}. */ private synchronized void startThread() { thread = new Thread() { @Override public void run() { try { AudioLevelEventDispatcher.this.run(); } finally { synchronized (AudioLevelEventDispatcher.this) { if (Thread.currentThread().equals(thread)) thread = null; /* * If the thread of this AudioLevelEventDispatcher * is dying yet the state suggests that it should be * running, restart it. */ if ((thread == null) && ((listener != null) || ((cache != null) && (ssrc != -1))) && (data != null) && (dataLength > 0)) startThread(); } } } }; thread.setDaemon(true); if (threadName != null) thread.setName(threadName); thread.start(); } }