code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/* * 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.intellij.psi.formatter.java; import com.intellij.formatting.*; import com.intellij.formatting.alignment.AlignmentStrategy; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.JavaCodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.formatter.common.AbstractBlock; import com.intellij.psi.formatter.java.wrap.JavaWrapManager; import com.intellij.psi.formatter.java.wrap.ReservedWrapsProvider; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.impl.source.tree.java.ClassElement; import com.intellij.psi.jsp.JspElementType; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType; import static com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper.findLastFieldInGroup; public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock"); @NotNull protected final CommonCodeStyleSettings mySettings; @NotNull protected final JavaCodeStyleSettings myJavaSettings; protected final CommonCodeStyleSettings.IndentOptions myIndentSettings; private final Indent myIndent; protected Indent myChildIndent; protected Alignment myChildAlignment; protected boolean myUseChildAttributes = false; @NotNull protected final AlignmentStrategy myAlignmentStrategy; private boolean myIsAfterClassKeyword = false; protected Alignment myReservedAlignment; protected Alignment myReservedAlignment2; private final JavaWrapManager myWrapManager; private Map<IElementType, Wrap> myPreferredWraps; private AbstractJavaBlock myParentBlock; protected AbstractJavaBlock(@NotNull final ASTNode node, final Wrap wrap, final Alignment alignment, final Indent indent, @NotNull final CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings) { this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, AlignmentStrategy.wrap(alignment)); } protected AbstractJavaBlock(@NotNull final ASTNode node, final Wrap wrap, @NotNull final AlignmentStrategy alignmentStrategy, final Indent indent, @NotNull final CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings) { this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, alignmentStrategy); } private AbstractJavaBlock(@NotNull ASTNode ignored, @NotNull CommonCodeStyleSettings commonSettings, @NotNull JavaCodeStyleSettings javaSettings) { super(ignored, null, null); mySettings = commonSettings; myJavaSettings = javaSettings; myIndentSettings = commonSettings.getIndentOptions(); myIndent = null; myWrapManager = JavaWrapManager.INSTANCE; myAlignmentStrategy = AlignmentStrategy.getNullStrategy(); } protected AbstractJavaBlock(@NotNull final ASTNode node, final Wrap wrap, final Indent indent, @NotNull final CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, final JavaWrapManager wrapManager, @NotNull final AlignmentStrategy alignmentStrategy) { super(node, wrap, createBlockAlignment(alignmentStrategy, node)); mySettings = settings; myJavaSettings = javaSettings; myIndentSettings = settings.getIndentOptions(); myIndent = indent; myWrapManager = wrapManager; myAlignmentStrategy = alignmentStrategy; } @Nullable private static Alignment createBlockAlignment(@NotNull AlignmentStrategy strategy, @NotNull ASTNode node) { // There is a possible case that 'implements' section is incomplete (e.g. ends with comma). We may want to align lbrace // to the first implemented interface reference then. if (node.getElementType() == JavaElementType.IMPLEMENTS_LIST) { return null; } return strategy.getAlignment(node.getElementType()); } @NotNull public Block createJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, @Nullable Indent indent, @Nullable Wrap wrap, Alignment alignment) { return createJavaBlock(child, settings, javaSettings,indent, wrap, AlignmentStrategy.wrap(alignment)); } @NotNull public Block createJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, final Indent indent, @Nullable Wrap wrap, @NotNull AlignmentStrategy alignmentStrategy) { return createJavaBlock(child, settings, javaSettings, indent, wrap, alignmentStrategy, -1); } @NotNull private Block createJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, @Nullable Indent indent, Wrap wrap, @NotNull AlignmentStrategy alignmentStrategy, int startOffset) { Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)) : indent; final IElementType elementType = child.getElementType(); Alignment alignment = alignmentStrategy.getAlignment(elementType); if (child.getPsi() instanceof PsiWhiteSpace) { String text = child.getText(); int start = CharArrayUtil.shiftForward(text, 0, " \t\n"); int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1; LOG.assertTrue(start < end); return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()), wrap, alignment, actualIndent, settings, javaSettings); } if (child.getPsi() instanceof PsiClass) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } if (isBlockType(elementType)) { return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } if (isStatement(child, child.getTreeParent())) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } if (isBuildInjectedBlocks() && child instanceof PsiComment && child instanceof PsiLanguageInjectionHost && InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)child)) { return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings, javaSettings); } if (child instanceof LeafElement) { final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent); block.setStartOffset(startOffset); return block; } else if (isLikeExtendsList(elementType)) { return new ExtendsListBlock(child, wrap, alignmentStrategy, settings, javaSettings); } else if (elementType == JavaElementType.CODE_BLOCK) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } else if (elementType == JavaElementType.LABELED_STATEMENT) { return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } else if (elementType == JavaDocElementType.DOC_COMMENT) { return new DocCommentBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } else { final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignmentStrategy, actualIndent, settings, javaSettings); simpleJavaBlock.setStartOffset(startOffset); return simpleJavaBlock; } } @NotNull public static Block newJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings) { final Indent indent = getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)); return newJavaBlock(child, settings, javaSettings, indent, null, AlignmentStrategy.getNullStrategy()); } @NotNull public static Block newJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, @Nullable Indent indent, @Nullable Wrap wrap, @NotNull AlignmentStrategy strategy) { return new AbstractJavaBlock(child, settings, javaSettings) { @Override protected List<Block> buildChildren() { return null; } }.createJavaBlock(child, settings, javaSettings, indent, wrap, strategy); } @NotNull private static CommonCodeStyleSettings.IndentOptions getJavaIndentOptions(CommonCodeStyleSettings settings) { CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions(); assert indentOptions != null : "Java indent options are not initialized"; return indentOptions; } private static boolean isLikeExtendsList(final IElementType elementType) { return elementType == JavaElementType.EXTENDS_LIST || elementType == JavaElementType.IMPLEMENTS_LIST || elementType == JavaElementType.THROWS_LIST; } private static boolean isBlockType(final IElementType elementType) { return elementType == JavaElementType.SWITCH_STATEMENT || elementType == JavaElementType.FOR_STATEMENT || elementType == JavaElementType.WHILE_STATEMENT || elementType == JavaElementType.DO_WHILE_STATEMENT || elementType == JavaElementType.TRY_STATEMENT || elementType == JavaElementType.CATCH_SECTION || elementType == JavaElementType.IF_STATEMENT || elementType == JavaElementType.METHOD || elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION || elementType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER || elementType == JavaElementType.CLASS_INITIALIZER || elementType == JavaElementType.SYNCHRONIZED_STATEMENT || elementType == JavaElementType.FOREACH_STATEMENT; } @Nullable private static Indent getDefaultSubtreeIndent(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) { final ASTNode parent = child.getTreeParent(); final IElementType childNodeType = child.getElementType(); if (childNodeType == JavaElementType.ANNOTATION) { if (parent.getPsi() instanceof PsiArrayInitializerMemberValue) { return Indent.getNormalIndent(); } return Indent.getNoneIndent(); } final ASTNode prevElement = FormatterUtil.getPreviousNonWhitespaceSibling(child); if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) { return Indent.getNoneIndent(); } if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent(); if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1); if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent(); if (parent != null) { final Indent defaultChildIndent = getChildIndent(parent, indentOptions); if (defaultChildIndent != null) return defaultChildIndent; } if (child.getTreeParent() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) { return Indent.getNoneIndent(); } return null; } @Nullable private static Indent getChildIndent(@NotNull ASTNode parent, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) { final IElementType parentType = parent.getElementType(); if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent(); if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent(); if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent(); if (parentType == TokenType.DUMMY_HOLDER) return Indent.getNoneIndent(); if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent(); if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent(); if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent(); if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent(); if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent(); if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent(); if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent(); if (parentType == JavaElementType.FIELD) return Indent.getContinuationWithoutFirstIndent(indentOptions.USE_RELATIVE_INDENTS); if (parentType == JavaElementType.EXPRESSION_STATEMENT) return Indent.getNoneIndent(); if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) { return Indent.getNoneIndent(); } return null; } protected static boolean isRBrace(@NotNull final ASTNode child) { return child.getElementType() == JavaTokenType.RBRACE; } @Nullable @Override public Spacing getSpacing(Block child1, @NotNull Block child2) { return JavaSpacePropertyProcessor.getSpacing(getTreeNode(child2), mySettings, myJavaSettings); } @Override public ASTNode getFirstTreeNode() { return myNode; } @Override public Indent getIndent() { return myIndent; } protected static boolean isStatement(final ASTNode child, @Nullable final ASTNode parentNode) { if (parentNode != null) { final IElementType parentType = parentNode.getElementType(); if (parentType == JavaElementType.CODE_BLOCK) return false; final int role = ((CompositeElement)parentNode).getChildRole(child); if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH; if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY; } return false; } @Nullable protected Wrap createChildWrap() { return myWrapManager.createChildBlockWrap(this, getSettings(), this); } @Nullable protected Alignment createChildAlignment() { IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION; if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) { if (myNode.getTreeParent() != null && myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION && myAlignment != null) { return myAlignment; } return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null); } if (nodeType == JavaElementType.PARENTH_EXPRESSION) { return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null); } if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) { return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null); } if (nodeType == JavaElementType.FOR_STATEMENT) { return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null); } if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null); } if (nodeType == JavaElementType.THROWS_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null); } if (nodeType == JavaElementType.PARAMETER_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null); } if (nodeType == JavaElementType.RESOURCE_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_RESOURCES, null); } if (nodeType == JavaElementType.BINARY_EXPRESSION) { Alignment defaultAlignment = null; if (shouldInheritAlignment()) { defaultAlignment = myAlignment; } return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment); } if (nodeType == JavaElementType.CLASS || nodeType == JavaElementType.METHOD) { return null; } return null; } @Nullable protected Alignment chooseAlignment(@Nullable Alignment alignment, @Nullable Alignment alignment2, @NotNull ASTNode child) { if (isTernaryOperatorToken(child)) { return alignment2; } return alignment; } private boolean isTernaryOperatorToken(@NotNull final ASTNode child) { final IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) { IElementType childType = child.getElementType(); return childType == JavaTokenType.QUEST || childType ==JavaTokenType.COLON; } else { return false; } } private boolean shouldInheritAlignment() { if (myNode instanceof PsiPolyadicExpression) { final ASTNode treeParent = myNode.getTreeParent(); if (treeParent instanceof PsiPolyadicExpression) { return JavaFormatterUtil.areSamePriorityBinaryExpressions(myNode, treeParent); } } return false; } @Nullable protected ASTNode processChild(@NotNull final List<Block> result, @NotNull ASTNode child, Alignment defaultAlignment, final Wrap defaultWrap, final Indent childIndent) { return processChild(result, child, AlignmentStrategy.wrap(defaultAlignment), defaultWrap, childIndent, -1); } @Nullable protected ASTNode processChild(@NotNull final List<Block> result, @NotNull ASTNode child, @NotNull AlignmentStrategy alignmentStrategy, @Nullable final Wrap defaultWrap, final Indent childIndent) { return processChild(result, child, alignmentStrategy, defaultWrap, childIndent, -1); } @Nullable protected ASTNode processChild(@NotNull final List<Block> result, @NotNull ASTNode child, @NotNull AlignmentStrategy alignmentStrategy, final Wrap defaultWrap, final Indent childIndent, int childOffset) { final IElementType childType = child.getElementType(); if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) { myIsAfterClassKeyword = true; } if (childType == JavaElementType.METHOD_CALL_EXPRESSION) { Alignment alignment = shouldAlignChild(child) ? alignmentStrategy.getAlignment(childType) : null; result.add(createMethodCallExpressionBlock(child, arrangeChildWrap(child, defaultWrap), alignment, childIndent)); } else { IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION; if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) { final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false); child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE, result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION); } else if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) { final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false); child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE, result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) { final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false); if (mySettings.PREFER_PARAMETERS_WRAP && !isInsideMethodCall(myNode.getPsi())) { wrap.ignoreParentWraps(); } child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) { ASTNode parent = myNode.getTreeParent(); boolean isLambdaParameterList = parent != null && parent.getElementType() == JavaElementType.LAMBDA_EXPRESSION; Wrap wrapToUse = isLambdaParameterList ? null : getMethodParametersWrap(); WrappingStrategy wrapStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(wrapToUse); child = processParenthesisBlock(result, child, wrapStrategy, mySettings.ALIGN_MULTILINE_PARAMETERS); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.RESOURCE_LIST) { Wrap wrap = Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false); child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_RESOURCES); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) { Wrap wrap = Wrap.createWrap(getWrapType(myJavaSettings.ANNOTATION_PARAMETER_WRAP), false); child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), myJavaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) { child = processParenthesisBlock(result, child, WrappingStrategy.DO_NOT_WRAP, mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION); } else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) { child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace()); } else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) { child = processTernaryOperationRange(result, child, defaultWrap, childIndent); } else if (childType == JavaElementType.FIELD) { child = processField(result, child, alignmentStrategy, defaultWrap, childIndent); } else if (childType == JavaElementType.LOCAL_VARIABLE || childType == JavaElementType.DECLARATION_STATEMENT && (nodeType == JavaElementType.METHOD || nodeType == JavaElementType.CODE_BLOCK)) { result.add(new SimpleJavaBlock(child, defaultWrap, alignmentStrategy, childIndent, mySettings, myJavaSettings)); } else { Alignment alignment = alignmentStrategy.getAlignment(childType); AlignmentStrategy alignmentStrategyToUse = shouldAlignChild(child) ? AlignmentStrategy.wrap(alignment) : AlignmentStrategy.getNullStrategy(); if (myAlignmentStrategy.getAlignment(nodeType, childType) != null && (nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS)) { alignmentStrategyToUse = myAlignmentStrategy; } Wrap wrap = arrangeChildWrap(child, defaultWrap); Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategyToUse, childOffset); if (block instanceof AbstractJavaBlock) { final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block; if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION || nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION) { javaBlock.setReservedWrap(getReservedWrap(nodeType), nodeType); javaBlock.setReservedWrap(getReservedWrap(childType), childType); } else if (nodeType == JavaElementType.BINARY_EXPRESSION) { javaBlock.setReservedWrap(defaultWrap, nodeType); } } result.add(block); } } return child; } private boolean isInsideMethodCall(@NotNull PsiElement element) { PsiElement e = element.getParent(); int parentsVisited = 0; while (e != null && !(e instanceof PsiStatement) && parentsVisited < 5) { if (e instanceof PsiExpressionList) { return true; } e = e.getParent(); parentsVisited++; } return false; } @NotNull private Wrap getMethodParametersWrap() { Wrap preferredWrap = getModifierListWrap(); if (preferredWrap == null) { return Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false); } else { return Wrap.createChildWrap(preferredWrap, getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false); } } @Nullable private Wrap getModifierListWrap() { AbstractJavaBlock parentBlock = getParentBlock(); if (parentBlock != null) { return parentBlock.getReservedWrap(JavaElementType.MODIFIER_LIST); } return null; } private ASTNode processField(@NotNull final List<Block> result, ASTNode child, @NotNull final AlignmentStrategy alignmentStrategy, final Wrap defaultWrap, final Indent childIndent) { ASTNode lastFieldInGroup = findLastFieldInGroup(child); if (lastFieldInGroup == child) { result.add(createJavaBlock(child, getSettings(), myJavaSettings, childIndent, arrangeChildWrap(child, defaultWrap), alignmentStrategy)); return child; } else { final ArrayList<Block> localResult = new ArrayList<Block>(); while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child)) { localResult.add(createJavaBlock( child, getSettings(), myJavaSettings, Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS), arrangeChildWrap(child, defaultWrap), alignmentStrategy ) ); } if (child == lastFieldInGroup) break; child = child.getTreeNext(); } if (!localResult.isEmpty()) { result.add(new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, childIndent, null)); } return lastFieldInGroup; } } @Nullable private ASTNode processTernaryOperationRange(@NotNull final List<Block> result, @NotNull final ASTNode child, final Wrap defaultWrap, final Indent childIndent) { final ArrayList<Block> localResult = new ArrayList<Block>(); final Wrap wrap = arrangeChildWrap(child, defaultWrap); final Alignment alignment = myReservedAlignment; final Alignment alignment2 = myReservedAlignment2; localResult.add(new LeafBlock(child, wrap, chooseAlignment(alignment, alignment2, child), childIndent)); ASTNode current = child.getTreeNext(); while (current != null) { if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) { if (isTernaryOperationSign(current)) break; current = processChild(localResult, current, chooseAlignment(alignment, alignment2, current), defaultWrap, childIndent); } if (current != null) { current = current.getTreeNext(); } } result.add(new SyntheticCodeBlock(localResult, chooseAlignment(alignment, alignment2, child), getSettings(), myJavaSettings, null, wrap)); if (current == null) { return null; } return current.getTreePrev(); } private boolean isTernaryOperationSign(@NotNull final ASTNode child) { if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false; final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child); return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON; } @NotNull private Block createMethodCallExpressionBlock(@NotNull ASTNode node, Wrap blockWrap, Alignment alignment, Indent indent) { final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>(); collectNodes(nodes, node); return new ChainMethodCallsBlockBuilder(alignment, blockWrap, indent, mySettings, myJavaSettings).build(nodes); } private static void collectNodes(@NotNull List<ASTNode> nodes, @NotNull ASTNode node) { ASTNode child = node.getFirstChildNode(); while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child)) { if (child.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION || child.getElementType() == JavaElementType .REFERENCE_EXPRESSION) { collectNodes(nodes, child); } else { nodes.add(child); } } child = child.getTreeNext(); } } private boolean shouldAlignChild(@NotNull final ASTNode child) { int role = getChildRole(child); final IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.FOR_STATEMENT) { if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) { return true; } return false; } else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) { return true; } return false; } else if (nodeType == JavaElementType.THROWS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST) { return true; } return false; } else if (nodeType == JavaElementType.CLASS) { if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return true; if (myIsAfterClassKeyword) return false; if (role == ChildRole.MODIFIER_LIST) return true; return false; } else if (JavaElementType.FIELD == nodeType) { return shouldAlignFieldInColumns(child); } else if (nodeType == JavaElementType.METHOD) { if (role == ChildRole.MODIFIER_LIST) return true; if (role == ChildRole.TYPE_PARAMETER_LIST) return true; if (role == ChildRole.TYPE) return true; if (role == ChildRole.NAME) return true; if (role == ChildRole.THROWS_LIST && mySettings.ALIGN_THROWS_KEYWORD) return true; return false; } else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) { if (role == ChildRole.LOPERAND) return true; if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) { return true; } return false; } else if (child.getElementType() == JavaTokenType.END_OF_LINE_COMMENT) { ASTNode previous = child.getTreePrev(); // There is a special case - comment block that is located at the very start of the line. We don't reformat such a blocks, // hence, no alignment should be applied to them in order to avoid subsequent blocks aligned with the same alignment to // be located at the left editor edge as well. CharSequence prevChars; if (previous != null && previous.getElementType() == TokenType.WHITE_SPACE && (prevChars = previous.getChars()).length() > 0 && prevChars.charAt(prevChars.length() - 1) == '\n') { return false; } return true; } else if (nodeType == JavaElementType.MODIFIER_LIST) { // There is a possible case that modifier list contains from more than one elements, e.g. 'private final'. It's also possible // that the list is aligned. We want to apply alignment rule only to the first element then. ASTNode previous = child.getTreePrev(); if (previous == null || previous.getTreeParent() != myNode) { return true; } return false; } else { return true; } } private static int getChildRole(@NotNull ASTNode child) { return ((CompositeElement)child.getTreeParent()).getChildRole(child); } /** * Encapsulates alignment retrieval logic for variable declaration use-case assuming that given node is a child node * of basic variable declaration node. * * @param child variable declaration child node which alignment is to be defined * @return alignment to use for the given node * @see CodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS */ @Nullable private boolean shouldAlignFieldInColumns(@NotNull ASTNode child) { // The whole idea of variable declarations alignment is that complete declaration blocks which children are to be aligned hold // reference to the same AlignmentStrategy object, hence, reuse the same Alignment objects. So, there is no point in checking // if it's necessary to align sub-blocks if shared strategy is not defined. if (!mySettings.ALIGN_GROUP_FIELD_DECLARATIONS) { return false; } IElementType childType = child.getElementType(); // We don't want to align subsequent identifiers in single-line declarations like 'int i1, i2, i3'. I.e. only 'i1' // should be aligned then. ASTNode previousNode = FormatterUtil.getPreviousNonWhitespaceSibling(child); if (childType == JavaTokenType.IDENTIFIER && (previousNode == null || previousNode.getElementType() == JavaTokenType.COMMA)) { return false; } return true; } @Nullable public static Alignment createAlignment(final boolean alignOption, @Nullable final Alignment defaultAlignment) { return alignOption ? createAlignmentOrDefault(null, defaultAlignment) : defaultAlignment; } @Nullable public static Alignment createAlignment(Alignment base, final boolean alignOption, @Nullable final Alignment defaultAlignment) { return alignOption ? createAlignmentOrDefault(base, defaultAlignment) : defaultAlignment; } @Nullable protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) { return myWrapManager.arrangeChildWrap(child, myNode, mySettings, myJavaSettings, defaultWrap, this); } @NotNull private ASTNode processParenthesisBlock(@NotNull List<Block> result, @NotNull ASTNode child, @NotNull WrappingStrategy wrappingStrategy, final boolean doAlign) { myUseChildAttributes = true; final IElementType from = JavaTokenType.LPARENTH; final IElementType to = JavaTokenType.RPARENTH; return processParenthesisBlock(from, to, result, child, wrappingStrategy, doAlign); } @NotNull private ASTNode processParenthesisBlock(@NotNull IElementType from, @Nullable final IElementType to, @NotNull final List<Block> result, @NotNull ASTNode child, @NotNull final WrappingStrategy wrappingStrategy, final boolean doAlign) { final Indent externalIndent = Indent.getNoneIndent(); final Indent internalIndent = Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS); final Indent internalIndentEnforcedToChildren = Indent.getIndent(Indent.Type.CONTINUATION, myIndentSettings.USE_RELATIVE_INDENTS, true); AlignmentStrategy alignmentStrategy = AlignmentStrategy.wrap(createAlignment(doAlign, null), JavaTokenType.COMMA); setChildIndent(internalIndent); setChildAlignment(alignmentStrategy.getAlignment(null)); boolean methodParametersBlock = true; ASTNode lBracketParent = child.getTreeParent(); if (lBracketParent != null) { ASTNode methodCandidate = lBracketParent.getTreeParent(); methodParametersBlock = methodCandidate != null && (methodCandidate.getElementType() == JavaElementType.METHOD || methodCandidate.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION); } Alignment bracketAlignment = methodParametersBlock && mySettings.ALIGN_MULTILINE_METHOD_BRACKETS ? Alignment.createAlignment() : null; AlignmentStrategy anonymousClassStrategy = doAlign ? alignmentStrategy : AlignmentStrategy.wrap(Alignment.createAlignment(), false, JavaTokenType.NEW_KEYWORD, JavaElementType.NEW_EXPRESSION, JavaTokenType.RBRACE); setChildIndent(internalIndent); setChildAlignment(alignmentStrategy.getAlignment(null)); boolean isAfterIncomplete = false; ASTNode prev = child; boolean afterAnonymousClass = false; final boolean enforceIndent = shouldEnforceIndentToChildren(); while (child != null) { isAfterIncomplete = isAfterIncomplete || child.getElementType() == TokenType.ERROR_ELEMENT || child.getElementType() == JavaElementType.EMPTY_EXPRESSION; if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) { if (child.getElementType() == from) { result.add(createJavaBlock(child, mySettings, myJavaSettings, externalIndent, null, bracketAlignment)); } else if (child.getElementType() == to) { result.add(createJavaBlock(child, mySettings, myJavaSettings, isAfterIncomplete && !afterAnonymousClass ? internalIndent : externalIndent, null, isAfterIncomplete ? alignmentStrategy.getAlignment(null) : bracketAlignment) ); return child; } else { final IElementType elementType = child.getElementType(); Indent indentToUse = enforceIndent ? internalIndentEnforcedToChildren : internalIndent; AlignmentStrategy alignmentStrategyToUse = canUseAnonymousClassAlignment(child) ? anonymousClassStrategy : alignmentStrategy; processChild(result, child, alignmentStrategyToUse.getAlignment(elementType), wrappingStrategy.getWrap(elementType), indentToUse); if (to == null) {//process only one statement return child; } } isAfterIncomplete = false; if (child.getElementType() != JavaTokenType.COMMA) { afterAnonymousClass = isAnonymousClass(child); } } prev = child; child = child.getTreeNext(); } return prev; } private static boolean canUseAnonymousClassAlignment(@NotNull ASTNode child) { // The general idea is to handle situations like below: // test(new Runnable() { // public void run() { // } // }, new Runnable() { // public void run() { // } // } // ); // I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument // at the same line, e.g.: // test("this is a long argument", new Runnable() { // public void run() { // } // }, new Runnable() { // public void run() { // } // } // ); if (!isAnonymousClass(child)) { return false; } for (ASTNode node = child.getTreePrev(); node != null; node = node.getTreePrev()) { if (node.getElementType() == TokenType.WHITE_SPACE) { if (StringUtil.countNewLines(node.getChars()) > 0) { return false; } } else if (node.getElementType() == JavaTokenType.LPARENTH) { // First method call argument. return true; } else if (node.getElementType() != JavaTokenType.COMMA && !isAnonymousClass(node)) { return false; } } return true; } private boolean shouldEnforceIndentToChildren() { if (myNode.getElementType() != JavaElementType.EXPRESSION_LIST) { return false; } ASTNode parent = myNode.getTreeParent(); if (parent == null || parent.getElementType() != JavaElementType.METHOD_CALL_EXPRESSION) { return false; } PsiExpression[] arguments = ((PsiExpressionList)myNode.getPsi()).getExpressions(); return JavaFormatterUtil.hasMultilineArguments(arguments) && JavaFormatterUtil.isMultilineExceptArguments(arguments); } private static boolean isAnonymousClass(@Nullable ASTNode node) { if (node == null || node.getElementType() != JavaElementType.NEW_EXPRESSION) { return false; } ASTNode lastChild = node.getLastChildNode(); return lastChild != null && lastChild.getElementType() == JavaElementType.ANONYMOUS_CLASS; } @Nullable private ASTNode processEnumBlock(@NotNull List<Block> result, @Nullable ASTNode child, ASTNode last) { final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap .createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true)); while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) { result.add(createJavaBlock(child, mySettings, myJavaSettings, Indent.getNormalIndent(), wrappingStrategy.getWrap(child.getElementType()), AlignmentStrategy.getNullStrategy())); if (child == last) return child; } child = child.getTreeNext(); } return null; } private void setChildAlignment(final Alignment alignment) { myChildAlignment = alignment; } private void setChildIndent(final Indent internalIndent) { myChildIndent = internalIndent; } @Nullable private static Alignment createAlignmentOrDefault(@Nullable Alignment base, @Nullable final Alignment defaultAlignment) { if (defaultAlignment == null) { return base == null ? Alignment.createAlignment() : Alignment.createChildAlignment(base); } return defaultAlignment; } private int getBraceStyle() { final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode); if (psiNode instanceof PsiClass) { return mySettings.CLASS_BRACE_STYLE; } if (psiNode instanceof PsiMethod || psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) { return mySettings.METHOD_BRACE_STYLE; } return mySettings.BRACE_STYLE; } protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) { return getCodeBlockInternalIndent(baseChildrenIndent, false); } protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent, boolean enforceParentIndent) { if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) { return Indent.getNoneIndent(); } final int braceStyle = getBraceStyle(); return braceStyle == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ? createNormalIndent(baseChildrenIndent - 1, enforceParentIndent) : createNormalIndent(baseChildrenIndent, enforceParentIndent); } protected static Indent createNormalIndent(final int baseChildrenIndent) { return createNormalIndent(baseChildrenIndent, false); } protected static Indent createNormalIndent(final int baseChildrenIndent, boolean enforceIndentToChildren) { if (baseChildrenIndent == 1) { return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren); } else if (baseChildrenIndent <= 0) { return Indent.getNoneIndent(); } else { LOG.assertTrue(false); return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren); } } private boolean isTopLevelClass() { return myNode.getElementType() == JavaElementType.CLASS && SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile; } protected Indent getCodeBlockExternalIndent() { final int braceStyle = getBraceStyle(); if (braceStyle == CommonCodeStyleSettings.END_OF_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED) { return Indent.getNoneIndent(); } return Indent.getNormalIndent(); } protected Indent getCodeBlockChildExternalIndent(final int newChildIndex) { final int braceStyle = getBraceStyle(); if (!isAfterCodeBlock(newChildIndex)) { return Indent.getNormalIndent(); } if (braceStyle == CommonCodeStyleSettings.NEXT_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED || braceStyle == CommonCodeStyleSettings.END_OF_LINE) { return Indent.getNoneIndent(); } return Indent.getNormalIndent(); } private boolean isAfterCodeBlock(final int newChildIndex) { if (newChildIndex == 0) return false; Block blockBefore = getSubBlocks().get(newChildIndex - 1); return blockBefore instanceof CodeBlockBlock; } /** * <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing * is refactored * * @param elementType target element type * @return <code>null</code> all the time */ @Nullable @Override public Wrap getReservedWrap(IElementType elementType) { return myPreferredWraps != null ? myPreferredWraps.get(elementType) : null; } /** * Defines contract for associating operation type and particular wrap instance. I.e. given wrap object <b>may</b> be returned * from subsequent {@link #getReservedWrap(IElementType)} call if given operation type is used as an argument there. * <p/> * Default implementation ({@link AbstractJavaBlock#setReservedWrap(Wrap, IElementType)}) does nothing. * <p/> * <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing * is refactored * * @param reservedWrap reserved wrap instance * @param operationType target operation type to associate with the given wrap instance */ public void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) { if (myPreferredWraps == null) { myPreferredWraps = ContainerUtil.newHashMap(); } myPreferredWraps.put(operationType, reservedWrap); } @Nullable protected static ASTNode getTreeNode(final Block child2) { if (child2 instanceof JavaBlock) { return ((JavaBlock)child2).getFirstTreeNode(); } if (child2 instanceof LeafBlock) { return ((LeafBlock)child2).getTreeNode(); } return null; } @Override @NotNull public ChildAttributes getChildAttributes(final int newChildIndex) { if (myUseChildAttributes) { return new ChildAttributes(myChildIndent, myChildAlignment); } if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) { return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment); } return super.getChildAttributes(newChildIndex); } @Override @Nullable protected Indent getChildIndent() { return getChildIndent(myNode, myIndentSettings); } @NotNull public CommonCodeStyleSettings getSettings() { return mySettings; } protected boolean isAfter(final int newChildIndex, @NotNull final IElementType[] elementTypes) { if (newChildIndex == 0) return false; final Block previousBlock = getSubBlocks().get(newChildIndex - 1); if (!(previousBlock instanceof AbstractBlock)) return false; final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType(); for (IElementType elementType : elementTypes) { if (previousElementType == elementType) return true; } return false; } @Nullable protected Alignment getUsedAlignment(final int newChildIndex) { final List<Block> subBlocks = getSubBlocks(); for (int i = 0; i < newChildIndex; i++) { if (i >= subBlocks.size()) return null; final Block block = subBlocks.get(i); final Alignment alignment = block.getAlignment(); if (alignment != null) return alignment; } return null; } @Override public boolean isLeaf() { return ShiftIndentInsideHelper.mayShiftIndentInside(myNode); } @Nullable protected ASTNode composeCodeBlock(@NotNull final List<Block> result, ASTNode child, final Indent indent, final int childrenIndent, @Nullable final Wrap childWrap) { final ArrayList<Block> localResult = new ArrayList<Block>(); processChild(localResult, child, AlignmentStrategy.getNullStrategy(), null, Indent.getNoneIndent()); child = child.getTreeNext(); ChildAlignmentStrategyProvider alignmentStrategyProvider = getStrategyProvider(); while (child != null) { if (FormatterUtil.containsWhiteSpacesOnly(child)) { child = child.getTreeNext(); continue; } Indent childIndent = getIndentForCodeBlock(child, childrenIndent); AlignmentStrategy alignmentStrategyToUse = alignmentStrategyProvider.getNextChildStrategy(child); final boolean isRBrace = isRBrace(child); child = processChild(localResult, child, alignmentStrategyToUse, childWrap, childIndent); if (isRBrace) { result.add(createCodeBlockBlock(localResult, indent, childrenIndent)); return child; } if (child != null) { child = child.getTreeNext(); } } result.add(createCodeBlockBlock(localResult, indent, childrenIndent)); return null; } private ChildAlignmentStrategyProvider getStrategyProvider() { if (mySettings.ALIGN_GROUP_FIELD_DECLARATIONS && myNode.getElementType() == JavaElementType.CLASS) { return new SubsequentFieldAligner(mySettings); } ASTNode parent = myNode.getTreeParent(); IElementType parentType = parent != null ? parent.getElementType() : null; if (mySettings.ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS && parentType == JavaElementType.METHOD) { return new SubsequentVariablesAligner(); } return ChildAlignmentStrategyProvider.NULL_STRATEGY_PROVIDER; } private Indent getIndentForCodeBlock(ASTNode child, int childrenIndent) { if (child.getElementType() == JavaElementType.CODE_BLOCK && (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED || getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2)) { return Indent.getNormalIndent(); } return isRBrace(child) ? Indent.getNoneIndent() : getCodeBlockInternalIndent(childrenIndent, false); } public AbstractJavaBlock getParentBlock() { return myParentBlock; } public void setParentBlock(@NotNull AbstractJavaBlock parentBlock) { myParentBlock = parentBlock; } @NotNull public SyntheticCodeBlock createCodeBlockBlock(final List<Block> localResult, final Indent indent, final int childrenIndent) { final SyntheticCodeBlock result = new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, indent, null); result.setChildAttributes(new ChildAttributes(getCodeBlockInternalIndent(childrenIndent), null)); return result; } }
robovm/robovm-studio
java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java
Java
apache-2.0
55,736
/* * 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.sql.relational; import com.facebook.presto.Session; import com.facebook.presto.metadata.FunctionKind; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Signature; import com.facebook.presto.spi.type.DecimalParseResult; import com.facebook.presto.spi.type.Decimals; import com.facebook.presto.spi.type.TimeZoneKey; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.spi.type.TypeSignature; import com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer; import com.facebook.presto.sql.tree.ArithmeticBinaryExpression; import com.facebook.presto.sql.tree.ArithmeticUnaryExpression; import com.facebook.presto.sql.tree.ArrayConstructor; import com.facebook.presto.sql.tree.AstVisitor; import com.facebook.presto.sql.tree.BetweenPredicate; import com.facebook.presto.sql.tree.BinaryLiteral; import com.facebook.presto.sql.tree.BooleanLiteral; import com.facebook.presto.sql.tree.Cast; import com.facebook.presto.sql.tree.CharLiteral; import com.facebook.presto.sql.tree.CoalesceExpression; import com.facebook.presto.sql.tree.ComparisonExpression; import com.facebook.presto.sql.tree.DecimalLiteral; import com.facebook.presto.sql.tree.DereferenceExpression; import com.facebook.presto.sql.tree.DoubleLiteral; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FieldReference; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.GenericLiteral; import com.facebook.presto.sql.tree.IfExpression; import com.facebook.presto.sql.tree.InListExpression; import com.facebook.presto.sql.tree.InPredicate; import com.facebook.presto.sql.tree.IntervalLiteral; import com.facebook.presto.sql.tree.IsNotNullPredicate; import com.facebook.presto.sql.tree.IsNullPredicate; import com.facebook.presto.sql.tree.LambdaArgumentDeclaration; import com.facebook.presto.sql.tree.LambdaExpression; import com.facebook.presto.sql.tree.LikePredicate; import com.facebook.presto.sql.tree.LogicalBinaryExpression; import com.facebook.presto.sql.tree.LongLiteral; import com.facebook.presto.sql.tree.NotExpression; import com.facebook.presto.sql.tree.NullIfExpression; import com.facebook.presto.sql.tree.NullLiteral; import com.facebook.presto.sql.tree.Row; import com.facebook.presto.sql.tree.SearchedCaseExpression; import com.facebook.presto.sql.tree.SimpleCaseExpression; import com.facebook.presto.sql.tree.StringLiteral; import com.facebook.presto.sql.tree.SubscriptExpression; import com.facebook.presto.sql.tree.SymbolReference; import com.facebook.presto.sql.tree.TimeLiteral; import com.facebook.presto.sql.tree.TimestampLiteral; import com.facebook.presto.sql.tree.TryExpression; import com.facebook.presto.sql.tree.WhenClause; import com.facebook.presto.type.RowType; import com.facebook.presto.type.RowType.RowField; import com.facebook.presto.type.UnknownType; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.IdentityHashMap; import java.util.List; import static com.facebook.presto.metadata.FunctionKind.SCALAR; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.CharType.createCharType; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE; import static com.facebook.presto.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.sql.relational.Expressions.call; import static com.facebook.presto.sql.relational.Expressions.constant; import static com.facebook.presto.sql.relational.Expressions.constantNull; import static com.facebook.presto.sql.relational.Expressions.field; import static com.facebook.presto.sql.relational.Signatures.arithmeticExpressionSignature; import static com.facebook.presto.sql.relational.Signatures.arithmeticNegationSignature; import static com.facebook.presto.sql.relational.Signatures.arrayConstructorSignature; import static com.facebook.presto.sql.relational.Signatures.betweenSignature; import static com.facebook.presto.sql.relational.Signatures.castSignature; import static com.facebook.presto.sql.relational.Signatures.coalesceSignature; import static com.facebook.presto.sql.relational.Signatures.comparisonExpressionSignature; import static com.facebook.presto.sql.relational.Signatures.dereferenceSignature; import static com.facebook.presto.sql.relational.Signatures.likePatternSignature; import static com.facebook.presto.sql.relational.Signatures.likeSignature; import static com.facebook.presto.sql.relational.Signatures.logicalExpressionSignature; import static com.facebook.presto.sql.relational.Signatures.nullIfSignature; import static com.facebook.presto.sql.relational.Signatures.rowConstructorSignature; import static com.facebook.presto.sql.relational.Signatures.subscriptSignature; import static com.facebook.presto.sql.relational.Signatures.switchSignature; import static com.facebook.presto.sql.relational.Signatures.tryCastSignature; import static com.facebook.presto.sql.relational.Signatures.whenSignature; import static com.facebook.presto.type.JsonType.JSON; import static com.facebook.presto.type.LikePatternType.LIKE_PATTERN; import static com.facebook.presto.util.DateTimeUtils.parseDayTimeInterval; import static com.facebook.presto.util.DateTimeUtils.parseTimeWithTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseTimeWithoutTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithoutTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseYearMonthInterval; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.facebook.presto.util.Types.checkType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.airlift.slice.SliceUtf8.countCodePoints; import static io.airlift.slice.Slices.utf8Slice; import static java.util.Objects.requireNonNull; public final class SqlToRowExpressionTranslator { private SqlToRowExpressionTranslator() {} public static RowExpression translate( Expression expression, FunctionKind functionKind, IdentityHashMap<Expression, Type> types, FunctionRegistry functionRegistry, TypeManager typeManager, Session session, boolean optimize) { RowExpression result = new Visitor(functionKind, types, typeManager, session.getTimeZoneKey()).process(expression, null); requireNonNull(result, "translated expression is null"); if (optimize) { ExpressionOptimizer optimizer = new ExpressionOptimizer(functionRegistry, typeManager, session); return optimizer.optimize(result); } return result; } private static class Visitor extends AstVisitor<RowExpression, Void> { private final FunctionKind functionKind; private final IdentityHashMap<Expression, Type> types; private final TypeManager typeManager; private final TimeZoneKey timeZoneKey; private Visitor(FunctionKind functionKind, IdentityHashMap<Expression, Type> types, TypeManager typeManager, TimeZoneKey timeZoneKey) { this.functionKind = functionKind; this.types = types; this.typeManager = typeManager; this.timeZoneKey = timeZoneKey; } @Override protected RowExpression visitExpression(Expression node, Void context) { throw new UnsupportedOperationException("not yet implemented: expression translator for " + node.getClass().getName()); } @Override protected RowExpression visitFieldReference(FieldReference node, Void context) { return field(node.getFieldIndex(), types.get(node)); } @Override protected RowExpression visitNullLiteral(NullLiteral node, Void context) { return constantNull(UnknownType.UNKNOWN); } @Override protected RowExpression visitBooleanLiteral(BooleanLiteral node, Void context) { return constant(node.getValue(), BOOLEAN); } @Override protected RowExpression visitLongLiteral(LongLiteral node, Void context) { if (node.getValue() >= Integer.MIN_VALUE && node.getValue() <= Integer.MAX_VALUE) { return constant(node.getValue(), INTEGER); } return constant(node.getValue(), BIGINT); } @Override protected RowExpression visitDoubleLiteral(DoubleLiteral node, Void context) { return constant(node.getValue(), DOUBLE); } @Override protected RowExpression visitDecimalLiteral(DecimalLiteral node, Void context) { DecimalParseResult parseResult = Decimals.parse(node.getValue()); return constant(parseResult.getObject(), parseResult.getType()); } @Override protected RowExpression visitStringLiteral(StringLiteral node, Void context) { return constant(node.getSlice(), createVarcharType(countCodePoints(node.getSlice()))); } @Override protected RowExpression visitCharLiteral(CharLiteral node, Void context) { return constant(node.getSlice(), createCharType(node.getValue().length())); } @Override protected RowExpression visitBinaryLiteral(BinaryLiteral node, Void context) { return constant(node.getValue(), VARBINARY); } @Override protected RowExpression visitGenericLiteral(GenericLiteral node, Void context) { Type type = typeManager.getType(parseTypeSignature(node.getType())); if (type == null) { throw new IllegalArgumentException("Unsupported type: " + node.getType()); } if (JSON.equals(type)) { return call( new Signature("json_parse", SCALAR, types.get(node).getTypeSignature(), VARCHAR.getTypeSignature()), types.get(node), constant(utf8Slice(node.getValue()), VARCHAR)); } return call( castSignature(types.get(node), VARCHAR), types.get(node), constant(utf8Slice(node.getValue()), VARCHAR)); } @Override protected RowExpression visitTimeLiteral(TimeLiteral node, Void context) { long value; if (types.get(node).equals(TIME_WITH_TIME_ZONE)) { value = parseTimeWithTimeZone(node.getValue()); } else { // parse in time zone of client value = parseTimeWithoutTimeZone(timeZoneKey, node.getValue()); } return constant(value, types.get(node)); } @Override protected RowExpression visitTimestampLiteral(TimestampLiteral node, Void context) { long value; if (types.get(node).equals(TIMESTAMP_WITH_TIME_ZONE)) { value = parseTimestampWithTimeZone(timeZoneKey, node.getValue()); } else { // parse in time zone of client value = parseTimestampWithoutTimeZone(timeZoneKey, node.getValue()); } return constant(value, types.get(node)); } @Override protected RowExpression visitIntervalLiteral(IntervalLiteral node, Void context) { long value; if (node.isYearToMonth()) { value = node.getSign().multiplier() * parseYearMonthInterval(node.getValue(), node.getStartField(), node.getEndField()); } else { value = node.getSign().multiplier() * parseDayTimeInterval(node.getValue(), node.getStartField(), node.getEndField()); } return constant(value, types.get(node)); } @Override protected RowExpression visitComparisonExpression(ComparisonExpression node, Void context) { RowExpression left = process(node.getLeft(), context); RowExpression right = process(node.getRight(), context); return call( comparisonExpressionSignature(node.getType(), left.getType(), right.getType()), BOOLEAN, left, right); } @Override protected RowExpression visitFunctionCall(FunctionCall node, Void context) { List<RowExpression> arguments = node.getArguments().stream() .map(value -> process(value, context)) .collect(toImmutableList()); List<TypeSignature> argumentTypes = arguments.stream() .map(RowExpression::getType) .map(Type::getTypeSignature) .collect(toImmutableList()); Signature signature = new Signature(node.getName().getSuffix(), functionKind, types.get(node).getTypeSignature(), argumentTypes); return call(signature, types.get(node), arguments); } @Override protected RowExpression visitSymbolReference(SymbolReference node, Void context) { return new VariableReferenceExpression(node.getName(), types.get(node)); } @Override protected RowExpression visitLambdaExpression(LambdaExpression node, Void context) { RowExpression body = process(node.getBody(), context); Type type = types.get(node); List<Type> typeParameters = type.getTypeParameters(); List<Type> argumentTypes = typeParameters.subList(0, typeParameters.size() - 1); List<String> argumentNames = node.getArguments().stream() .map(LambdaArgumentDeclaration::getName) .collect(toImmutableList()); return new LambdaDefinitionExpression(argumentTypes, argumentNames, body); } @Override protected RowExpression visitArithmeticBinary(ArithmeticBinaryExpression node, Void context) { RowExpression left = process(node.getLeft(), context); RowExpression right = process(node.getRight(), context); return call( arithmeticExpressionSignature(node.getType(), types.get(node), left.getType(), right.getType()), types.get(node), left, right); } @Override protected RowExpression visitArithmeticUnary(ArithmeticUnaryExpression node, Void context) { RowExpression expression = process(node.getValue(), context); switch (node.getSign()) { case PLUS: return expression; case MINUS: return call( arithmeticNegationSignature(types.get(node), expression.getType()), types.get(node), expression); } throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign()); } @Override protected RowExpression visitLogicalBinaryExpression(LogicalBinaryExpression node, Void context) { return call( logicalExpressionSignature(node.getType()), BOOLEAN, process(node.getLeft(), context), process(node.getRight(), context)); } @Override protected RowExpression visitCast(Cast node, Void context) { RowExpression value = process(node.getExpression(), context); if (node.isTypeOnly()) { return changeType(value, types.get(node)); } if (node.isSafe()) { return call(tryCastSignature(types.get(node), value.getType()), types.get(node), value); } return call(castSignature(types.get(node), value.getType()), types.get(node), value); } private static RowExpression changeType(RowExpression value, Type targetType) { ChangeTypeVisitor visitor = new ChangeTypeVisitor(targetType); return value.accept(visitor, null); } private static class ChangeTypeVisitor implements RowExpressionVisitor<Void, RowExpression> { private final Type targetType; private ChangeTypeVisitor(Type targetType) { this.targetType = targetType; } @Override public RowExpression visitCall(CallExpression call, Void context) { return new CallExpression(call.getSignature(), targetType, call.getArguments()); } @Override public RowExpression visitInputReference(InputReferenceExpression reference, Void context) { return new InputReferenceExpression(reference.getField(), targetType); } @Override public RowExpression visitConstant(ConstantExpression literal, Void context) { return new ConstantExpression(literal.getValue(), targetType); } @Override public RowExpression visitLambda(LambdaDefinitionExpression lambda, Void context) { throw new UnsupportedOperationException(); } @Override public RowExpression visitVariableReference(VariableReferenceExpression reference, Void context) { return new VariableReferenceExpression(reference.getName(), targetType); } } @Override protected RowExpression visitCoalesceExpression(CoalesceExpression node, Void context) { List<RowExpression> arguments = node.getOperands().stream() .map(value -> process(value, context)) .collect(toImmutableList()); List<Type> argumentTypes = arguments.stream().map(RowExpression::getType).collect(toImmutableList()); return call(coalesceSignature(types.get(node), argumentTypes), types.get(node), arguments); } @Override protected RowExpression visitSimpleCaseExpression(SimpleCaseExpression node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); arguments.add(process(node.getOperand(), context)); for (WhenClause clause : node.getWhenClauses()) { arguments.add(call(whenSignature(types.get(clause)), types.get(clause), process(clause.getOperand(), context), process(clause.getResult(), context))); } Type returnType = types.get(node); arguments.add(node.getDefaultValue() .map((value) -> process(value, context)) .orElse(constantNull(returnType))); return call(switchSignature(returnType), returnType, arguments.build()); } @Override protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context) { /* Translates an expression like: case when cond1 then value1 when cond2 then value2 when cond3 then value3 else value4 end To: IF(cond1, value1, IF(cond2, value2, If(cond3, value3, value4))) */ RowExpression expression = node.getDefaultValue() .map((value) -> process(value, context)) .orElse(constantNull(types.get(node))); for (WhenClause clause : Lists.reverse(node.getWhenClauses())) { expression = call( Signatures.ifSignature(types.get(node)), types.get(node), process(clause.getOperand(), context), process(clause.getResult(), context), expression); } return expression; } @Override protected RowExpression visitDereferenceExpression(DereferenceExpression node, Void context) { RowType rowType = checkType(types.get(node.getBase()), RowType.class, "type"); List<RowField> fields = rowType.getFields(); int index = -1; for (int i = 0; i < fields.size(); i++) { RowField field = fields.get(i); if (field.getName().isPresent() && field.getName().get().equalsIgnoreCase(node.getFieldName())) { checkArgument(index < 0, "Ambiguous field %s in type %s", field, rowType.getDisplayName()); index = i; } } checkState(index >= 0, "could not find field name: %s", node.getFieldName()); Type returnType = types.get(node); return call(dereferenceSignature(returnType, rowType), returnType, process(node.getBase(), context), constant(index, INTEGER)); } @Override protected RowExpression visitIfExpression(IfExpression node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); arguments.add(process(node.getCondition(), context)) .add(process(node.getTrueValue(), context)); if (node.getFalseValue().isPresent()) { arguments.add(process(node.getFalseValue().get(), context)); } else { arguments.add(constantNull(types.get(node))); } return call(Signatures.ifSignature(types.get(node)), types.get(node), arguments.build()); } @Override protected RowExpression visitTryExpression(TryExpression node, Void context) { return call(Signatures.trySignature(types.get(node)), types.get(node), process(node.getInnerExpression(), context)); } @Override protected RowExpression visitInPredicate(InPredicate node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); arguments.add(process(node.getValue(), context)); InListExpression values = (InListExpression) node.getValueList(); for (Expression value : values.getValues()) { arguments.add(process(value, context)); } return call(Signatures.inSignature(), BOOLEAN, arguments.build()); } @Override protected RowExpression visitIsNotNullPredicate(IsNotNullPredicate node, Void context) { RowExpression expression = process(node.getValue(), context); return call( Signatures.notSignature(), BOOLEAN, call(Signatures.isNullSignature(expression.getType()), BOOLEAN, ImmutableList.of(expression))); } @Override protected RowExpression visitIsNullPredicate(IsNullPredicate node, Void context) { RowExpression expression = process(node.getValue(), context); return call(Signatures.isNullSignature(expression.getType()), BOOLEAN, expression); } @Override protected RowExpression visitNotExpression(NotExpression node, Void context) { return call(Signatures.notSignature(), BOOLEAN, process(node.getValue(), context)); } @Override protected RowExpression visitNullIfExpression(NullIfExpression node, Void context) { RowExpression first = process(node.getFirst(), context); RowExpression second = process(node.getSecond(), context); return call( nullIfSignature(types.get(node), first.getType(), second.getType()), types.get(node), first, second); } @Override protected RowExpression visitBetweenPredicate(BetweenPredicate node, Void context) { RowExpression value = process(node.getValue(), context); RowExpression min = process(node.getMin(), context); RowExpression max = process(node.getMax(), context); return call( betweenSignature(value.getType(), min.getType(), max.getType()), BOOLEAN, value, min, max); } @Override protected RowExpression visitLikePredicate(LikePredicate node, Void context) { RowExpression value = process(node.getValue(), context); RowExpression pattern = process(node.getPattern(), context); if (node.getEscape() != null) { RowExpression escape = process(node.getEscape(), context); return call(likeSignature(), BOOLEAN, value, call(likePatternSignature(), LIKE_PATTERN, pattern, escape)); } return call(likeSignature(), BOOLEAN, value, call(castSignature(LIKE_PATTERN, VARCHAR), LIKE_PATTERN, pattern)); } @Override protected RowExpression visitSubscriptExpression(SubscriptExpression node, Void context) { RowExpression base = process(node.getBase(), context); RowExpression index = process(node.getIndex(), context); return call( subscriptSignature(types.get(node), base.getType(), index.getType()), types.get(node), base, index); } @Override protected RowExpression visitArrayConstructor(ArrayConstructor node, Void context) { List<RowExpression> arguments = node.getValues().stream() .map(value -> process(value, context)) .collect(toImmutableList()); List<Type> argumentTypes = arguments.stream() .map(RowExpression::getType) .collect(toImmutableList()); return call(arrayConstructorSignature(types.get(node), argumentTypes), types.get(node), arguments); } @Override protected RowExpression visitRow(Row node, Void context) { List<RowExpression> arguments = node.getItems().stream() .map(value -> process(value, context)) .collect(toImmutableList()); Type returnType = types.get(node); List<Type> argumentTypes = node.getItems().stream() .map(value -> types.get(value)) .collect(toImmutableList()); return call(rowConstructorSignature(returnType, argumentTypes), returnType, arguments); } } }
marsorp/blog
presto166/presto-main/src/main/java/com/facebook/presto/sql/relational/SqlToRowExpressionTranslator.java
Java
apache-2.0
28,699
package org.motechproject.mds.builder.impl; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import org.apache.commons.lang.reflect.FieldUtils; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.motechproject.mds.annotations.internal.samples.AnotherSample; import org.motechproject.mds.builder.EntityMetadataBuilder; import org.motechproject.mds.builder.Sample; import org.motechproject.mds.builder.SampleWithIncrementStrategy; import org.motechproject.mds.domain.ClassData; import org.motechproject.mds.domain.EntityType; import org.motechproject.mds.domain.OneToManyRelationship; import org.motechproject.mds.domain.OneToOneRelationship; import org.motechproject.mds.dto.EntityDto; import org.motechproject.mds.dto.FieldBasicDto; import org.motechproject.mds.dto.FieldDto; import org.motechproject.mds.dto.LookupDto; import org.motechproject.mds.dto.LookupFieldDto; import org.motechproject.mds.dto.LookupFieldType; import org.motechproject.mds.dto.MetadataDto; import org.motechproject.mds.dto.SchemaHolder; import org.motechproject.mds.dto.TypeDto; import org.motechproject.mds.javassist.MotechClassPool; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceModifier; import javax.jdo.metadata.ClassMetadata; import javax.jdo.metadata.ClassPersistenceModifier; import javax.jdo.metadata.CollectionMetadata; import javax.jdo.metadata.FieldMetadata; import javax.jdo.metadata.ForeignKeyMetadata; import javax.jdo.metadata.IndexMetadata; import javax.jdo.metadata.InheritanceMetadata; import javax.jdo.metadata.JDOMetadata; import javax.jdo.metadata.PackageMetadata; import javax.jdo.metadata.UniqueMetadata; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.motechproject.mds.testutil.FieldTestHelper.fieldDto; import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_CLASS; import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_FIELD; import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.CREATOR_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.CREATOR_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.DATANUCLEUS; import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.OWNER_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.OWNER_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.VALUE_GENERATOR; @RunWith(PowerMockRunner.class) @PrepareForTest({MotechClassPool.class, FieldUtils.class}) public class EntityMetadataBuilderTest { private static final String PACKAGE = "org.motechproject.mds.entity"; private static final String ENTITY_NAME = "Sample"; private static final String MODULE = "MrS"; private static final String NAMESPACE = "arrio"; private static final String TABLE_NAME = ""; private static final String CLASS_NAME = String.format("%s.%s", PACKAGE, ENTITY_NAME); private static final String TABLE_NAME_1 = String.format("MDS_%s", ENTITY_NAME).toUpperCase(); private static final String TABLE_NAME_2 = String.format("%s_%s", MODULE, ENTITY_NAME).toUpperCase(); private static final String TABLE_NAME_3 = String.format("%s_%s_%s", MODULE, NAMESPACE, ENTITY_NAME).toUpperCase(); private EntityMetadataBuilder entityMetadataBuilder = new EntityMetadataBuilderImpl(); @Mock private EntityDto entity; @Mock private FieldDto idField; @Mock private JDOMetadata jdoMetadata; @Mock private PackageMetadata packageMetadata; @Mock private ClassMetadata classMetadata; @Mock private FieldMetadata idMetadata; @Mock private InheritanceMetadata inheritanceMetadata; @Mock private IndexMetadata indexMetadata; @Mock private SchemaHolder schemaHolder; @Before public void setUp() { initMocks(this); when(entity.getClassName()).thenReturn(CLASS_NAME); when(classMetadata.newFieldMetadata("id")).thenReturn(idMetadata); when(idMetadata.getName()).thenReturn("id"); when(classMetadata.newInheritanceMetadata()).thenReturn(inheritanceMetadata); when(schemaHolder.getFieldByName(entity, "id")).thenReturn(idField); when(entity.isBaseEntity()).thenReturn(true); } @Test public void shouldAddEntityMetadata() throws Exception { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getModule()).thenReturn(MODULE); when(entity.getNamespace()).thenReturn(NAMESPACE); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(jdoMetadata).newPackageMetadata(PACKAGE); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_3); verifyCommonClassMetadata(); } @Test public void shouldAddToAnExistingPackage() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.getPackages()).thenReturn(new PackageMetadata[]{packageMetadata}); when(packageMetadata.getName()).thenReturn(PACKAGE); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(jdoMetadata, never()).newPackageMetadata(PACKAGE); verify(jdoMetadata).getPackages(); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_1); verifyCommonClassMetadata(); } @Test public void shouldSetAppropriateTableName() throws Exception { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(classMetadata).setTable(TABLE_NAME_1); when(entity.getModule()).thenReturn(MODULE); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(classMetadata).setTable(TABLE_NAME_2); when(entity.getNamespace()).thenReturn(NAMESPACE); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(classMetadata).setTable(TABLE_NAME_3); } @Test public void shouldAddBaseEntityMetadata() throws Exception { CtField ctField = mock(CtField.class); CtClass ctClass = mock(CtClass.class); CtClass superClass = mock(CtClass.class); ClassData classData = mock(ClassData.class); ClassPool pool = mock(ClassPool.class); PowerMockito.mockStatic(MotechClassPool.class); PowerMockito.when(MotechClassPool.getDefault()).thenReturn(pool); when(classData.getClassName()).thenReturn(CLASS_NAME); when(classData.getModule()).thenReturn(MODULE); when(classData.getNamespace()).thenReturn(NAMESPACE); when(entity.getTableName()).thenReturn(TABLE_NAME); when(pool.getOrNull(CLASS_NAME)).thenReturn(ctClass); when(ctClass.getField("id")).thenReturn(ctField); when(ctClass.getSuperclass()).thenReturn(superClass); when(superClass.getName()).thenReturn(Object.class.getName()); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addBaseMetadata(jdoMetadata, classData, EntityType.STANDARD, Sample.class); verify(jdoMetadata).newPackageMetadata(PACKAGE); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_3); verifyCommonClassMetadata(); } @Test public void shouldAddOneToManyRelationshipMetadata() { FieldDto oneToManyField = fieldDto("oneToManyName", OneToManyRelationship.class); oneToManyField.addMetadata(new MetadataDto(RELATED_CLASS, "org.motechproject.test.MyClass")); FieldMetadata fmd = mock(FieldMetadata.class); CollectionMetadata collMd = mock(CollectionMetadata.class); when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getId()).thenReturn(2L); when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToManyField)); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); when(classMetadata.newFieldMetadata("oneToManyName")).thenReturn(fmd); when(fmd.getCollectionMetadata()).thenReturn(collMd); when(fmd.getName()).thenReturn("oneToManyName"); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verifyCommonClassMetadata(); verify(fmd).setDefaultFetchGroup(true); verify(collMd).setEmbeddedElement(false); verify(collMd).setSerializedElement(false); verify(collMd).setElementType("org.motechproject.test.MyClass"); } @Test public void shouldAddOneToOneRelationshipMetadata() throws NotFoundException, CannotCompileException { final String relClassName = "org.motechproject.test.MyClass"; final String relFieldName = "myField"; FieldDto oneToOneField = fieldDto("oneToOneName", OneToOneRelationship.class); oneToOneField.addMetadata(new MetadataDto(RELATED_CLASS, relClassName)); oneToOneField.addMetadata(new MetadataDto(RELATED_FIELD, relFieldName)); FieldMetadata fmd = mock(FieldMetadata.class); when(fmd.getName()).thenReturn("oneToOneName"); ForeignKeyMetadata fkmd = mock(ForeignKeyMetadata.class); when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getId()).thenReturn(3L); when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToOneField)); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); when(classMetadata.newFieldMetadata("oneToOneName")).thenReturn(fmd); when(fmd.newForeignKeyMetadata()).thenReturn(fkmd); /* We simulate configuration for the bi-directional relationship (the related class has got a field that links back to the main class) */ CtClass myClass = mock(CtClass.class); CtClass relatedClass = mock(CtClass.class); CtField myField = mock(CtField.class); CtField relatedField = mock(CtField.class); when(myClass.getName()).thenReturn(relClassName); when(myClass.getDeclaredFields()).thenReturn(new CtField[]{myField}); when(myField.getType()).thenReturn(relatedClass); when(myField.getName()).thenReturn(relFieldName); when(relatedClass.getDeclaredFields()).thenReturn(new CtField[]{relatedField}); when(relatedClass.getName()).thenReturn(CLASS_NAME); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verifyCommonClassMetadata(); verify(fmd).setDefaultFetchGroup(true); verify(fmd).setPersistenceModifier(PersistenceModifier.PERSISTENT); verify(fkmd).setName("fk_Sample_oneToOneName_3"); } @Test public void shouldSetIndexOnMetadataLookupField() throws Exception { FieldDto lookupField = fieldDto("lookupField", String.class); LookupDto lookup = new LookupDto(); lookup.setLookupName("A lookup"); lookup.setLookupFields(singletonList(new LookupFieldDto("lookupField", LookupFieldType.VALUE))); lookup.setIndexRequired(true); lookupField.setLookups(singletonList(lookup)); FieldMetadata fmd = mock(FieldMetadata.class); when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getId()).thenReturn(14L); when(schemaHolder.getFields(entity)).thenReturn(singletonList(lookupField)); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); when(classMetadata.newFieldMetadata("lookupField")).thenReturn(fmd); when(fmd.newIndexMetadata()).thenReturn(indexMetadata); PowerMockito.mockStatic(FieldUtils.class); when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg")); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verifyCommonClassMetadata(); verify(fmd).newIndexMetadata(); verify(indexMetadata).setName("lkp_idx_" + ENTITY_NAME + "_lookupField_14"); } @Test public void shouldAddObjectValueGeneratorToAppropriateFields() throws Exception { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); List<FieldDto> fields = new ArrayList<>(); // for these fields the appropriate generator should be added fields.add(fieldDto(1L, CREATOR_FIELD_NAME, String.class.getName(), CREATOR_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(2L, OWNER_FIELD_NAME, String.class.getName(), OWNER_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(3L, CREATION_DATE_FIELD_NAME, DateTime.class.getName(), CREATION_DATE_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(4L, MODIFIED_BY_FIELD_NAME, String.class.getName(), MODIFIED_BY_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(5L, MODIFICATION_DATE_FIELD_NAME, DateTime.class.getName(), MODIFICATION_DATE_DISPLAY_FIELD_NAME, null)); doReturn(fields).when(schemaHolder).getFields(CLASS_NAME); final List<FieldMetadata> list = new ArrayList<>(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { // we create a mock ... FieldMetadata metadata = mock(FieldMetadata.class); // ... and it should return correct name doReturn(invocation.getArguments()[0]).when(metadata).getName(); // Because we want to check that appropriate methods was executed // we added metadata to list and later we will verify conditions list.add(metadata); // in the end we have to return the mock return metadata; } }).when(classMetadata).newFieldMetadata(anyString()); PowerMockito.mockStatic(FieldUtils.class); when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg")); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); for (FieldMetadata metadata : list) { String name = metadata.getName(); // the id field should not have set object value generator metadata int invocations = "id".equalsIgnoreCase(name) ? 0 : 1; verify(classMetadata).newFieldMetadata(name); verify(metadata, times(invocations)).setPersistenceModifier(PersistenceModifier.PERSISTENT); verify(metadata, times(invocations)).setDefaultFetchGroup(true); verify(metadata, times(invocations)).newExtensionMetadata(DATANUCLEUS, VALUE_GENERATOR, "ovg." + name); } } @Test public void shouldNotSetDefaultInheritanceStrategyIfUserDefinedOwn() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, AnotherSample.class, schemaHolder); verifyZeroInteractions(inheritanceMetadata); } @Test public void shouldNotSetDefaultFetchGroupIfSpecified() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); FieldDto field = fieldDto("notInDefFg", OneToOneRelationship.class); when(schemaHolder.getFields(CLASS_NAME)).thenReturn(singletonList(field)); FieldMetadata fmd = mock(FieldMetadata.class); when(fmd.getName()).thenReturn("notInDefFg"); when(classMetadata.newFieldMetadata("notInDefFg")).thenReturn(fmd); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(fmd, never()).setDefaultFetchGroup(anyBoolean()); } @Test public void shouldMarkEudeFieldsAsUnique() { when(entity.getName()).thenReturn(ENTITY_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); FieldDto eudeField = mock(FieldDto.class); FieldBasicDto eudeBasic = mock(FieldBasicDto.class); when(eudeField.getBasic()).thenReturn(eudeBasic); when(eudeBasic.getName()).thenReturn("uniqueField"); when(eudeField.isReadOnly()).thenReturn(false); when(eudeBasic.isUnique()).thenReturn(true); when(eudeField.getType()).thenReturn(TypeDto.STRING); FieldDto ddeField = mock(FieldDto.class); FieldBasicDto ddeBasic = mock(FieldBasicDto.class); when(ddeField.getBasic()).thenReturn(ddeBasic); when(ddeBasic.getName()).thenReturn("uniqueField2"); when(ddeField.isReadOnly()).thenReturn(true); when(ddeBasic.isUnique()).thenReturn(true); when(ddeField.getType()).thenReturn(TypeDto.STRING); when(schemaHolder.getFields(entity)).thenReturn(asList(ddeField, eudeField)); FieldMetadata fmdEude = mock(FieldMetadata.class); when(fmdEude.getName()).thenReturn("uniqueField"); when(classMetadata.newFieldMetadata("uniqueField")).thenReturn(fmdEude); FieldMetadata fmdDde = mock(FieldMetadata.class); when(fmdDde.getName()).thenReturn("uniqueField2"); when(classMetadata.newFieldMetadata("uniqueField2")).thenReturn(fmdDde); UniqueMetadata umd = mock(UniqueMetadata.class); when(fmdEude.newUniqueMetadata()).thenReturn(umd); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(fmdDde, never()).newUniqueMetadata(); verify(fmdDde, never()).setUnique(anyBoolean()); verify(fmdEude).newUniqueMetadata(); verify(umd).setName("unq_Sample_uniqueField"); } @Test public void shouldSetIncrementStrategy() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getModule()).thenReturn(MODULE); when(entity.getNamespace()).thenReturn(NAMESPACE); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, SampleWithIncrementStrategy.class, schemaHolder); verify(jdoMetadata).newPackageMetadata(PACKAGE); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_3); verifyCommonClassMetadata(IdGeneratorStrategy.INCREMENT); } private void verifyCommonClassMetadata() { verifyCommonClassMetadata(IdGeneratorStrategy.NATIVE); } private void verifyCommonClassMetadata(IdGeneratorStrategy expextedStrategy) { verify(classMetadata).setDetachable(true); verify(classMetadata).setIdentityType(IdentityType.APPLICATION); verify(classMetadata).setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE); verify(idMetadata).setPrimaryKey(true); verify(idMetadata).setValueStrategy(expextedStrategy); verify(inheritanceMetadata).setCustomStrategy("complete-table"); } }
sebbrudzinski/motech
platform/mds/mds/src/test/java/org/motechproject/mds/builder/impl/EntityMetadataBuilderTest.java
Java
bsd-3-clause
22,796
package org.spongycastle.crypto.test; import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.digests.SHA256Digest; /** * standard vector test for SHA-256 from FIPS Draft 180-2. * * Note, the first two vectors are _not_ from the draft, the last three are. */ public class SHA256DigestTest extends DigestTest { private static String[] messages = { "", "a", "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }; private static String[] digests = { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" }; // 1 million 'a' static private String million_a_digest = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"; SHA256DigestTest() { super(new SHA256Digest(), messages, digests); } public void performTest() { super.performTest(); millionATest(million_a_digest); } protected Digest cloneDigest(Digest digest) { return new SHA256Digest((SHA256Digest)digest); } protected Digest cloneDigest(byte[] encodedState) { return new SHA256Digest(encodedState); } public static void main( String[] args) { runTest(new SHA256DigestTest()); } }
Skywalker-11/spongycastle
core/src/test/java/org/spongycastle/crypto/test/SHA256DigestTest.java
Java
mit
1,536
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.dsmr.internal.device; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.io.transport.serial.SerialPortManager; import org.openhab.binding.dsmr.internal.device.connector.DSMRConnectorErrorEvent; import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialConnector; import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialSettings; import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DSMR Serial device that auto discovers the serial port speed. * * @author M. Volaart - Initial contribution * @author Hilbrand Bouwkamp - New class. Simplified states and contains code specific to discover the serial port * settings automatically. */ @NonNullByDefault public class DSMRSerialAutoDevice implements DSMRDevice, DSMREventListener { /** * Enum to keep track of the internal state of {@link DSMRSerialAutoDevice}. */ enum DeviceState { /** * Discovers the settings of the serial port. */ DISCOVER_SETTINGS, /** * Device is receiving telegram data from the serial port. */ NORMAL, /** * Communication with serial port isn't working. */ ERROR } /** * When switching baudrate ignore any errors received with the given time frame. Switching baudrate causes errors * and should not be interpreted as reading errors. */ private static final long SWITCHING_BAUDRATE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(5); /** * This factor is multiplied with the {@link #baudrateSwitchTimeoutSeconds} and used as the duration the discovery * of the baudrate may take. */ private static final int DISCOVER_TIMEOUT_FACTOR = 4; /* * Februari 2017 * Due to the Dutch Smart Meter program where every residence is provided * a smart for free and the smart meters are DSMR V4 or higher * we assume the majority of meters communicate with HIGH_SPEED_SETTINGS * For older meters this means initializing is taking probably 1 minute */ private static final DSMRSerialSettings DEFAULT_PORT_SETTINGS = DSMRSerialSettings.HIGH_SPEED_SETTINGS; private final Logger logger = LoggerFactory.getLogger(DSMRSerialAutoDevice.class); /** * DSMR Connector to the serial port */ private final DSMRSerialConnector dsmrConnector; private final ScheduledExecutorService scheduler; private final DSMRTelegramListener telegramListener; /** * Time in seconds in which period valid data is expected during discovery. If exceeded without success the baudrate * is switched */ private final int baudrateSwitchTimeoutSeconds; /** * Serial port connection settings */ private DSMRSerialSettings portSettings = DEFAULT_PORT_SETTINGS; /** * Keeps track of the state this instance is in. */ private DeviceState state = DeviceState.NORMAL; /** * Timer for handling discovery of a single setting. */ private @Nullable ScheduledFuture<?> halfTimeTimer; /** * Timer for handling end of discovery. */ private @Nullable ScheduledFuture<?> endTimeTimer; /** * The listener of the class handling the connector events */ private DSMREventListener parentListener; /** * Time in nanos the last time the baudrate was switched. This is used during discovery ignore errors retrieved * after switching baudrate for the period set in {@link #SWITCHING_BAUDRATE_TIMEOUT_NANOS}. */ private long lastSwitchedBaudrateNanos; /** * Creates a new {@link DSMRSerialAutoDevice} * * @param serialPortManager the manager to get a new serial port connecting from * @param serialPortName the port name (e.g. /dev/ttyUSB0 or COM1) * @param listener the parent {@link DSMREventListener} * @param scheduler the scheduler to use with the baudrate switching timers * @param baudrateSwitchTimeoutSeconds timeout period for when to try other baudrate settings and end the discovery * of the baudrate */ public DSMRSerialAutoDevice(SerialPortManager serialPortManager, String serialPortName, DSMREventListener listener, ScheduledExecutorService scheduler, int baudrateSwitchTimeoutSeconds) { this.parentListener = listener; this.scheduler = scheduler; this.baudrateSwitchTimeoutSeconds = baudrateSwitchTimeoutSeconds; telegramListener = new DSMRTelegramListener(listener); dsmrConnector = new DSMRSerialConnector(serialPortManager, serialPortName, telegramListener); logger.debug("Initialized port '{}'", serialPortName); } @Override public void start() { stopDiscover(DeviceState.DISCOVER_SETTINGS); portSettings = DEFAULT_PORT_SETTINGS; telegramListener.setDsmrEventListener(this); dsmrConnector.open(portSettings); restartHalfTimer(); endTimeTimer = scheduler.schedule(this::endTimeScheduledCall, baudrateSwitchTimeoutSeconds * DISCOVER_TIMEOUT_FACTOR, TimeUnit.SECONDS); } @Override public void restart() { if (state == DeviceState.ERROR) { stop(); start(); } else if (state == DeviceState.NORMAL) { dsmrConnector.restart(portSettings); } } @Override public synchronized void stop() { dsmrConnector.close(); stopDiscover(state); logger.trace("stopped with state:{}", state); } /** * Handle if telegrams are received. * * @param telegram the details of the received telegram */ @Override public void handleTelegramReceived(P1Telegram telegram) { if (!telegram.getCosemObjects().isEmpty()) { stopDiscover(DeviceState.NORMAL); parentListener.handleTelegramReceived(telegram); logger.info("Start receiving telegrams on port {} with settings: {}", dsmrConnector.getPortName(), portSettings); } } /** * Event handler for DSMR Port events. * * @param portEvent {@link DSMRConnectorErrorEvent} to handle */ @Override public void handleErrorEvent(DSMRConnectorErrorEvent portEvent) { logger.trace("Received portEvent {}", portEvent.getEventDetails()); if (portEvent == DSMRConnectorErrorEvent.READ_ERROR) { switchBaudrate(); } else { logger.debug("Error during discovery of port settings: {}, current state:{}.", portEvent.getEventDetails(), state); stopDiscover(DeviceState.ERROR); parentListener.handleErrorEvent(portEvent); } } /** * @param lenientMode the lenientMode to set */ @Override public void setLenientMode(boolean lenientMode) { telegramListener.setLenientMode(lenientMode); } /** * @return Returns the state of the instance. Used for testing only. */ DeviceState getState() { return state; } /** * Switches the baudrate on the serial port. */ private void switchBaudrate() { if (lastSwitchedBaudrateNanos + SWITCHING_BAUDRATE_TIMEOUT_NANOS > System.nanoTime()) { // Ignore switching baudrate if this is called within the timeout after a previous switch. return; } lastSwitchedBaudrateNanos = System.nanoTime(); if (state == DeviceState.DISCOVER_SETTINGS) { restartHalfTimer(); logger.debug( "Discover port settings is running for half time now and still nothing discovered, switching baudrate and retrying"); portSettings = portSettings == DSMRSerialSettings.HIGH_SPEED_SETTINGS ? DSMRSerialSettings.LOW_SPEED_SETTINGS : DSMRSerialSettings.HIGH_SPEED_SETTINGS; dsmrConnector.setSerialPortParams(portSettings); } } /** * Stops the discovery process as triggered by the end timer. It will only act if the discovery process was still * running. */ private void endTimeScheduledCall() { if (state == DeviceState.DISCOVER_SETTINGS) { stopDiscover(DeviceState.ERROR); parentListener.handleErrorEvent(DSMRConnectorErrorEvent.DONT_EXISTS); } } /** * Stops the discovery of port speed process and sets the state with which it should be stopped. * * @param state the state with which the process was stopped. */ private void stopDiscover(DeviceState state) { telegramListener.setDsmrEventListener(parentListener); logger.debug("Stop discovery of port settings."); if (halfTimeTimer != null) { halfTimeTimer.cancel(true); halfTimeTimer = null; } if (endTimeTimer != null) { endTimeTimer.cancel(true); endTimeTimer = null; } this.state = state; } /** * Method to (re)start the switching baudrate timer. */ private void restartHalfTimer() { if (halfTimeTimer != null) { halfTimeTimer.cancel(true); } halfTimeTimer = scheduler.schedule(this::switchBaudrate, baudrateSwitchTimeoutSeconds, TimeUnit.SECONDS); } }
afuechsel/openhab2
addons/binding/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRSerialAutoDevice.java
Java
epl-1.0
9,975
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.yamahareceiver.internal.state; import static org.openhab.binding.yamahareceiver.YamahaReceiverBindingConstants.VALUE_EMPTY; /** * The state of a specific zone of a Yamaha receiver. * * @author David Graeff <david.graeff@web.de> * */ public class ZoneControlState { public boolean power = false; // User visible name of the input channel for the current zone public String inputName = VALUE_EMPTY; // The ID of the input channel that is used as xml tags (for example NET_RADIO, HDMI_1). // This may differ from what the AVR returns in Input/Input_Sel ("NET RADIO", "HDMI1") public String inputID = VALUE_EMPTY; public String surroundProgram = VALUE_EMPTY; public float volumeDB = 0.0f; // volume in dB public boolean mute = false; public int dialogueLevel = 0; }
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/state/ZoneControlState.java
Java
epl-1.0
1,158
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.nikohomecontrol.internal.protocol; /** * Class {@link NhcMessageBase} used as base class for output from gson for cmd or event feedback from Niko Home * Control. This class only contains the common base fields required for the deserializer * {@link NikoHomeControlMessageDeserializer} to select the specific formats implemented in {@link NhcMessageMap}, * {@link NhcMessageListMap}, {@link NhcMessageCmd}. * <p> * * @author Mark Herwege - Initial Contribution */ abstract class NhcMessageBase { private String cmd; private String event; String getCmd() { return this.cmd; } void setCmd(String cmd) { this.cmd = cmd; } String getEvent() { return this.event; } void setEvent(String event) { this.event = event; } }
aogorek/openhab2-addons
addons/binding/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NhcMessageBase.java
Java
epl-1.0
1,148
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8163346 * @summary Test hashing of extended characters in Serviceability Agent. * @library /test/lib * @library /lib/testlibrary * @compile -encoding utf8 HeapDumpTest.java * @run main/timeout=240 HeapDumpTest */ import static jdk.testlibrary.Asserts.assertTrue; import java.io.IOException; import java.io.File; import java.util.List; import java.util.Arrays; import jdk.testlibrary.JDKToolLauncher; import jdk.testlibrary.OutputAnalyzer; import jdk.testlibrary.ProcessTools; import jdk.test.lib.apps.LingeredApp; import jdk.test.lib.Platform; public class HeapDumpTest { private static LingeredAppWithExtendedChars theApp = null; /** * * @param vmArgs - tool arguments to launch jhsdb * @return exit code of tool */ public static void launch(String expectedMessage, List<String> toolArgs) throws IOException { System.out.println("Starting LingeredApp"); try { theApp = new LingeredAppWithExtendedChars(); LingeredApp.startApp(Arrays.asList("-Xmx256m"), theApp); System.out.println(theApp.\u00CB); System.out.println("Starting " + toolArgs.get(0) + " against " + theApp.getPid()); JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jhsdb"); for (String cmd : toolArgs) { launcher.addToolArg(cmd); } launcher.addToolArg("--pid=" + Long.toString(theApp.getPid())); ProcessBuilder processBuilder = new ProcessBuilder(launcher.getCommand()); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); System.out.println("stdout:"); System.out.println(output.getStdout()); System.out.println("stderr:"); System.out.println(output.getStderr()); output.shouldContain(expectedMessage); output.shouldHaveExitValue(0); } catch (Exception ex) { throw new RuntimeException("Test ERROR " + ex, ex); } finally { LingeredApp.stopApp(theApp); } } public static void launch(String expectedMessage, String... toolArgs) throws IOException { launch(expectedMessage, Arrays.asList(toolArgs)); } public static void testHeapDump() throws IOException { File dump = new File("jhsdb.jmap.heap." + System.currentTimeMillis() + ".hprof"); if (dump.exists()) { dump.delete(); } launch("heap written to", "jmap", "--binaryheap", "--dumpfile=" + dump.getAbsolutePath()); assertTrue(dump.exists() && dump.isFile(), "Could not create dump file " + dump.getAbsolutePath()); dump.delete(); } public static void main(String[] args) throws Exception { if (!Platform.shouldSAAttach()) { // Silently skip the test if we don't have enough permissions to attach System.err.println("Error! Insufficient permissions to attach - test skipped."); return; } testHeapDump(); // The test throws RuntimeException on error. // IOException is thrown if LingeredApp can't start because of some bad // environment condition System.out.println("Test PASSED"); } }
YouDiSN/OpenJDK-Research
jdk9/jdk/test/sun/tools/jhsdb/HeapDumpTest.java
Java
gpl-2.0
4,479
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.List; import java.util.Properties; import org.compiere.util.DB; /** * Shipment Material Allocation * * @author Jorg Janke * @version $Id: MInOutLineMA.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ */ public class MInOutLineMA extends X_M_InOutLineMA { /** * */ private static final long serialVersionUID = -3229418883339488380L; /** * Get Material Allocations for Line * @param ctx context * @param M_InOutLine_ID line * @param trxName trx * @return allocations */ public static MInOutLineMA[] get (Properties ctx, int M_InOutLine_ID, String trxName) { Query query = MTable.get(ctx, MInOutLineMA.Table_Name) .createQuery(I_M_InOutLineMA.COLUMNNAME_M_InOutLine_ID+"=?", trxName); query.setParameters(M_InOutLine_ID); List<MInOutLineMA> list = query.list(); MInOutLineMA[] retValue = new MInOutLineMA[list.size ()]; list.toArray (retValue); return retValue; } // get /** * Delete all Material Allocation for InOut * @param M_InOut_ID shipment * @param trxName transaction * @return number of rows deleted or -1 for error */ public static int deleteInOutMA (int M_InOut_ID, String trxName) { String sql = "DELETE FROM M_InOutLineMA ma WHERE EXISTS " + "(SELECT * FROM M_InOutLine l WHERE l.M_InOutLine_ID=ma.M_InOutLine_ID" + " AND M_InOut_ID=" + M_InOut_ID + ")"; return DB.executeUpdate(sql, trxName); } // deleteInOutMA /** * Delete all Material Allocation for InOutLine * @param M_InOutLine_ID Shipment Line * @param trxName transaction * @return number of rows deleted or -1 for error */ public static int deleteInOutLineMA (int M_InOutLine_ID, String trxName) { String sql = "DELETE FROM M_InOutLineMA ma WHERE ma.M_InOutLine_ID=?"; return DB.executeUpdate(sql, M_InOutLine_ID, trxName); } // deleteInOutLineMA // /** Logger */ // private static CLogger s_log = CLogger.getCLogger (MInOutLineMA.class); /************************************************************************** * Standard Constructor * @param ctx context * @param M_InOutLineMA_ID ignored * @param trxName trx */ public MInOutLineMA (Properties ctx, int M_InOutLineMA_ID, String trxName) { super (ctx, M_InOutLineMA_ID, trxName); if (M_InOutLineMA_ID != 0) throw new IllegalArgumentException("Multi-Key"); } // MInOutLineMA /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MInOutLineMA (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MInOutLineMA /** * Parent Constructor * @param parent parent * @param M_AttributeSetInstance_ID asi * @param MovementQty qty */ public MInOutLineMA (MInOutLine parent, int M_AttributeSetInstance_ID, BigDecimal MovementQty) { this (parent.getCtx(), 0, parent.get_TrxName()); setClientOrg(parent); setM_InOutLine_ID(parent.getM_InOutLine_ID()); // setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); setMovementQty(MovementQty); } // MInOutLineMA /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MInOutLineMA["); sb.append("M_InOutLine_ID=").append(getM_InOutLine_ID()) .append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID()) .append(", Qty=").append(getMovementQty()) .append ("]"); return sb.toString (); } // toString } // MInOutLineMA
erpcya/adempierePOS
base/src/org/compiere/model/MInOutLineMA.java
Java
gpl-2.0
4,940
/* * #%L * Bio-Formats Plugins for ImageJ: a collection of ImageJ plugins including the * Bio-Formats Importer, Bio-Formats Exporter, Bio-Formats Macro Extensions, * Data Browser and Stack Slicer. * %% * Copyright (C) 2006 - 2015 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package loci.plugins.util; import ij.IJ; import ij.ImageJ; import ij.gui.GenericDialog; import java.awt.BorderLayout; import java.awt.Checkbox; import java.awt.Choice; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Panel; import java.awt.Point; import java.awt.Rectangle; import java.awt.ScrollPane; import java.awt.TextField; import java.awt.Toolkit; import java.awt.Window; import java.util.List; import java.util.StringTokenizer; import loci.common.DebugTools; import loci.plugins.BF; /** * Utility methods for managing ImageJ dialogs and windows. */ public final class WindowTools { // -- Constructor -- private WindowTools() { } // -- Utility methods -- /** Adds AWT scroll bars to the given container. */ public static void addScrollBars(Container pane) { GridBagLayout layout = (GridBagLayout) pane.getLayout(); // extract components int count = pane.getComponentCount(); Component[] c = new Component[count]; GridBagConstraints[] gbc = new GridBagConstraints[count]; for (int i=0; i<count; i++) { c[i] = pane.getComponent(i); gbc[i] = layout.getConstraints(c[i]); } // clear components pane.removeAll(); layout.invalidateLayout(pane); // create new container panel Panel newPane = new Panel(); GridBagLayout newLayout = new GridBagLayout(); newPane.setLayout(newLayout); for (int i=0; i<count; i++) { newLayout.setConstraints(c[i], gbc[i]); newPane.add(c[i]); } // HACK - get preferred size for container panel // NB: don't know a better way: // - newPane.getPreferredSize() doesn't work // - newLayout.preferredLayoutSize(newPane) doesn't work Frame f = new Frame(); f.setLayout(new BorderLayout()); f.add(newPane, BorderLayout.CENTER); f.pack(); final Dimension size = newPane.getSize(); f.remove(newPane); f.dispose(); // compute best size for scrollable viewport size.width += 25; size.height += 15; Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int maxWidth = 7 * screen.width / 8; int maxHeight = 3 * screen.height / 4; if (size.width > maxWidth) size.width = maxWidth; if (size.height > maxHeight) size.height = maxHeight; // create scroll pane ScrollPane scroll = new ScrollPane() { @Override public Dimension getPreferredSize() { return size; } }; scroll.add(newPane); // add scroll pane to original container GridBagConstraints constraints = new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; layout.setConstraints(scroll, constraints); pane.add(scroll); } /** * Places the given window at a nice location on screen, either centered * below the ImageJ window if there is one, or else centered on screen. */ public static void placeWindow(Window w) { Dimension size = w.getSize(); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); ImageJ ij = IJ.getInstance(); Point p = new Point(); if (ij == null) { // center config window on screen p.x = (screen.width - size.width) / 2; p.y = (screen.height - size.height) / 2; } else { // place config window below ImageJ window Rectangle ijBounds = ij.getBounds(); p.x = ijBounds.x + (ijBounds.width - size.width) / 2; p.y = ijBounds.y + ijBounds.height + 5; } // nudge config window away from screen edges final int pad = 10; if (p.x < pad) p.x = pad; else if (p.x + size.width + pad > screen.width) { p.x = screen.width - size.width - pad; } if (p.y < pad) p.y = pad; else if (p.y + size.height + pad > screen.height) { p.y = screen.height - size.height - pad; } w.setLocation(p); } /** Reports the given exception with stack trace in an ImageJ error dialog. */ public static void reportException(Throwable t) { reportException(t, false, null); } /** Reports the given exception with stack trace in an ImageJ error dialog. */ public static void reportException(Throwable t, boolean quiet) { reportException(t, quiet, null); } /** Reports the given exception with stack trace in an ImageJ error dialog. */ public static void reportException(Throwable t, boolean quiet, String msg) { if (quiet) return; BF.status(quiet, ""); if (t != null) { String s = DebugTools.getStackTrace(t); StringTokenizer st = new StringTokenizer(s, "\n\r"); while (st.hasMoreTokens()) IJ.log(st.nextToken()); } if (msg != null) IJ.error("Bio-Formats Importer", msg); } @SuppressWarnings("unchecked") public static List<TextField> getNumericFields(GenericDialog gd) { return gd.getNumericFields(); } @SuppressWarnings("unchecked") public static List<Checkbox> getCheckboxes(GenericDialog gd) { return gd.getCheckboxes(); } @SuppressWarnings("unchecked") public static List<Choice> getChoices(GenericDialog gd) { return gd.getChoices(); } }
dgault/bioformats
components/bio-formats-plugins/src/loci/plugins/util/WindowTools.java
Java
gpl-2.0
6,353
/** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.core.internal.resources; import org.eclipse.osgi.util.NLS; /** * * @author Ingo Muschenetz * */ public final class Messages extends NLS { private static final String BUNDLE_NAME = "com.aptana.core.internal.resources.messages"; //$NON-NLS-1$ private Messages() { } static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } /** * MarkerManager_MarkerIDIsDefined */ public static String MarkerManager_MarkerIDIsDefined; /** * UniformResourceMarker_UniformResourceMarketInfoNull */ public static String UniformResourceMarker_UniformResourceMarketInfoNull; }
HossainKhademian/Studio3
plugins/com.aptana.core/src/com/aptana/core/internal/resources/Messages.java
Java
gpl-3.0
969
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.scenes; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.Statistics; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.windows.WndError; import com.shatteredpixel.shatteredpixeldungeon.windows.WndStory; import com.watabou.noosa.BitmapText; import com.watabou.noosa.Camera; import com.watabou.noosa.Game; import com.watabou.noosa.audio.Music; import com.watabou.noosa.audio.Sample; import java.io.FileNotFoundException; import java.io.IOException; public class InterlevelScene extends PixelScene { private static final float TIME_TO_FADE = 0.3f; private static final String TXT_DESCENDING = "Descending..."; private static final String TXT_ASCENDING = "Ascending..."; private static final String TXT_LOADING = "Loading..."; private static final String TXT_RESURRECTING= "Resurrecting..."; private static final String TXT_RETURNING = "Returning..."; private static final String TXT_FALLING = "Falling..."; private static final String ERR_FILE_NOT_FOUND = "Save file not found. If this error persists after restarting, " + "it may mean this save game is corrupted. Sorry about that."; private static final String ERR_IO = "Cannot read save file. If this error persists after restarting, " + "it may mean this save game is corrupted. Sorry about that."; public static enum Mode { DESCEND, ASCEND, CONTINUE, RESURRECT, RETURN, FALL }; public static Mode mode; public static int returnDepth; public static int returnPos; public static boolean noStory = false; public static boolean fallIntoPit; private enum Phase { FADE_IN, STATIC, FADE_OUT }; private Phase phase; private float timeLeft; private BitmapText message; private Thread thread; private Exception error = null; @Override public void create() { super.create(); String text = ""; switch (mode) { case DESCEND: text = TXT_DESCENDING; break; case ASCEND: text = TXT_ASCENDING; break; case CONTINUE: text = TXT_LOADING; break; case RESURRECT: text = TXT_RESURRECTING; break; case RETURN: text = TXT_RETURNING; break; case FALL: text = TXT_FALLING; break; } message = PixelScene.createText( text, 9 ); message.measure(); message.x = (Camera.main.width - message.width()) / 2; message.y = (Camera.main.height - message.height()) / 2; add( message ); phase = Phase.FADE_IN; timeLeft = TIME_TO_FADE; thread = new Thread() { @Override public void run() { try { Generator.reset(); switch (mode) { case DESCEND: descend(); break; case ASCEND: ascend(); break; case CONTINUE: restore(); break; case RESURRECT: resurrect(); break; case RETURN: returnTo(); break; case FALL: fall(); break; } if ((Dungeon.depth % 5) == 0) { Sample.INSTANCE.load( Assets.SND_BOSS ); } } catch (Exception e) { error = e; } if (phase == Phase.STATIC && error == null) { phase = Phase.FADE_OUT; timeLeft = TIME_TO_FADE; } } }; thread.start(); } @Override public void update() { super.update(); float p = timeLeft / TIME_TO_FADE; switch (phase) { case FADE_IN: message.alpha( 1 - p ); if ((timeLeft -= Game.elapsed) <= 0) { if (!thread.isAlive() && error == null) { phase = Phase.FADE_OUT; timeLeft = TIME_TO_FADE; } else { phase = Phase.STATIC; } } break; case FADE_OUT: message.alpha( p ); if (mode == Mode.CONTINUE || (mode == Mode.DESCEND && Dungeon.depth == 1)) { Music.INSTANCE.volume( p ); } if ((timeLeft -= Game.elapsed) <= 0) { Game.switchScene( GameScene.class ); } break; case STATIC: if (error != null) { String errorMsg; if (error instanceof FileNotFoundException) errorMsg = ERR_FILE_NOT_FOUND; else if (error instanceof IOException) errorMsg = ERR_IO; else throw new RuntimeException("fatal error occured while moving between floors", error); add( new WndError( errorMsg ) { public void onBackPressed() { super.onBackPressed(); Game.switchScene( StartScene.class ); }; } ); error = null; } break; } } private void descend() throws IOException { Actor.fixTime(); if (Dungeon.hero == null) { Dungeon.init(); if (noStory) { Dungeon.chapters.add( WndStory.ID_SEWERS ); noStory = false; } } else { Dungeon.saveLevel(); } Level level; if (Dungeon.depth >= Statistics.deepestFloor) { level = Dungeon.newLevel(); } else { Dungeon.depth++; level = Dungeon.loadLevel( Dungeon.hero.heroClass ); } Dungeon.switchLevel( level, level.entrance ); } private void fall() throws IOException { Actor.fixTime(); Dungeon.saveLevel(); Level level; if (Dungeon.depth >= Statistics.deepestFloor) { level = Dungeon.newLevel(); } else { Dungeon.depth++; level = Dungeon.loadLevel( Dungeon.hero.heroClass ); } Dungeon.switchLevel( level, fallIntoPit ? level.pitCell() : level.randomRespawnCell() ); } private void ascend() throws IOException { Actor.fixTime(); Dungeon.saveLevel(); Dungeon.depth--; Level level = Dungeon.loadLevel( Dungeon.hero.heroClass ); Dungeon.switchLevel( level, level.exit ); } private void returnTo() throws IOException { Actor.fixTime(); Dungeon.saveLevel(); Dungeon.depth = returnDepth; Level level = Dungeon.loadLevel( Dungeon.hero.heroClass ); Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( returnPos ) : returnPos ); } private void restore() throws IOException { Actor.fixTime(); Dungeon.loadGame( StartScene.curClass ); if (Dungeon.depth == -1) { Dungeon.depth = Statistics.deepestFloor; Dungeon.switchLevel( Dungeon.loadLevel( StartScene.curClass ), -1 ); } else { Level level = Dungeon.loadLevel( StartScene.curClass ); Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( Dungeon.hero.pos ) : Dungeon.hero.pos ); } } private void resurrect() throws IOException { Actor.fixTime(); if (Dungeon.level.locked) { Dungeon.hero.resurrect( Dungeon.depth ); Dungeon.depth--; Level level = Dungeon.newLevel(); Dungeon.switchLevel( level, level.entrance ); } else { Dungeon.hero.resurrect( -1 ); Dungeon.resetLevel(); } } @Override protected void onBackPressed() { //Do nothing } }
Lobz/reforged-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/scenes/InterlevelScene.java
Java
gpl-3.0
7,657
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.cg.service.impl; import java.util.ArrayList; import java.util.List; import org.kuali.kfs.module.cg.CGPropertyConstants; import org.kuali.kfs.module.cg.service.ContractsAndGrantsBillingService; /** * Service with methods related to the Contracts & Grants Billing (CGB) enhancement. */ public class ContractsAndGrantsBillingServiceImpl implements ContractsAndGrantsBillingService { @Override public List<String> getAgencyContractsGrantsBillingSectionIds() { List<String> contractsGrantsSectionIds = new ArrayList<String>(); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESSES_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_COLLECTIONS_MAINTENANCE_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CONTRACTS_AND_GRANTS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CUSTOMER_SECTION_ID); return contractsGrantsSectionIds; } @Override public List<String> getAwardContractsGrantsBillingSectionIds() { List<String> contractsGrantsSectionIds = new ArrayList<String>(); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_FUND_MANAGERS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_INVOICING_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_MILESTONE_SCHEDULE_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_PREDETERMINED_BILLING_SCHEDULE_SECTION_ID); return contractsGrantsSectionIds; } }
bhutchinson/kfs
kfs-cg/src/main/java/org/kuali/kfs/module/cg/service/impl/ContractsAndGrantsBillingServiceImpl.java
Java
agpl-3.0
2,589
package org.herac.tuxguitar.gui.util; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.player.base.MidiRepeatController; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGMeasureHeader; public class MidiTickUtil { public static long getStart(long tick){ long startPoint = getStartPoint(); long start = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ start += length; length = header.getLength(); //verifico si es el compas correcto if(tick >= start && tick < (start + length )){ return header.getStart() + (tick - start); } } } return ( tick < startPoint ? startPoint : start ); } public static long getTick(long start){ long startPoint = getStartPoint(); long tick = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ tick += length; length = header.getLength(); //verifico si es el compas correcto if(start >= header.getStart() && start < (header.getStart() + length )){ return tick; } } } return ( start < startPoint ? startPoint : tick ); } private static long getStartPoint(){ TuxGuitar.instance().getPlayer().updateLoop( false ); return TuxGuitar.instance().getPlayer().getLoopSPosition(); } public static int getSHeader() { return TuxGuitar.instance().getPlayer().getLoopSHeader(); } public static int getEHeader() { return TuxGuitar.instance().getPlayer().getLoopEHeader(); } }
elkafoury/tux
src/org/herac/tuxguitar/gui/util/MidiTickUtil.java
Java
lgpl-2.1
2,150
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.narayana.txframework.api.exception; /** * @deprecated The TXFramework API will be removed. The org.jboss.narayana.compensations API should be used instead. * The new API is superior for these reasons: * <p/> * i) offers a higher level API; * ii) The API very closely matches that of JTA, making it easier for developers to learn, * iii) It works for non-distributed transactions as well as distributed transactions. * iv) It is CDI based so only needs a CDI container to run, rather than a full Java EE server. * <p/> */ @Deprecated public class TXFrameworkException extends Exception { public TXFrameworkException(String message) { super(message); } public TXFrameworkException(String message, Throwable cause) { super(message, cause); } }
gytis/narayana
txframework/src/main/java/org/jboss/narayana/txframework/api/exception/TXFrameworkException.java
Java
lgpl-2.1
1,829
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK. // package org.jboss.jbossts.qa.RawResources02Clients2; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ import org.jboss.jbossts.qa.RawResources02.*; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.OTS; import org.jboss.jbossts.qa.Utils.ServerIORStore; import org.omg.CORBA.TRANSACTION_ROLLEDBACK; public class Client085 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]); Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1)); String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]); Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2)); ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1]; resourceBehaviors1[0] = new ResourceBehavior(); resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteRollback; resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1]; resourceBehaviors2[0] = new ResourceBehavior(); resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteReadOnly; resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; boolean correct = true; OTS.current().begin(); service1.oper(resourceBehaviors1, OTS.current().get_control()); service2.oper(resourceBehaviors2, OTS.current().get_control()); try { OTS.current().commit(true); System.err.println("Commit succeeded when it shouldn't"); correct = false; } catch (TRANSACTION_ROLLEDBACK transactionRolledback) { } correct = correct && service1.is_correct() && service2.is_correct(); if (!correct) { System.err.println("service1.is_correct() or service2.is_correct() returned false"); } ResourceTrace resourceTrace1 = service1.get_resource_trace(0); ResourceTrace resourceTrace2 = service2.get_resource_trace(0); correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareRollback); correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepare) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback)); if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); System.out.println("Failed"); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); } } }
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client085.java
Java
lgpl-2.1
4,881
package com.pi4j.io.gpio; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : GpioPinPwm.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2015 Pi4J * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * Gpio input pin interface. This interface is extension of {@link GpioPin} interface * with reading pwm values. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ @SuppressWarnings("unused") public interface GpioPinPwm extends GpioPin { int getPwm(); }
curvejumper/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/GpioPinPwm.java
Java
lgpl-3.0
1,511
/* * 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.beam.sdk.extensions.ml; import static org.junit.Assert.assertThrows; import java.util.List; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.PCollectionView; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DLPInspectTextTest { @Rule public TestPipeline testPipeline = TestPipeline.create(); private static final Integer BATCH_SIZE_SMALL = 200; private static final String DELIMITER = ";"; private static final String TEMPLATE_NAME = "test_template"; private static final String PROJECT_ID = "test_id"; @Test public void throwsExceptionWhenDeidentifyConfigAndTemplatesAreEmpty() { assertThrows( "Either inspectTemplateName or inspectConfig must be supplied!", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsNullAndHeadersAreSet() { PCollectionView<List<String>> header = testPipeline.apply(Create.of("header")).apply(View.asList()); assertThrows( "Column delimiter should be set if headers are present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setHeaderColumns(header) .build()); testPipeline.run().waitUntilFinish(); } @Test public void throwsExceptionWhenBatchSizeIsTooLarge() { assertThrows( String.format( "Batch size is too large! It should be smaller or equal than %d.", DLPInspectText.DLP_PAYLOAD_LIMIT_BYTES), IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(Integer.MAX_VALUE) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsSetAndHeadersAreNot() { assertThrows( "Column headers should be supplied when delimiter is present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } }
lukecwik/incubator-beam
sdks/java/extensions/ml/src/test/java/org/apache/beam/sdk/extensions/ml/DLPInspectTextTest.java
Java
apache-2.0
3,694
/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a full listing * of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ /* * Copyright (C) 2002, * * Arjuna Technologies Limited, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ */ package com.arjuna.wsas.tests; import com.arjuna.mw.wsas.context.Context; import com.arjuna.mw.wsas.UserActivityFactory; import com.arjuna.mw.wsas.common.GlobalId; import com.arjuna.mw.wsas.activity.Outcome; import com.arjuna.mw.wsas.activity.HLS; import com.arjuna.mw.wsas.completionstatus.CompletionStatus; import com.arjuna.mw.wsas.exceptions.*; import java.util.*; /** * @author Mark Little (mark.little@arjuna.com) * @version $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ * @since 1.0. */ public class DemoHLS implements HLS { private Stack<GlobalId> _id; public DemoHLS() { _id = new Stack<GlobalId>(); } /** * An activity has begun and is active on the current thread. */ public void begun () throws SystemException { try { GlobalId activityId = UserActivityFactory.userActivity().activityId(); _id.push(activityId); System.out.println("DemoHLS.begun "+activityId); } catch (Exception ex) { ex.printStackTrace(); } } /** * The current activity is completing with the specified completion status. * * @return The result of terminating the relationship of this HLS and * the current activity. */ public Outcome complete (CompletionStatus cs) throws SystemException { try { System.out.println("DemoHLS.complete ( "+cs+" ) " + UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * The activity has been suspended. How does the HLS know which activity * has been suspended? It must remember what its notion of current is. */ public void suspended () throws SystemException { System.out.println("DemoHLS.suspended"); } /** * The activity has been resumed on the current thread. */ public void resumed () throws SystemException { System.out.println("DemoHLS.resumed"); } /** * The activity has completed and is no longer active on the current * thread. */ public void completed () throws SystemException { try { System.out.println("DemoHLS.completed "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } if (!_id.isEmpty()) { _id.pop(); } } /** * The HLS name. */ public String identity () throws SystemException { return "DemoHLS"; } /** * The activity service maintains a priority ordered list of HLS * implementations. If an HLS wishes to be ordered based on priority * then it can return a non-negative value: the higher the value, * the higher the priority and hence the earlier in the list of HLSes * it will appear (and be used in). * * @return a positive value for the priority for this HLS, or zero/negative * if the order is not important. */ public int priority () throws SystemException { return 0; } /** * Return the context augmentation for this HLS, if any on the current * activity. * * @return a context object or null if no augmentation is necessary. */ public Context context () throws SystemException { if (_id.isEmpty()) { throw new SystemException("request for context when inactive"); } try { System.out.println("DemoHLS.context "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return new DemoSOAPContextImple(identity() + "_" + _id.size()); } }
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/localjunit/unit/src/test/java/com/arjuna/wsas/tests/DemoHLS.java
Java
apache-2.0
4,846
/* * 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.kylin.metadata.tool; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.common.util.HiveClient; import org.apache.kylin.metadata.MetadataConstants; import org.apache.kylin.metadata.MetadataManager; import org.apache.kylin.metadata.model.ColumnDesc; import org.apache.kylin.metadata.model.TableDesc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; /** * Management class to sync hive table metadata with command See main method for * how to use the class * * @author jianliu */ public class HiveSourceTableLoader { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HiveSourceTableLoader.class); public static final String OUTPUT_SURFIX = "json"; public static final String TABLE_FOLDER_NAME = "table"; public static final String TABLE_EXD_FOLDER_NAME = "table_exd"; public static Set<String> reloadHiveTables(String[] hiveTables, KylinConfig config) throws IOException { Map<String, Set<String>> db2tables = Maps.newHashMap(); for (String table : hiveTables) { String[] parts = HadoopUtil.parseHiveTableName(table); Set<String> set = db2tables.get(parts[0]); if (set == null) { set = Sets.newHashSet(); db2tables.put(parts[0], set); } set.add(parts[1]); } // extract from hive Set<String> loadedTables = Sets.newHashSet(); for (String database : db2tables.keySet()) { List<String> loaded = extractHiveTables(database, db2tables.get(database), config); loadedTables.addAll(loaded); } return loadedTables; } private static List<String> extractHiveTables(String database, Set<String> tables, KylinConfig config) throws IOException { List<String> loadedTables = Lists.newArrayList(); MetadataManager metaMgr = MetadataManager.getInstance(KylinConfig.getInstanceFromEnv()); for (String tableName : tables) { Table table = null; HiveClient hiveClient = new HiveClient(); List<FieldSchema> partitionFields = null; List<FieldSchema> fields = null; try { table = hiveClient.getHiveTable(database, tableName); partitionFields = table.getPartitionKeys(); fields = hiveClient.getHiveTableFields(database, tableName); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } if (fields != null && partitionFields != null && partitionFields.size() > 0) { fields.addAll(partitionFields); } long tableSize = hiveClient.getFileSizeForTable(table); long tableFileNum = hiveClient.getFileNumberForTable(table); TableDesc tableDesc = metaMgr.getTableDesc(database + "." + tableName); if (tableDesc == null) { tableDesc = new TableDesc(); tableDesc.setDatabase(database.toUpperCase()); tableDesc.setName(tableName.toUpperCase()); tableDesc.setUuid(UUID.randomUUID().toString()); tableDesc.setLastModified(0); } int columnNumber = fields.size(); List<ColumnDesc> columns = new ArrayList<ColumnDesc>(columnNumber); for (int i = 0; i < columnNumber; i++) { FieldSchema field = fields.get(i); ColumnDesc cdesc = new ColumnDesc(); cdesc.setName(field.getName().toUpperCase()); cdesc.setDatatype(field.getType()); cdesc.setId(String.valueOf(i + 1)); columns.add(cdesc); } tableDesc.setColumns(columns.toArray(new ColumnDesc[columnNumber])); StringBuffer partitionColumnString = new StringBuffer(); for (int i = 0, n = partitionFields.size(); i < n; i++) { if (i > 0) partitionColumnString.append(", "); partitionColumnString.append(partitionFields.get(i).getName().toUpperCase()); } Map<String, String> map = metaMgr.getTableDescExd(tableDesc.getIdentity()); if (map == null) { map = Maps.newHashMap(); } map.put(MetadataConstants.TABLE_EXD_TABLENAME, table.getTableName()); map.put(MetadataConstants.TABLE_EXD_LOCATION, table.getSd().getLocation()); map.put(MetadataConstants.TABLE_EXD_IF, table.getSd().getInputFormat()); map.put(MetadataConstants.TABLE_EXD_OF, table.getSd().getOutputFormat()); map.put(MetadataConstants.TABLE_EXD_OWNER, table.getOwner()); map.put(MetadataConstants.TABLE_EXD_LAT, String.valueOf(table.getLastAccessTime())); map.put(MetadataConstants.TABLE_EXD_PC, partitionColumnString.toString()); map.put(MetadataConstants.TABLE_EXD_TFS, String.valueOf(tableSize)); map.put(MetadataConstants.TABLE_EXD_TNF, String.valueOf(tableFileNum)); map.put(MetadataConstants.TABLE_EXD_PARTITIONED, Boolean.valueOf(partitionFields != null && partitionFields.size() > 0).toString()); metaMgr.saveSourceTable(tableDesc); metaMgr.saveTableExd(tableDesc.getIdentity(), map); loadedTables.add(tableDesc.getIdentity()); } return loadedTables; } }
nvoron23/Kylin
metadata/src/main/java/org/apache/kylin/metadata/tool/HiveSourceTableLoader.java
Java
apache-2.0
6,633
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.io; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Splitter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class ConfiguredBuckOutIntegrationTest { private ProjectWorkspace workspace; @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Before public void setUp() throws IOException { workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "configured_buck_out", tmp); workspace.setUp(); } @Test public void outputPathsUseConfiguredBuckOut() throws IOException { String buckOut = "new-buck-out"; Path output = workspace.buildAndReturnOutput("-c", "project.buck_out=" + buckOut, "//:dummy"); assertTrue(Files.exists(output)); assertThat(workspace.getDestPath().relativize(output).toString(), Matchers.startsWith(buckOut)); } @Test public void configuredBuckOutAffectsRuleKey() throws IOException { String out = workspace .runBuckCommand("targets", "--show-rulekey", "//:dummy") .assertSuccess() .getStdout(); String ruleKey = Splitter.on(' ').splitToList(out).get(1); String configuredOut = workspace .runBuckCommand( "targets", "--show-rulekey", "-c", "project.buck_out=something", "//:dummy") .assertSuccess() .getStdout(); String configuredRuleKey = Splitter.on(' ').splitToList(configuredOut).get(1); assertThat(ruleKey, Matchers.not(Matchers.equalTo(configuredRuleKey))); } @Test public void buckOutCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); ProcessResult result = workspace.runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy"); result.assertSuccess(); assertThat( Files.readSymbolicLink(workspace.resolve("buck-out/gen")), Matchers.equalTo(workspace.getDestPath().getFileSystem().getPath("../something/gen"))); } @Test public void verifyTogglingConfiguredBuckOut() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.runBuckBuild("//:dummy").assertSuccess(); workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); } @Test public void verifyNoopBuildWithCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); // Do an initial build. workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally("//:dummy"); // Run another build immediately after and verify everything was up to date. workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.getBuildLog().assertTargetHadMatchingRuleKey("//:dummy"); } @Test public void targetsShowOutput() throws IOException { String output = workspace .runBuckCommand( "targets", "--show-output", "-c", "project.buck_out=something", "//:dummy") .assertSuccess() .getStdout() .trim(); output = Splitter.on(' ').splitToList(output).get(1); assertThat(MorePaths.pathWithUnixSeparators(output), Matchers.startsWith("something/")); } @Test public void targetsShowOutputCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); String output = workspace .runBuckCommand( "targets", "--show-output", "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess() .getStdout() .trim(); output = Splitter.on(' ').splitToList(output).get(1); assertThat(MorePaths.pathWithUnixSeparators(output), Matchers.startsWith("buck-out/gen/")); } @Test public void buildShowOutput() throws IOException { Path output = workspace.buildAndReturnOutput("-c", "project.buck_out=something", "//:dummy"); assertThat( MorePaths.pathWithUnixSeparators(workspace.getDestPath().relativize(output)), Matchers.startsWith("something/")); } @Test public void buildShowOutputCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); Path output = workspace.buildAndReturnOutput( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy"); assertThat( MorePaths.pathWithUnixSeparators(workspace.getDestPath().relativize(output)), Matchers.startsWith("buck-out/gen/")); } }
LegNeato/buck
test/com/facebook/buck/io/ConfiguredBuckOutIntegrationTest.java
Java
apache-2.0
6,709
/******************************************************************************* * Copyright 2011 Netflix * * 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.netflix.astyanax.thrift.model; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; import com.netflix.astyanax.Serializer; import com.netflix.astyanax.model.AbstractColumnList; import com.netflix.astyanax.model.Column; public class ThriftCounterColumnListImpl<C> extends AbstractColumnList<C> { private final List<org.apache.cassandra.thrift.CounterColumn> columns; private Map<C, org.apache.cassandra.thrift.CounterColumn> lookup; private final Serializer<C> colSer; public ThriftCounterColumnListImpl(List<org.apache.cassandra.thrift.CounterColumn> columns, Serializer<C> colSer) { this.columns = columns; this.colSer = colSer; } @Override public Iterator<Column<C>> iterator() { class IteratorImpl implements Iterator<Column<C>> { Iterator<org.apache.cassandra.thrift.CounterColumn> base; public IteratorImpl(Iterator<org.apache.cassandra.thrift.CounterColumn> base) { this.base = base; } @Override public boolean hasNext() { return base.hasNext(); } @Override public Column<C> next() { org.apache.cassandra.thrift.CounterColumn c = base.next(); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public void remove() { throw new UnsupportedOperationException("Iterator is immutable"); } } return new IteratorImpl(columns.iterator()); } @Override public Column<C> getColumnByName(C columnName) { constructMap(); org.apache.cassandra.thrift.CounterColumn c = lookup.get(columnName); if (c == null) { return null; } return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public Column<C> getColumnByIndex(int idx) { org.apache.cassandra.thrift.CounterColumn c = columns.get(idx); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public <C2> Column<C2> getSuperColumn(C columnName, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public <C2> Column<C2> getSuperColumn(int idx, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public boolean isEmpty() { return columns.isEmpty(); } @Override public int size() { return columns.size(); } @Override public boolean isSuperColumn() { return false; } @Override public Collection<C> getColumnNames() { constructMap(); return lookup.keySet(); } private void constructMap() { if (lookup == null) { lookup = Maps.newHashMap(); for (org.apache.cassandra.thrift.CounterColumn column : columns) { lookup.put(colSer.fromBytes(column.getName()), column); } } } }
0x6e6562/astyanax
src/main/java/com/netflix/astyanax/thrift/model/ThriftCounterColumnListImpl.java
Java
apache-2.0
3,953
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.unnest; import com.facebook.presto.Session; import com.facebook.presto.block.BlockAssertions.Encoding; import com.facebook.presto.common.Page; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.RowType; import com.facebook.presto.common.type.Type; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.operator.DriverContext; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorFactory; import com.facebook.presto.operator.PageAssertions; import com.facebook.presto.spi.plan.PlanNodeId; import com.facebook.presto.testing.MaterializedResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.facebook.airlift.concurrent.Threads.daemonThreadsNamed; import static com.facebook.presto.RowPagesBuilder.rowPagesBuilder; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.block.BlockAssertions.Encoding.DICTIONARY; import static com.facebook.presto.block.BlockAssertions.Encoding.RUN_LENGTH; import static com.facebook.presto.block.BlockAssertions.createMapType; 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.Decimals.MAX_SHORT_PRECISION; 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.RowType.withDefaultFieldNames; import static com.facebook.presto.common.type.SmallintType.SMALLINT; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.metadata.MetadataManager.createTestMetadataManager; import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEquals; import static com.facebook.presto.operator.PageAssertions.assertPageEquals; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildExpectedPage; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildOutputTypes; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.calculateMaxCardinalities; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.mergePages; import static com.facebook.presto.testing.MaterializedResult.resultBuilder; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.facebook.presto.testing.TestingTaskContext.createTaskContext; import static com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME; import static com.facebook.presto.util.StructuralTestUtil.arrayBlockOf; import static com.facebook.presto.util.StructuralTestUtil.mapBlockOf; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.NaN; import static java.lang.Double.POSITIVE_INFINITY; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestUnnestOperator { private static final int PAGE_COUNT = 10; private static final int POSITION_COUNT = 500; private static final ExecutorService EXECUTOR = newCachedThreadPool(daemonThreadsNamed("test-EXECUTOR-%s")); private static final ScheduledExecutorService SCHEDULER = newScheduledThreadPool(1, daemonThreadsNamed("test-%s")); private ExecutorService executor; private ScheduledExecutorService scheduledExecutor; private DriverContext driverContext; @BeforeMethod public void setUp() { executor = newCachedThreadPool(daemonThreadsNamed("test-executor-%s")); scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s")); driverContext = createTaskContext(executor, scheduledExecutor, TEST_SESSION) .addPipelineContext(0, true, true, false) .addDriverContext(); } @AfterMethod public void tearDown() { executor.shutdownNow(); scheduledExecutor.shutdownNow(); } @Test public void testUnnest() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L) .row(1L, 3L, null, null) .row(2L, 99L, null, null) .row(6L, 7L, 9L, 10L) .row(6L, 8L, 11L, 12L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArray() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(array(bigint))")); Type mapType = metadata.getType(parseTypeSignature("map(array(bigint),array(bigint))")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row( 1L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(2, 4), ImmutableList.of(3, 6)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(4, 8), ImmutableList.of(5, 10)))) .row(2L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(99, 198)), null) .row(3L, null, null) .pageBreak() .row( 6, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(7, 14), ImmutableList.of(8, 16)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(9, 18), ImmutableList.of(10, 20), ImmutableList.of(11, 22), ImmutableList.of(12, 24)))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, new ArrayType(BIGINT), new ArrayType(BIGINT), new ArrayType(BIGINT)) .row(1L, ImmutableList.of(2L, 4L), ImmutableList.of(4L, 8L), ImmutableList.of(5L, 10L)) .row(1L, ImmutableList.of(3L, 6L), null, null) .row(2L, ImmutableList.of(99L, 198L), null, null) .row(6L, ImmutableList.of(7L, 14L), ImmutableList.of(9L, 18L), ImmutableList.of(10L, 20L)) .row(6L, ImmutableList.of(8L, 16L), ImmutableList.of(11L, 22L), ImmutableList.of(12L, 24L)) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithOrdinality() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), true); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L, 1L) .row(1L, 3L, null, null, 2L) .row(2L, 99L, null, null, 1L) .row(6L, 7L, 9L, 10L, 1L) .row(6L, 8L, 11L, 12L, 2L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestNonNumericDoubles() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(double)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,double)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(DOUBLE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN), mapBlockOf(BIGINT, DOUBLE, ImmutableMap.of(1, NEGATIVE_INFINITY, 2, POSITIVE_INFINITY, 3, NaN))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, DOUBLE, BIGINT, DOUBLE) .row(1L, NEGATIVE_INFINITY, 1L, NEGATIVE_INFINITY) .row(1L, POSITIVE_INFINITY, 2L, POSITIVE_INFINITY) .row(1L, NaN, 3L, NaN) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArrayOfRows() { MetadataManager metadata = createTestMetadataManager(); Type arrayOfRowType = metadata.getType(parseTypeSignature("array(row(bigint, double, varchar))")); Type elementType = RowType.anonymous(ImmutableList.of(BIGINT, DOUBLE, VARCHAR)); List<Page> input = rowPagesBuilder(BIGINT, arrayOfRowType) .row(1, arrayBlockOf(elementType, ImmutableList.of(2, 4.2, "abc"), ImmutableList.of(3, 6.6, "def"))) .row(2, arrayBlockOf(elementType, ImmutableList.of(99, 3.14, "pi"), null)) .row(3, null) .pageBreak() .row(6, arrayBlockOf(elementType, null, ImmutableList.of(8, 1.111, "tt"))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1), ImmutableList.of(arrayOfRowType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, DOUBLE, VARCHAR) .row(1L, 2L, 4.2, "abc") .row(1L, 3L, 6.6, "def") .row(2L, 99L, 3.14, "pi") .row(2L, null, null, null) .row(6L, null, null, null) .row(6L, 8L, 1.111, "tt") .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestSingleArrayUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleMapUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleArrayOfRowUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR))))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BOOLEAN); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BOOLEAN), new ArrayType(BOOLEAN)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(SMALLINT); unnestTypes = ImmutableList.of(new ArrayType(SMALLINT), new ArrayType(SMALLINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(INTEGER); unnestTypes = ImmutableList.of(new ArrayType(INTEGER), new ArrayType(INTEGER)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(BIGINT), new ArrayType(BIGINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(createDecimalType(MAX_SHORT_PRECISION + 1)); unnestTypes = ImmutableList.of( new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1)), new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR), new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT)), new ArrayType(new ArrayType(VARCHAR))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(createMapType(BIGINT, BIGINT)), new ArrayType(createMapType(BIGINT, BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoMapUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT), createMapType(VARCHAR, VARCHAR)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayOfRowUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER))), new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestMultipleUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR), new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT))), new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } protected void testUnnest(List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types) { testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); } protected void testUnnest( List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types, float primitiveNullRate, float nestedNullRate, boolean useBlockView, List<Encoding> wrappings) { List<Page> inputPages = new ArrayList<>(); for (int i = 0; i < PAGE_COUNT; i++) { Page inputPage = PageAssertions.createPageWithRandomData(types, POSITION_COUNT, false, false, primitiveNullRate, nestedNullRate, useBlockView, wrappings); inputPages.add(inputPage); } testUnnest(inputPages, replicatedTypes, unnestTypes, false, false); testUnnest(inputPages, replicatedTypes, unnestTypes, true, false); testUnnest(inputPages, replicatedTypes, unnestTypes, false, true); testUnnest(inputPages, replicatedTypes, unnestTypes, true, true); } private void testUnnest(List<Page> inputPages, List<Type> replicatedTypes, List<Type> unnestTypes, boolean withOrdinality, boolean legacyUnnest) { List<Integer> replicatedChannels = IntStream.range(0, replicatedTypes.size()).boxed().collect(Collectors.toList()); List<Integer> unnestChannels = IntStream.range(replicatedTypes.size(), replicatedTypes.size() + unnestTypes.size()).boxed().collect(Collectors.toList()); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), replicatedChannels, replicatedTypes, unnestChannels, unnestTypes, withOrdinality); Operator unnestOperator = ((UnnestOperator.UnnestOperatorFactory) operatorFactory).createOperator(createDriverContext(), legacyUnnest); for (Page inputPage : inputPages) { int[] maxCardinalities = calculateMaxCardinalities(inputPage, replicatedTypes, unnestTypes); List<Type> outputTypes = buildOutputTypes(replicatedTypes, unnestTypes, withOrdinality, legacyUnnest); Page expectedPage = buildExpectedPage(inputPage, replicatedTypes, unnestTypes, outputTypes, maxCardinalities, withOrdinality, legacyUnnest); unnestOperator.addInput(inputPage); List<Page> outputPages = new ArrayList<>(); while (true) { Page outputPage = unnestOperator.getOutput(); if (outputPage == null) { break; } assertTrue(outputPage.getPositionCount() <= 1000); outputPages.add(outputPage); } Page mergedOutputPage = mergePages(outputTypes, outputPages); assertPageEquals(outputTypes, mergedOutputPage, expectedPage); } } private DriverContext createDriverContext() { Session testSession = testSessionBuilder() .setCatalog("tpch") .setSchema(TINY_SCHEMA_NAME) .build(); return createTaskContext(EXECUTOR, SCHEDULER, testSession) .addPipelineContext(0, true, true, false) .addDriverContext(); } }
facebook/presto
presto-main/src/test/java/com/facebook/presto/operator/unnest/TestUnnestOperator.java
Java
apache-2.0
26,599
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: $ */ package org.apache.xml.serializer.dom3; import org.w3c.dom.DOMError; import org.w3c.dom.DOMLocator; /** * Implementation of the DOM Level 3 DOMError interface. * * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ERROR-Interfaces-DOMError'>DOMError Interface definition from Document Object Model (DOM) Level 3 Core Specification</a>. * * @xsl.usage internal */ public final class DOMErrorImpl implements DOMError { /** private data members */ // The DOMError Severity private short fSeverity = DOMError.SEVERITY_WARNING; // The Error message private String fMessage = null; // A String indicating which related data is expected in relatedData. private String fType; // The platform related exception private Exception fException = null; // private Object fRelatedData; // The location of the exception private DOMLocatorImpl fLocation = new DOMLocatorImpl(); // // Constructors // /** * Default constructor. */ DOMErrorImpl () { } /** * @param severity * @param message * @param type */ public DOMErrorImpl(short severity, String message, String type) { fSeverity = severity; fMessage = message; fType = type; } /** * @param severity * @param message * @param type * @param exception */ public DOMErrorImpl(short severity, String message, String type, Exception exception) { fSeverity = severity; fMessage = message; fType = type; fException = exception; } /** * @param severity * @param message * @param type * @param exception * @param relatedData * @param location */ public DOMErrorImpl(short severity, String message, String type, Exception exception, Object relatedData, DOMLocatorImpl location) { fSeverity = severity; fMessage = message; fType = type; fException = exception; fRelatedData = relatedData; fLocation = location; } /** * The severity of the error, either <code>SEVERITY_WARNING</code>, * <code>SEVERITY_ERROR</code>, or <code>SEVERITY_FATAL_ERROR</code>. * * @return A short containing the DOMError severity */ public short getSeverity() { return fSeverity; } /** * The DOMError message string. * * @return String */ public String getMessage() { return fMessage; } /** * The location of the DOMError. * * @return A DOMLocator object containing the DOMError location. */ public DOMLocator getLocation() { return fLocation; } /** * The related platform dependent exception if any. * * @return A java.lang.Exception */ public Object getRelatedException(){ return fException; } /** * Returns a String indicating which related data is expected in relatedData. * * @return A String */ public String getType(){ return fType; } /** * The related DOMError.type dependent data if any. * * @return java.lang.Object */ public Object getRelatedData(){ return fRelatedData; } public void reset(){ fSeverity = DOMError.SEVERITY_WARNING; fException = null; fMessage = null; fType = null; fRelatedData = null; fLocation = null; } }// class DOMErrorImpl
mirego/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/dom3/DOMErrorImpl.java
Java
apache-2.0
4,503
package org.axonframework.test.saga; public class NonTransientResource { }
bojanv55/AxonFramework
test/src/test/java/org/axonframework/test/saga/NonTransientResource.java
Java
apache-2.0
76
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dfareporting.model; /** * Click-through URL * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the DCM/DFA Reporting And Trafficking API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class CreativeClickThroughUrl extends com.google.api.client.json.GenericJson { /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String computedClickThroughUrl; /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String customClickThroughUrl; /** * ID of the landing page for the click-through URL. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long landingPageId; /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @return value or {@code null} for none */ public java.lang.String getComputedClickThroughUrl() { return computedClickThroughUrl; } /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @param computedClickThroughUrl computedClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setComputedClickThroughUrl(java.lang.String computedClickThroughUrl) { this.computedClickThroughUrl = computedClickThroughUrl; return this; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @return value or {@code null} for none */ public java.lang.String getCustomClickThroughUrl() { return customClickThroughUrl; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @param customClickThroughUrl customClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setCustomClickThroughUrl(java.lang.String customClickThroughUrl) { this.customClickThroughUrl = customClickThroughUrl; return this; } /** * ID of the landing page for the click-through URL. * @return value or {@code null} for none */ public java.lang.Long getLandingPageId() { return landingPageId; } /** * ID of the landing page for the click-through URL. * @param landingPageId landingPageId or {@code null} for none */ public CreativeClickThroughUrl setLandingPageId(java.lang.Long landingPageId) { this.landingPageId = landingPageId; return this; } @Override public CreativeClickThroughUrl set(String fieldName, Object value) { return (CreativeClickThroughUrl) super.set(fieldName, value); } @Override public CreativeClickThroughUrl clone() { return (CreativeClickThroughUrl) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-dfareporting/v3.4/1.29.2/com/google/api/services/dfareporting/model/CreativeClickThroughUrl.java
Java
apache-2.0
4,569
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.neural.pattern; import java.util.ArrayList; import java.util.List; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; import org.encog.neural.networks.layers.Layer; /** * Used to create feedforward neural networks. A feedforward network has an * input and output layers separated by zero or more hidden layers. The * feedforward neural network is one of the most common neural network patterns. * * @author jheaton * */ public class FeedForwardPattern implements NeuralNetworkPattern { /** * The number of input neurons. */ private int inputNeurons; /** * The number of output neurons. */ private int outputNeurons; /** * The activation function. */ private ActivationFunction activationHidden; /** * The activation function. */ private ActivationFunction activationOutput; /** * The number of hidden neurons. */ private final List<Integer> hidden = new ArrayList<Integer>(); /** * Add a hidden layer, with the specified number of neurons. * * @param count * The number of neurons to add. */ public void addHiddenLayer(final int count) { this.hidden.add(count); } /** * Clear out any hidden neurons. */ public void clear() { this.hidden.clear(); } /** * Generate the feedforward neural network. * * @return The feedforward neural network. */ public MLMethod generate() { if( this.activationOutput==null ) this.activationOutput = this.activationHidden; final Layer input = new BasicLayer(null, true, this.inputNeurons); final BasicNetwork result = new BasicNetwork(); result.addLayer(input); for (final Integer count : this.hidden) { final Layer hidden = new BasicLayer(this.activationHidden, true, count); result.addLayer(hidden); } final Layer output = new BasicLayer(this.activationOutput, false, this.outputNeurons); result.addLayer(output); result.getStructure().finalizeStructure(); result.reset(); return result; } /** * Set the activation function to use on each of the layers. * * @param activation * The activation function. */ public void setActivationFunction(final ActivationFunction activation) { this.activationHidden = activation; } /** * Set the number of input neurons. * * @param count * Neuron count. */ public void setInputNeurons(final int count) { this.inputNeurons = count; } /** * Set the number of output neurons. * * @param count * Neuron count. */ public void setOutputNeurons(final int count) { this.outputNeurons = count; } /** * @return the activationOutput */ public ActivationFunction getActivationOutput() { return activationOutput; } /** * @param activationOutput the activationOutput to set */ public void setActivationOutput(ActivationFunction activationOutput) { this.activationOutput = activationOutput; } }
Crespo911/encog-java-core
src/main/java/org/encog/neural/pattern/FeedForwardPattern.java
Java
apache-2.0
3,936
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net.starlark.java.syntax; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** Syntax node for a for loop statement, {@code for vars in iterable: ...}. */ public final class ForStatement extends Statement { private final int forOffset; private final Expression vars; private final Expression iterable; private final ImmutableList<Statement> body; // non-empty if well formed /** Constructs a for loop statement. */ ForStatement( FileLocations locs, int forOffset, Expression vars, Expression iterable, ImmutableList<Statement> body) { super(locs); this.forOffset = forOffset; this.vars = Preconditions.checkNotNull(vars); this.iterable = Preconditions.checkNotNull(iterable); this.body = body; } /** * Returns variables assigned by each iteration. May be a compound target such as {@code (a[b], * c.d)}. */ public Expression getVars() { return vars; } /** Returns the iterable value. */ // TODO(adonovan): rename to getIterable. public Expression getCollection() { return iterable; } /** Returns the statements of the loop body. Non-empty if parsing succeeded. */ public ImmutableList<Statement> getBody() { return body; } @Override public int getStartOffset() { return forOffset; } @Override public int getEndOffset() { return body.isEmpty() ? iterable.getEndOffset() // wrong, but tree is ill formed : body.get(body.size() - 1).getEndOffset(); } @Override public String toString() { return "for " + vars + " in " + iterable + ": ...\n"; } @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } @Override public Kind kind() { return Kind.FOR; } }
twitter-forks/bazel
src/main/java/net/starlark/java/syntax/ForStatement.java
Java
apache-2.0
2,418
package de.j4velin.pedometer.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class ColorPreview extends View { private Paint paint = new Paint(); private int color; public ColorPreview(Context context) { super(context); } public ColorPreview(Context context, AttributeSet attrs) { super(context, attrs); } public ColorPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setColor(final int c) { color = c; invalidate(); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); paint.setColor(color); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, paint); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2 - 1, paint); } }
hgl888/Pedometer
src/main/java/de/j4velin/pedometer/util/ColorPreview.java
Java
apache-2.0
1,251
/* * Copyright (C) 2009-2017 Lightbend Inc. <https://www.lightbend.com> */ package javaguide.xml; import org.w3c.dom.Document; import play.libs.XPath; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; public class JavaXmlRequests extends Controller { //#xml-hello public Result sayHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello //#xml-hello-bodyparser @BodyParser.Of(BodyParser.Xml.class) public Result sayHelloBP() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello-bodyparser //#xml-reply @BodyParser.Of(BodyParser.Xml.class) public Result replyHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("<message \"status\"=\"KO\">Missing parameter [name]</message>").as("application/xml"); } else { return ok("<message \"status\"=\"OK\">Hello " + name + "</message>").as("application/xml"); } } } //#xml-reply }
wsargent/playframework
documentation/manual/working/javaGuide/main/xml/code/javaguide/xml/JavaXmlRequests.java
Java
apache-2.0
1,900
/* * 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.druid.indexer; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.IOUtils; import org.apache.druid.common.utils.UUIDUtils; import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.IOE; import org.apache.druid.java.util.common.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.MRJobConfig; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class HdfsClasspathSetupTest { private static MiniDFSCluster miniCluster; private static File hdfsTmpDir; private static Configuration conf; private static String dummyJarString = "This is a test jar file."; private File dummyJarFile; private Path finalClasspath; private Path intermediatePath; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @BeforeClass public static void setupStatic() throws IOException { hdfsTmpDir = File.createTempFile("hdfsClasspathSetupTest", "dir"); if (!hdfsTmpDir.delete()) { throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath()); } conf = new Configuration(true); conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath()); miniCluster = new MiniDFSCluster.Builder(conf).build(); } @Before public void setUp() throws IOException { // intermedatePath and finalClasspath are relative to hdfsTmpDir directory. intermediatePath = new Path(StringUtils.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(StringUtils.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy( new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); } @AfterClass public static void tearDownStatic() throws IOException { if (miniCluster != null) { miniCluster.shutdown(true); } FileUtils.deleteDirectory(hdfsTmpDir); } @After public void tearDown() throws IOException { dummyJarFile.delete(); Assert.assertFalse(dummyJarFile.exists()); miniCluster.getFileSystem().delete(finalClasspath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(finalClasspath)); miniCluster.getFileSystem().delete(intermediatePath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(intermediatePath)); } @Test public void testAddSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); Path intermediatePath = new Path("/tmp/classpath"); JobHelper.addSnapshotJarToClassPath(dummyJarFile, intermediatePath, fs, job); Path expectedJarPath = new Path(intermediatePath, dummyJarFile.getName()); // check file gets uploaded to HDFS Assert.assertTrue(fs.exists(expectedJarPath)); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testAddNonSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePath, fs, job); Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file gets deleted Assert.assertFalse(fs.exists(new Path(intermediatePath, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testIsSnapshot() { Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT.jar"))); Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT-selfcontained.jar"))); } @Test public void testConcurrentUpload() throws IOException, InterruptedException, ExecutionException, TimeoutException { final int concurrency = 10; ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(concurrency)); // barrier ensures that all jobs try to add files to classpath at same time. final CyclicBarrier barrier = new CyclicBarrier(concurrency); final DistributedFileSystem fs = miniCluster.getFileSystem(); final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { futures.add( pool.submit( new Callable() { @Override public Boolean call() throws Exception { int id = barrier.await(); Job job = Job.getInstance(conf, "test-job-" + id); Path intermediatePathForJob = new Path(intermediatePath, "job-" + id); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file is not present Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals( expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES) ); return true; } } ) ); } Futures.allAsList(futures).get(30, TimeUnit.SECONDS); pool.shutdownNow(); } }
pjain1/druid
indexing-hadoop/src/test/java/org/apache/druid/indexer/HdfsClasspathSetupTest.java
Java
apache-2.0
8,361
/* * 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.twill.internal; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.apache.twill.internal.state.Message; import org.apache.twill.internal.state.MessageCodec; import org.apache.twill.zookeeper.ZKClient; import org.apache.twill.zookeeper.ZKOperations; import org.apache.zookeeper.CreateMode; /** * Helper class to send messages to remote instances using Apache Zookeeper watch mechanism. */ public final class ZKMessages { /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. * @return A {@link ListenableFuture} that will be completed when the message is consumed, which indicated * by deletion of the node. If there is exception during the process, it will be reflected * to the future returned. */ public static <V> ListenableFuture<V> sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final V completionResult) { SettableFuture<V> result = SettableFuture.create(); sendMessage(zkClient, messagePathPrefix, message, result, completionResult); return result; } /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completion A {@link SettableFuture} to reflect the result of message process completion. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. */ public static <V> void sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final SettableFuture<V> completion, final V completionResult) { // Creates a message and watch for its deletion for completion. Futures.addCallback(zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL), new FutureCallback<String>() { @Override public void onSuccess(String path) { Futures.addCallback(ZKOperations.watchDeleted(zkClient, path), new FutureCallback<String>() { @Override public void onSuccess(String result) { completion.set(completionResult); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } private ZKMessages() { } }
cdapio/twill
twill-core/src/main/java/org/apache/twill/internal/ZKMessages.java
Java
apache-2.0
4,170
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; /** * Sets the level for a particular DiagnosticGroup. * @author nicksantos@google.com (Nick Santos) */ public class DiagnosticGroupWarningsGuard extends WarningsGuard { private final DiagnosticGroup group; private final CheckLevel level; public DiagnosticGroupWarningsGuard( DiagnosticGroup group, CheckLevel level) { this.group = group; this.level = level; } @Override public CheckLevel level(JSError error) { return group.matches(error) ? level : null; } @Override public boolean disables(DiagnosticGroup otherGroup) { return !level.isOn() && group.isSubGroup(otherGroup); } @Override public boolean enables(DiagnosticGroup otherGroup) { if (level.isOn()) { for (DiagnosticType type : otherGroup.getTypes()) { if (group.matches(type)) { return true; } } } return false; } }
johan/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroupWarningsGuard.java
Java
apache-2.0
1,568
/* * 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.flink.streaming.kafka.test.base; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * The util class for kafka example. */ public class KafkaExampleUtil { public static StreamExecutionEnvironment prepareExecutionEnv(ParameterTool parameterTool) throws Exception { if (parameterTool.getNumberOfParameters() < 5) { System.out.println("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); throw new Exception("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); } StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setRestartStrategy(RestartStrategies.fixedDelayRestart(4, 10000)); env.enableCheckpointing(5000); // create a checkpoint every 5 seconds env.getConfig().setGlobalJobParameters(parameterTool); // make parameters available in the web interface env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); return env; } }
GJL/flink
flink-end-to-end-tests/flink-streaming-kafka-test-base/src/main/java/org/apache/flink/streaming/kafka/test/base/KafkaExampleUtil.java
Java
apache-2.0
2,183
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.content.model; /** * Model definition for OrdersSetLineItemMetadataResponse. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class OrdersSetLineItemMetadataResponse extends com.google.api.client.json.GenericJson { /** * The status of the execution. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String executionStatus; /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * The status of the execution. * @return value or {@code null} for none */ public java.lang.String getExecutionStatus() { return executionStatus; } /** * The status of the execution. * @param executionStatus executionStatus or {@code null} for none */ public OrdersSetLineItemMetadataResponse setExecutionStatus(java.lang.String executionStatus) { this.executionStatus = executionStatus; return this; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @param kind kind or {@code null} for none */ public OrdersSetLineItemMetadataResponse setKind(java.lang.String kind) { this.kind = kind; return this; } @Override public OrdersSetLineItemMetadataResponse set(String fieldName, Object value) { return (OrdersSetLineItemMetadataResponse) super.set(fieldName, value); } @Override public OrdersSetLineItemMetadataResponse clone() { return (OrdersSetLineItemMetadataResponse) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-content/v2/1.29.2/com/google/api/services/content/model/OrdersSetLineItemMetadataResponse.java
Java
apache-2.0
3,052
/** * Copyright 2010-2015 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.mybatis.spring; import static java.lang.reflect.Proxy.newProxyInstance; import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable; import static org.mybatis.spring.SqlSessionUtils.closeSqlSession; import static org.mybatis.spring.SqlSessionUtils.getSqlSession; import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional; import static org.springframework.util.Assert.notNull; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.Connection; import java.util.List; import java.util.Map; import org.apache.ibatis.cursor.Cursor; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.executor.BatchResult; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.dao.support.PersistenceExceptionTranslator; /** * Thread safe, Spring managed, {@code SqlSession} that works with Spring * transaction management to ensure that that the actual SqlSession used is the * one associated with the current Spring transaction. In addition, it manages * the session life-cycle, including closing, committing or rolling back the * session as necessary based on the Spring transaction configuration. * <p> * The template needs a SqlSessionFactory to create SqlSessions, passed as a * constructor argument. It also can be constructed indicating the executor type * to be used, if not, the default executor type, defined in the session factory * will be used. * <p> * This template converts MyBatis PersistenceExceptions into unchecked * DataAccessExceptions, using, by default, a {@code MyBatisExceptionTranslator}. * <p> * Because SqlSessionTemplate is thread safe, a single instance can be shared * by all DAOs; there should also be a small memory savings by doing this. This * pattern can be used in Spring configuration files as follows: * * <pre class="code"> * {@code * <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg ref="sqlSessionFactory" /> * </bean> * } * </pre> * * @author Putthibong Boonbong * @author Hunter Presnall * @author Eduardo Macarron * * @see SqlSessionFactory * @see MyBatisExceptionTranslator * @version $Id$ */ public class SqlSessionTemplate implements SqlSession, DisposableBean { private final SqlSessionFactory sqlSessionFactory; private final ExecutorType executorType; private final SqlSession sqlSessionProxy; private final PersistenceExceptionTranslator exceptionTranslator; /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument. * * @param sqlSessionFactory */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument and the given {@code ExecutorType} * {@code ExecutorType} cannot be changed once the {@code SqlSessionTemplate} * is constructed. * * @param sqlSessionFactory * @param executorType */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) { this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator( sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true)); } /** * Constructs a Spring managed {@code SqlSession} with the given * {@code SqlSessionFactory} and {@code ExecutorType}. * A custom {@code SQLExceptionTranslator} can be provided as an * argument so any {@code PersistenceException} thrown by MyBatis * can be custom translated to a {@code RuntimeException} * The {@code SQLExceptionTranslator} can also be null and thus no * exception translation will be done and MyBatis exceptions will be * thrown * * @param sqlSessionFactory * @param executorType * @param exceptionTranslator */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required"); notNull(executorType, "Property 'executorType' is required"); this.sqlSessionFactory = sqlSessionFactory; this.executorType = executorType; this.exceptionTranslator = exceptionTranslator; this.sqlSessionProxy = (SqlSession) newProxyInstance( SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } public SqlSessionFactory getSqlSessionFactory() { return this.sqlSessionFactory; } public ExecutorType getExecutorType() { return this.executorType; } public PersistenceExceptionTranslator getPersistenceExceptionTranslator() { return this.exceptionTranslator; } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement) { return this.sqlSessionProxy.<T> selectOne(statement); } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.<T> selectOne(statement, parameter); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement) { return this.sqlSessionProxy.selectCursor(statement); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter) { return this.sqlSessionProxy.selectCursor(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement) { return this.sqlSessionProxy.<E> selectList(statement); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter) { return this.sqlSessionProxy.<E> selectList(statement, parameter); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public void select(String statement, ResultHandler handler) { this.sqlSessionProxy.select(statement, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, rowBounds, handler); } /** * {@inheritDoc} */ @Override public int insert(String statement) { return this.sqlSessionProxy.insert(statement); } /** * {@inheritDoc} */ @Override public int insert(String statement, Object parameter) { return this.sqlSessionProxy.insert(statement, parameter); } /** * {@inheritDoc} */ @Override public int update(String statement) { return this.sqlSessionProxy.update(statement); } /** * {@inheritDoc} */ @Override public int update(String statement, Object parameter) { return this.sqlSessionProxy.update(statement, parameter); } /** * {@inheritDoc} */ @Override public int delete(String statement) { return this.sqlSessionProxy.delete(statement); } /** * {@inheritDoc} */ @Override public int delete(String statement, Object parameter) { return this.sqlSessionProxy.delete(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> T getMapper(Class<T> type) { return getConfiguration().getMapper(type, this); } /** * {@inheritDoc} */ @Override public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void commit(boolean force) { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback(boolean force) { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void clearCache() { this.sqlSessionProxy.clearCache(); } /** * {@inheritDoc} * */ @Override public Configuration getConfiguration() { return this.sqlSessionFactory.getConfiguration(); } /** * {@inheritDoc} */ @Override public Connection getConnection() { return this.sqlSessionProxy.getConnection(); } /** * {@inheritDoc} * * @since 1.0.2 * */ @Override public List<BatchResult> flushStatements() { return this.sqlSessionProxy.flushStatements(); } /** * Allow gently dispose bean: * <pre> * {@code * * <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg index="0" ref="sqlSessionFactory" /> * </bean> * } *</pre> * * The implementation of {@link DisposableBean} forces spring context to use {@link DisposableBean#destroy()} method instead of {@link SqlSessionTemplate#close()} to shutdown gently. * * @see SqlSessionTemplate#close() * @see org.springframework.beans.factory.support.DisposableBeanAdapter#inferDestroyMethodIfNecessary * @see org.springframework.beans.factory.support.DisposableBeanAdapter#CLOSE_METHOD_NAME */ @Override public void destroy() throws Exception { //This method forces spring disposer to avoid call of SqlSessionTemplate.close() which gives UnsupportedOperationException } /** * Proxy needed to route MyBatis method calls to the proper SqlSession got * from Spring's Transaction Manager * It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to * pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}. */ private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = getSqlSession( SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator); try { Object result = method.invoke(sqlSession, args); if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) { // force commit even on non-dirty sessions because some databases require // a commit/rollback before calling close() sqlSession.commit(true); } return result; } catch (Throwable t) { Throwable unwrapped = unwrapThrowable(t); if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) { // release the connection to avoid a deadlock if the translator is no loaded. See issue #22 closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); sqlSession = null; Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped); if (translated != null) { unwrapped = translated; } } throw unwrapped; } finally { if (sqlSession != null) { closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); } } } } }
jiangchaoting/spring
src/main/java/org/mybatis/spring/SqlSessionTemplate.java
Java
apache-2.0
13,876
/* * Copyright (c) 2010, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.test.jdbc4.jdbc41; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.postgresql.test.TestUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.Properties; public class SchemaTest { private Connection _conn; private boolean dropUserSchema; @Before public void setUp() throws Exception { _conn = TestUtil.openDB(); Statement stmt = _conn.createStatement(); try { stmt.execute("CREATE SCHEMA " + TestUtil.getUser()); dropUserSchema = true; } catch (SQLException e) { /* assume schema existed */ } stmt.execute("CREATE SCHEMA schema1"); stmt.execute("CREATE SCHEMA schema2"); stmt.execute("CREATE SCHEMA \"schema 3\""); stmt.execute("CREATE SCHEMA \"schema \"\"4\""); stmt.execute("CREATE SCHEMA \"schema '5\""); stmt.execute("CREATE SCHEMA \"schema ,6\""); stmt.execute("CREATE SCHEMA \"UpperCase\""); TestUtil.createTable(_conn, "schema1.table1", "id integer"); TestUtil.createTable(_conn, "schema2.table2", "id integer"); TestUtil.createTable(_conn, "\"UpperCase\".table3", "id integer"); TestUtil.createTable(_conn, "schema1.sptest", "id integer"); TestUtil.createTable(_conn, "schema2.sptest", "id varchar"); } @After public void tearDown() throws SQLException { _conn.setAutoCommit(true); _conn.setSchema(null); Statement stmt = _conn.createStatement(); if (dropUserSchema) { stmt.execute("DROP SCHEMA " + TestUtil.getUser() + " CASCADE"); } stmt.execute("DROP SCHEMA schema1 CASCADE"); stmt.execute("DROP SCHEMA schema2 CASCADE"); stmt.execute("DROP SCHEMA \"schema 3\" CASCADE"); stmt.execute("DROP SCHEMA \"schema \"\"4\" CASCADE"); stmt.execute("DROP SCHEMA \"schema '5\" CASCADE"); stmt.execute("DROP SCHEMA \"schema ,6\""); stmt.execute("DROP SCHEMA \"UpperCase\" CASCADE"); TestUtil.closeDB(_conn); } /** * Test that what you set is what you get */ @Test public void testGetSetSchema() throws SQLException { _conn.setSchema("schema1"); assertEquals("schema1", _conn.getSchema()); _conn.setSchema("schema2"); assertEquals("schema2", _conn.getSchema()); _conn.setSchema("schema 3"); assertEquals("schema 3", _conn.getSchema()); _conn.setSchema("schema \"4"); assertEquals("schema \"4", _conn.getSchema()); _conn.setSchema("schema '5"); assertEquals("schema '5", _conn.getSchema()); _conn.setSchema("UpperCase"); assertEquals("UpperCase", _conn.getSchema()); } /** * Test that setting the schema allows to access objects of this schema without prefix, hide * objects from other schemas but doesn't prevent to prefix-access to them. */ @Test public void testUsingSchema() throws SQLException { Statement stmt = _conn.createStatement(); try { try { _conn.setSchema("schema1"); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("schema2"); stmt.executeQuery(TestUtil.selectSQL("table2", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("UpperCase"); stmt.executeQuery(TestUtil.selectSQL("table3", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } } catch (SQLException e) { fail("Could not find expected schema elements: " + e.getMessage()); } } finally { try { stmt.close(); } catch (SQLException e) { } } } /** * Test that get schema returns the schema with the highest priority in the search path */ @Test public void testMultipleSearchPath() throws SQLException { execute("SET search_path TO schema1,schema2"); assertEquals("schema1", _conn.getSchema()); execute("SET search_path TO \"schema ,6\",schema2"); assertEquals("schema ,6", _conn.getSchema()); } @Test public void testSchemaInProperties() throws Exception { Properties properties = new Properties(); properties.setProperty("currentSchema", "schema1"); Connection conn = TestUtil.openDB(properties); try { assertEquals("schema1", conn.getSchema()); Statement stmt = conn.createStatement(); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } } finally { TestUtil.closeDB(conn); } } @Test public void testSchemaPath$User() throws Exception { execute("SET search_path TO \"$user\",public,schema2"); assertEquals(TestUtil.getUser(), _conn.getSchema()); } private void execute(String sql) throws SQLException { Statement stmt = _conn.createStatement(); try { stmt.execute(sql); } finally { try { stmt.close(); } catch (SQLException e) { } } } @Test public void testSearchPathPreparedStatementAutoCommitFalse() throws SQLException { _conn.setAutoCommit(false); testSearchPathPreparedStatement(); } @Test public void testSearchPathPreparedStatementAutoCommitTrue() throws SQLException { testSearchPathPreparedStatement(); } @Test public void testSearchPathPreparedStatement() throws SQLException { execute("set search_path to schema1,public"); PreparedStatement ps = _conn.prepareStatement("select * from sptest"); for (int i = 0; i < 10; i++) { ps.execute(); } assertColType(ps, "sptest should point to schema1.sptest, thus column type should be INT", Types.INTEGER); ps.close(); execute("set search_path to schema2,public"); ps = _conn.prepareStatement("select * from sptest"); assertColType(ps, "sptest should point to schema2.sptest, thus column type should be VARCHAR", Types.VARCHAR); ps.close(); } private void assertColType(PreparedStatement ps, String message, int expected) throws SQLException { ResultSet rs = ps.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int columnType = md.getColumnType(1); assertEquals(message, expected, columnType); rs.close(); } }
panchenko/pgjdbc
pgjdbc/src/test/java/org/postgresql/test/jdbc4/jdbc41/SchemaTest.java
Java
bsd-2-clause
7,435
// Copyright 2019 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.browserservices.ui.splashscreen.trustedwebactivity; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static androidx.browser.trusted.TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.browser.customtabs.TrustedWebUtils; import androidx.browser.trusted.TrustedWebActivityIntentBuilder; import androidx.browser.trusted.splashscreens.SplashScreenParamKey; import org.chromium.base.IntentUtils; import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashController; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashDelegate; import org.chromium.chrome.browser.customtabs.TranslucentCustomTabActivity; import org.chromium.chrome.browser.tab.Tab; import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.util.ColorUtils; import javax.inject.Inject; /** * Orchestrates the flow of showing and removing splash screens for apps based on Trusted Web * Activities. * * The flow is as follows: * - TWA client app verifies conditions for showing splash screen. If the checks pass, it shows the * splash screen immediately. * - The client passes the URI to a file with the splash image to * {@link androidx.browser.customtabs.CustomTabsService}. The image is decoded and put into * {@link SplashImageHolder}. * - The client then launches a TWA, at which point the Bitmap is already available. * - ChromeLauncherActivity calls {@link #handleIntent}, which starts * {@link TranslucentCustomTabActivity} - a CustomTabActivity with translucent style. The * translucency is necessary in order to avoid a flash that might be seen when starting the activity * before the splash screen is attached. * - {@link TranslucentCustomTabActivity} creates an instance of {@link TwaSplashController} which * immediately displays the splash screen in an ImageView on top of the rest of view hierarchy. * - It also immediately removes the translucency. See comment in {@link SplashController} for more * details. * - It waits for the page to load, and removes the splash image once first paint (or a failure) * occurs. * * Lifecycle: this class is resolved only once when CustomTabActivity is launched, and is * gc-ed when it finishes its job. * If these lifecycle assumptions change, consider whether @ActivityScope needs to be added. */ public class TwaSplashController implements SplashDelegate { // TODO(pshmakov): move this to AndroidX. private static final String KEY_SHOWN_IN_CLIENT = "androidx.browser.trusted.KEY_SPLASH_SCREEN_SHOWN_IN_CLIENT"; private final SplashController mSplashController; private final Activity mActivity; private final SplashImageHolder mSplashImageCache; private final BrowserServicesIntentDataProvider mIntentDataProvider; @Inject public TwaSplashController(SplashController splashController, Activity activity, ActivityWindowAndroid activityWindowAndroid, SplashImageHolder splashImageCache, BrowserServicesIntentDataProvider intentDataProvider) { mSplashController = splashController; mActivity = activity; mSplashImageCache = splashImageCache; mIntentDataProvider = intentDataProvider; long splashHideAnimationDurationMs = IntentUtils.safeGetInt(getSplashScreenParamsFromIntent(), SplashScreenParamKey.KEY_FADE_OUT_DURATION_MS, 0); mSplashController.setConfig(this, splashHideAnimationDurationMs); } @Override public View buildSplashView() { Bitmap bitmap = mSplashImageCache.takeImage(mIntentDataProvider.getSession()); if (bitmap == null) { return null; } ImageView splashView = new ImageView(mActivity); splashView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); splashView.setImageBitmap(bitmap); applyCustomizationsToSplashScreenView(splashView); return splashView; } @Override public void onSplashHidden(Tab tab, long startTimestamp, long endTimestamp) {} @Override public boolean shouldWaitForSubsequentPageLoadToHideSplash() { return false; } private void applyCustomizationsToSplashScreenView(ImageView imageView) { Bundle params = getSplashScreenParamsFromIntent(); int backgroundColor = IntentUtils.safeGetInt( params, SplashScreenParamKey.KEY_BACKGROUND_COLOR, Color.WHITE); imageView.setBackgroundColor(ColorUtils.getOpaqueColor(backgroundColor)); int scaleTypeOrdinal = IntentUtils.safeGetInt(params, SplashScreenParamKey.KEY_SCALE_TYPE, -1); ImageView.ScaleType[] scaleTypes = ImageView.ScaleType.values(); ImageView.ScaleType scaleType; if (scaleTypeOrdinal < 0 || scaleTypeOrdinal >= scaleTypes.length) { scaleType = ImageView.ScaleType.CENTER; } else { scaleType = scaleTypes[scaleTypeOrdinal]; } imageView.setScaleType(scaleType); if (scaleType != ImageView.ScaleType.MATRIX) return; float[] matrixValues = IntentUtils.safeGetFloatArray( params, SplashScreenParamKey.KEY_IMAGE_TRANSFORMATION_MATRIX); if (matrixValues == null || matrixValues.length != 9) return; Matrix matrix = new Matrix(); matrix.setValues(matrixValues); imageView.setImageMatrix(matrix); } private Bundle getSplashScreenParamsFromIntent() { return mIntentDataProvider.getIntent().getBundleExtra(EXTRA_SPLASH_SCREEN_PARAMS); } /** * Returns true if the intent corresponds to a TWA with a splash screen. */ public static boolean intentIsForTwaWithSplashScreen(Intent intent) { boolean isTrustedWebActivity = IntentUtils.safeGetBooleanExtra( intent, TrustedWebUtils.EXTRA_LAUNCH_AS_TRUSTED_WEB_ACTIVITY, false); boolean requestsSplashScreen = IntentUtils.safeGetParcelableExtra(intent, EXTRA_SPLASH_SCREEN_PARAMS) != null; return isTrustedWebActivity && requestsSplashScreen; } /** * Handles the intent if it should launch a TWA with splash screen. * @param activity Activity, from which to start the next one. * @param intent Incoming intent. * @return Whether the intent was handled. */ public static boolean handleIntent(Activity activity, Intent intent) { if (!intentIsForTwaWithSplashScreen(intent)) return false; Bundle params = IntentUtils.safeGetBundleExtra( intent, TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS); boolean shownInClient = IntentUtils.safeGetBoolean(params, KEY_SHOWN_IN_CLIENT, true); // shownInClient is "true" by default for the following reasons: // - For compatibility with older clients which don't use this bundle key. // - Because getting "false" when it should be "true" leads to more severe visual glitches, // than vice versa. if (shownInClient) { // If splash screen was shown in client, we must launch a translucent activity to // ensure smooth transition. intent.setClassName(activity, TranslucentCustomTabActivity.class.getName()); } intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.startActivity(intent); activity.overridePendingTransition(0, 0); return true; } }
ric2b/Vivaldi-browser
chromium/chrome/android/java/src/org/chromium/chrome/browser/browserservices/ui/splashscreen/trustedwebactivity/TwaSplashController.java
Java
bsd-3-clause
8,032
package com.greenlemonmobile.app.ebook.books.parser; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; public interface ZipWrapper { ZipEntry getEntry(String entryName); InputStream getInputStream(ZipEntry entry) throws IOException; Enumeration<? extends ZipEntry> entries(); void close() throws IOException; }
xiaopengs/iBooks
src/com/greenlemonmobile/app/ebook/books/parser/ZipWrapper.java
Java
mit
433
package com.greenlemonmobile.app.ebook.books.imagezoom.graphics; import android.graphics.Bitmap; /** * Base interface used in the {@link ImageViewTouchBase} view * @author alessandro * */ public interface IBitmapDrawable { Bitmap getBitmap(); }
yy1300326388/iBooks
src/com/greenlemonmobile/app/ebook/books/imagezoom/graphics/IBitmapDrawable.java
Java
mit
253
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.azurespecials.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import fixtures.azurespecials.ApiVersionDefaults; import fixtures.azurespecials.ApiVersionLocals; import fixtures.azurespecials.AutoRestAzureSpecialParametersTestClient; import fixtures.azurespecials.Headers; import fixtures.azurespecials.Odatas; import fixtures.azurespecials.SkipUrlEncodings; import fixtures.azurespecials.SubscriptionInCredentials; import fixtures.azurespecials.SubscriptionInMethods; import fixtures.azurespecials.XMsClientRequestIds; /** * Initializes a new instance of the AutoRestAzureSpecialParametersTestClientImpl class. */ public final class AutoRestAzureSpecialParametersTestClientImpl extends AzureServiceClient implements AutoRestAzureSpecialParametersTestClient { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. */ private String subscriptionId; /** * Gets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The api version, which appears in the query, the value is always '2015-07-01-preview'. */ private String apiVersion; /** * Gets The api version, which appears in the query, the value is always '2015-07-01-preview'. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** Gets or sets the preferred language for the response. */ private String acceptLanguage; /** * Gets Gets or sets the preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets Gets or sets the preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * The XMsClientRequestIds object to access its operations. */ private XMsClientRequestIds xMsClientRequestIds; /** * Gets the XMsClientRequestIds object to access its operations. * @return the XMsClientRequestIds object. */ public XMsClientRequestIds xMsClientRequestIds() { return this.xMsClientRequestIds; } /** * The SubscriptionInCredentials object to access its operations. */ private SubscriptionInCredentials subscriptionInCredentials; /** * Gets the SubscriptionInCredentials object to access its operations. * @return the SubscriptionInCredentials object. */ public SubscriptionInCredentials subscriptionInCredentials() { return this.subscriptionInCredentials; } /** * The SubscriptionInMethods object to access its operations. */ private SubscriptionInMethods subscriptionInMethods; /** * Gets the SubscriptionInMethods object to access its operations. * @return the SubscriptionInMethods object. */ public SubscriptionInMethods subscriptionInMethods() { return this.subscriptionInMethods; } /** * The ApiVersionDefaults object to access its operations. */ private ApiVersionDefaults apiVersionDefaults; /** * Gets the ApiVersionDefaults object to access its operations. * @return the ApiVersionDefaults object. */ public ApiVersionDefaults apiVersionDefaults() { return this.apiVersionDefaults; } /** * The ApiVersionLocals object to access its operations. */ private ApiVersionLocals apiVersionLocals; /** * Gets the ApiVersionLocals object to access its operations. * @return the ApiVersionLocals object. */ public ApiVersionLocals apiVersionLocals() { return this.apiVersionLocals; } /** * The SkipUrlEncodings object to access its operations. */ private SkipUrlEncodings skipUrlEncodings; /** * Gets the SkipUrlEncodings object to access its operations. * @return the SkipUrlEncodings object. */ public SkipUrlEncodings skipUrlEncodings() { return this.skipUrlEncodings; } /** * The Odatas object to access its operations. */ private Odatas odatas; /** * Gets the Odatas object to access its operations. * @return the Odatas object. */ public Odatas odatas() { return this.odatas; } /** * The Headers object to access its operations. */ private Headers headers; /** * Gets the Headers object to access its operations. * @return the Headers object. */ public Headers headers() { return this.headers; } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(ServiceClientCredentials credentials) { this("http://localhost", credentials); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(String baseUrl, ServiceClientCredentials credentials) { this(new RestClient.Builder() .withBaseUrl(baseUrl) .withCredentials(credentials) .build()); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param restClient the REST client to connect to Azure. */ public AutoRestAzureSpecialParametersTestClientImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2015-07-01-preview"; this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.xMsClientRequestIds = new XMsClientRequestIdsImpl(restClient().retrofit(), this); this.subscriptionInCredentials = new SubscriptionInCredentialsImpl(restClient().retrofit(), this); this.subscriptionInMethods = new SubscriptionInMethodsImpl(restClient().retrofit(), this); this.apiVersionDefaults = new ApiVersionDefaultsImpl(restClient().retrofit(), this); this.apiVersionLocals = new ApiVersionLocalsImpl(restClient().retrofit(), this); this.skipUrlEncodings = new SkipUrlEncodingsImpl(restClient().retrofit(), this); this.odatas = new OdatasImpl(restClient().retrofit(), this); this.headers = new HeadersImpl(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("Azure-SDK-For-Java/%s (%s)", getClass().getPackage().getImplementationVersion(), "AutoRestAzureSpecialParametersTestClient, 2015-07-01-preview"); } }
yaqiyang/autorest
src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/azurespecials/implementation/AutoRestAzureSpecialParametersTestClientImpl.java
Java
mit
10,599
package org.jabref.benchmarks; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.jabref.Globals; import org.jabref.logic.exporter.BibtexDatabaseWriter; import org.jabref.logic.exporter.SavePreferences; import org.jabref.logic.exporter.StringSaveSession; import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.logic.search.SearchQuery; import org.jabref.model.Defaults; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.BibDatabaseModeDetection; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.KeywordGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.JabRefPreferences; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; @State(Scope.Thread) public class Benchmarks { private String bibtexString; private final BibDatabase database = new BibDatabase(); private String latexConversionString; private String htmlConversionString; @Setup public void init() throws Exception { Globals.prefs = JabRefPreferences.getInstance(); Random randomizer = new Random(); for (int i = 0; i < 1000; i++) { BibEntry entry = new BibEntry(); entry.setCiteKey("id" + i); entry.setField("title", "This is my title " + i); entry.setField("author", "Firstname Lastname and FirstnameA LastnameA and FirstnameB LastnameB" + i); entry.setField("journal", "Journal Title " + i); entry.setField("keyword", "testkeyword"); entry.setField("year", "1" + i); entry.setField("rnd", "2" + randomizer.nextInt()); database.insertEntry(entry); } BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); bibtexString = saveSession.getStringValue(); latexConversionString = "{A} \\textbf{bold} approach {\\it to} ${{\\Sigma}}{\\Delta}$ modulator \\textsuperscript{2} \\$"; htmlConversionString = "<b>&Ouml;sterreich</b> &#8211; &amp; characters &#x2aa2; <i>italic</i>"; } @Benchmark public ParserResult parse() throws IOException { BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences()); return parser.parse(new StringReader(bibtexString)); } @Benchmark public String write() throws Exception { BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); return saveSession.getStringValue(); } @Benchmark public List<BibEntry> search() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().stream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public List<BibEntry> parallelSearch() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().parallelStream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public BibDatabaseMode inferBibDatabaseMode() { return BibDatabaseModeDetection.inferMode(database); } @Benchmark public String latexToUnicodeConversion() { LatexToUnicodeFormatter f = new LatexToUnicodeFormatter(); return f.format(latexConversionString); } @Benchmark public String latexToHTMLConversion() { HTMLChars f = new HTMLChars(); return f.format(latexConversionString); } @Benchmark public String htmlToLatexConversion() { HtmlToLatexFormatter f = new HtmlToLatexFormatter(); return f.format(htmlConversionString); } @Benchmark public boolean keywordGroupContains() throws ParseException { KeywordGroup group = new WordKeywordGroup("testGroup", GroupHierarchyType.INDEPENDENT, "keyword", "testkeyword", false, ',', false); return group.containsAll(database.getEntries()); } public static void main(String[] args) throws IOException, RunnerException { Main.main(args); } }
shitikanth/jabref
src/jmh/java/org/jabref/benchmarks/Benchmarks.java
Java
mit
5,418
/** * Copyright (c) 2014,2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.core.library.items; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.library.CoreItemFactory; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; /** * A DimmerItem can be used as a switch (ON/OFF), but it also accepts percent values * to reflect the dimmed state. * * @author Kai Kreuzer - Initial contribution and API * @author Markus Rathgeb - Support more types for getStateAs * */ @NonNullByDefault public class DimmerItem extends SwitchItem { private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>(); private static List<Class<? extends Command>> acceptedCommandTypes = new ArrayList<Class<? extends Command>>(); static { acceptedDataTypes.add(PercentType.class); acceptedDataTypes.add(OnOffType.class); acceptedDataTypes.add(UnDefType.class); acceptedCommandTypes.add(PercentType.class); acceptedCommandTypes.add(OnOffType.class); acceptedCommandTypes.add(IncreaseDecreaseType.class); acceptedCommandTypes.add(RefreshType.class); } public DimmerItem(String name) { super(CoreItemFactory.DIMMER, name); } /* package */ DimmerItem(String type, String name) { super(type, name); } public void send(PercentType command) { internalSend(command); } @Override public List<Class<? extends State>> getAcceptedDataTypes() { return Collections.unmodifiableList(acceptedDataTypes); } @Override public List<Class<? extends Command>> getAcceptedCommandTypes() { return Collections.unmodifiableList(acceptedCommandTypes); } @Override public void setState(State state) { if (isAcceptedState(acceptedDataTypes, state)) { // try conversion State convertedState = state.as(PercentType.class); if (convertedState != null) { applyState(convertedState); } else { applyState(state); } } else { logSetTypeError(state); } } }
Snickermicker/smarthome
bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/items/DimmerItem.java
Java
epl-1.0
3,066
/* * ome.server.itests.ImmutabilityTest * * Copyright 2006 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.server.itests; // Java imports // Third-party libraries import org.testng.annotations.Test; // Application-internal dependencies import ome.model.core.Image; import ome.model.meta.Event; import ome.parameters.Filter; import ome.parameters.Parameters; /** * * @author Josh Moore &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:josh.moore@gmx.de">josh.moore@gmx.de</a> * @version 1.0 <small> (<b>Internal version:</b> $Rev$ $Date$) </small> * @since 1.0 */ public class ImmutabilityTest extends AbstractManagedContextTest { @Test public void testCreationEventWillBeSilentlyUnchanged() throws Exception { loginRoot(); Image i = new_Image("immutable creation"); i = iUpdate.saveAndReturnObject(i); Event oldEvent = i.getDetails().getCreationEvent(); Event newEvent = iQuery.findByQuery( "select e from Event e where id != :id", new Parameters( new Filter().page(0, 1)).addId(oldEvent.getId())); i.getDetails().setCreationEvent(newEvent); // This fails because it gets silently copied to our new instance. See: // http://trac.openmicroscopy.org.uk/ome/ticket/346 // i = iUpdate.saveAndReturnObject(i); // assertEquals( i.getDetails().getCreationEvent().getId(), // oldEvent.getId()); // Saving and reacquiring to be sure. iUpdate.saveObject(i); // unfortunately still not working properly i = iQuery.refresh(i); i = iQuery.get(i.getClass(), i.getId()); assertEquals(i.getDetails().getCreationEvent().getId(), oldEvent .getId()); } }
bramalingam/openmicroscopy
components/server/test/ome/server/itests/ImmutabilityTest.java
Java
gpl-2.0
1,831
/* * uiComponents.CustomLabel * *------------------------------------------------------------------------------ * Copyright (C) 2006-2008 University of Dundee. All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.agents.editor.uiComponents; //Java imports import javax.swing.Icon; import javax.swing.JLabel; //Third-party libraries //Application-internal dependencies /** * A Custom Label, which should be used by the UI instead of using * JLabel. Sets the font to CUSTOM FONT. * * This font is also used by many other Custom UI components in this * package, making it easy to change the font in many components in * one place (here!). * * @author William Moore &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:will@lifesci.dundee.ac.uk">will@lifesci.dundee.ac.uk</a> * @version 3.0 * <small> * (<b>Internal version:</b> $Revision: $Date: $) * </small> * @since OME3.0 */ public class CustomLabel extends JLabel { private int fontSize; /** * Simply delegates to JLabel superclass. */ public CustomLabel() { super(); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(Icon image) { super(image); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(String text) { super(text); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(String text, int fontSize) { super(text); this.fontSize = fontSize; setFont(); } private void setFont() { if (fontSize == 0) setFont(new CustomFont()); else { setFont(CustomFont.getFontBySize(fontSize)); } } }
jballanc/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/agents/editor/uiComponents/CustomLabel.java
Java
gpl-2.0
2,450
package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; public class TopicStruct { private String topicTitle; private String topicUrl; public TopicStruct () { } public TopicStruct (JSONObject json) { this.topicTitle = json.optString("topic_title"); this.topicUrl = json.optString("topic_url"); } public String getTopicTitle() { return this.topicTitle; } public void setTopicTitle(String topicTitle) { this.topicTitle = topicTitle; } public String getTopicUrl() { return this.topicUrl; } public void setTopicUrl(String topicUrl) { this.topicUrl = topicUrl; } }
JohnTsaiAndroid/iBeebo
app/src/main/java/org/zarroboogs/weibo/hot/bean/hotweibo/TopicStruct.java
Java
gpl-3.0
718
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package mod._streams.uno; import com.sun.star.io.XActiveDataSink; import com.sun.star.io.XActiveDataSource; import com.sun.star.io.XDataOutputStream; import com.sun.star.io.XInputStream; import com.sun.star.io.XOutputStream; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import java.util.ArrayList; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; /** * Test for object which is represented by service * <code>com.sun.star.io.DataInputStream</code>. * <ul> * <li> <code>com::sun::star::io::XInputStream</code></li> * <li> <code>com::sun::star::io::XDataInputStream</code></li> * <li> <code>com::sun::star::io::XConnectable</code></li> * <li> <code>com::sun::star::io::XActiveDataSink</code></li> * </ul> * @see com.sun.star.io.DataInputStream * @see com.sun.star.io.XInputStream * @see com.sun.star.io.XDataInputStream * @see com.sun.star.io.XConnectable * @see com.sun.star.io.XActiveDataSink * @see ifc.io._XInputStream * @see ifc.io._XDataInputStream * @see ifc.io._XConnectable * @see ifc.io._XActiveDataSink */ public class DataInputStream extends TestCase { /** * Creates a TestEnvironment for the interfaces to be tested. * Creates <code>com.sun.star.io.DataInputStream</code> object, * connects it to <code>com.sun.star.io.DataOutputStream</code> * through <code>com.sun.star.io.Pipe</code>. All of possible data * types are written into <code>DataOutputStream</code>. * Object relations created : * <ul> * <li> <code>'StreamData'</code> for * {@link ifc.io._XDataInputStream}(the data that should be written into * the stream) </li> * <li> <code>'ByteData'</code> for * {@link ifc.io._XInputStream}(the data that should be written into * the stream) </li> * <li> <code>'StreamWriter'</code> for * {@link ifc.io._XDataInputStream} * {@link ifc.io._XInputStream}(a stream to write data to) </li> * <li> <code>'Connectable'</code> for * {@link ifc.io._XConnectable}(another object that can be connected) </li> * <li> <code>'InputStream'</code> for * {@link ifc.io._XActiveDataSink}(an input stream to set and get) </li> * </ul> */ @Override protected TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) throws Exception { Object oInterface = null; XMultiServiceFactory xMSF = Param.getMSF(); oInterface = xMSF.createInstance("com.sun.star.io.DataInputStream"); XInterface oObj = (XInterface) oInterface; // creating and connecting DataOutputStream to the // DataInputStream created through the Pipe XActiveDataSink xDataSink = UnoRuntime.queryInterface(XActiveDataSink.class, oObj); XInterface oPipe = (XInterface) xMSF.createInstance("com.sun.star.io.Pipe"); XInputStream xPipeInput = UnoRuntime.queryInterface(XInputStream.class, oPipe); XOutputStream xPipeOutput = UnoRuntime.queryInterface(XOutputStream.class, oPipe); XInterface oDataOutput = (XInterface) xMSF.createInstance("com.sun.star.io.DataOutputStream"); XDataOutputStream xDataOutput = UnoRuntime.queryInterface(XDataOutputStream.class, oDataOutput) ; XActiveDataSource xDataSource = UnoRuntime.queryInterface(XActiveDataSource.class, oDataOutput) ; xDataSource.setOutputStream(xPipeOutput) ; xDataSink.setInputStream(xPipeInput) ; // all data types for writing to an XDataInputStream ArrayList<Object> data = new ArrayList<Object>() ; data.add(Boolean.TRUE) ; data.add(Byte.valueOf((byte)123)) ; data.add(new Character((char)1234)) ; data.add(Short.valueOf((short)1234)) ; data.add(Integer.valueOf(123456)) ; data.add(new Float(1.234)) ; data.add(new Double(1.23456)) ; data.add("DataInputStream") ; // information for writing to the pipe byte[] byteData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 } ; // creating a connectable object for XConnectable interface XInterface xConnect = (XInterface)xMSF.createInstance( "com.sun.star.io.DataInputStream") ; // creating an input stream to set in XActiveDataSink XInterface oDataInput = (XInterface) xMSF.createInstance( "com.sun.star.io.Pipe" ); log.println("creating a new environment for object"); TestEnvironment tEnv = new TestEnvironment( oObj ); // adding sequence of data that must be read // by XDataInputStream interface methods tEnv.addObjRelation("StreamData", data) ; // add a writer tEnv.addObjRelation("StreamWriter", xDataOutput); // add a connectable tEnv.addObjRelation("Connectable", xConnect); // add an inputStream tEnv.addObjRelation("InputStream", oDataInput); tEnv.addObjRelation("ByteData", byteData); return tEnv; } // finish method getTestEnvironment }
jvanz/core
qadevOOo/tests/java/mod/_streams/uno/DataInputStream.java
Java
gpl-3.0
6,006
package com.earth2me.essentials.antibuild; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { private final transient Map<AntiBuildConfig, Boolean> settingsBoolean = new EnumMap<AntiBuildConfig, Boolean>(AntiBuildConfig.class); private final transient Map<AntiBuildConfig, List<Integer>> settingsList = new EnumMap<AntiBuildConfig, List<Integer>>(AntiBuildConfig.class); private transient EssentialsConnect ess = null; @Override public void onEnable() { final PluginManager pm = this.getServer().getPluginManager(); final Plugin essPlugin = pm.getPlugin("Essentials"); if (essPlugin == null || !essPlugin.isEnabled()) { return; } ess = new EssentialsConnect(essPlugin, this); final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this); pm.registerEvents(blockListener, this); } @Override public boolean checkProtectionItems(final AntiBuildConfig list, final int id) { final List<Integer> itemList = settingsList.get(list); return itemList != null && !itemList.isEmpty() && itemList.contains(id); } @Override public EssentialsConnect getEssentialsConnect() { return ess; } @Override public Map<AntiBuildConfig, Boolean> getSettingsBoolean() { return settingsBoolean; } @Override public Map<AntiBuildConfig, List<Integer>> getSettingsList() { return settingsList; } @Override public boolean getSettingBool(final AntiBuildConfig protectConfig) { final Boolean bool = settingsBoolean.get(protectConfig); return bool == null ? protectConfig.getDefaultValueBoolean() : bool; } }
walster001/Essentials
EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java
Java
gpl-3.0
1,783
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.jboss.as.test.manualmode.secman; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.manualmode.deployment.AbstractDeploymentScannerBasedTestCase; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.ServerControl; import org.wildfly.core.testrunner.ServerController; import org.wildfly.core.testrunner.WildflyTestRunner; import javax.inject.Inject; import java.io.File; /** * Tests the processing of {@code permissions.xml} in deployments * * @author Jaikiran Pai */ @RunWith(WildflyTestRunner.class) @ServerControl(manual = true) public class PermissionsDeploymentTestCase extends AbstractDeploymentScannerBasedTestCase { private static final String SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS = "-Dorg.jboss.server.bootstrap.maxThreads=1"; @Rule public TemporaryFolder tempDir = new TemporaryFolder(); @Inject private ServerController container; private ModelControllerClient modelControllerClient; @Before public void before() throws Exception { modelControllerClient = TestSuiteEnvironment.getModelControllerClient(); } @After public void after() throws Exception { modelControllerClient.close(); } @Override protected File getDeployDir() { return this.tempDir.getRoot(); } /** * Tests that when the server is booted with {@code org.jboss.server.bootstrap.maxThreads} system property * set (to whatever value), the deployment unit processors relevant for dealing with processing of {@code permissions.xml}, * in deployments, do run and process the deployment * <p> * NOTE: This test just tests that the deployment unit processor(s) process the deployment unit for the {@code permissions.xml} * and it's not in the scope of this test to verify that the permissions configured in that file are indeed applied correctly * to the deployment unit * * @throws Exception * @see <a href="https://issues.jboss.org/browse/WFLY-6657">WFLY-6657</a> */ @Test public void testWithConfiguredMaxBootThreads() throws Exception { // Test-runner's ServerController/Server uses prop jvm.args to control what args are passed // to the server process VM. So, we add the system property controlling the max boot threads, // here final String existingJvmArgs = System.getProperty("jvm.args"); if (existingJvmArgs == null) { System.setProperty("jvm.args", SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS); } else { System.setProperty("jvm.args", existingJvmArgs + " " + SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS); } // start the container container.start(); try { addDeploymentScanner(modelControllerClient,1000, false, true); this.testInvalidPermissionsXmlDeployment("test-permissions-xml-with-configured-max-boot-threads.jar"); } finally { removeDeploymentScanner(modelControllerClient); container.stop(); if (existingJvmArgs == null) { System.clearProperty("jvm.args"); } else { System.setProperty("jvm.args", existingJvmArgs); } } } /** * Tests that when the server is booted *without* the {@code org.jboss.server.bootstrap.maxThreads} system property * set, the deployment unit processors relevant for dealing with processing of {@code permissions.xml}, * in deployments, do run and process the deployment * <p> * NOTE: This test just tests that the deployment unit processor(s) process the deployment unit for the {@code permissions.xml} * and it's not in the scope of this test to verify that the permissions configured in that file are indeed applied correctly * to the deployment unit * * @throws Exception * @see <a href="https://issues.jboss.org/browse/WFLY-6657">WFLY-6657</a> */ @Test public void testWithoutConfiguredMaxBootThreads() throws Exception { container.start(); try { addDeploymentScanner(modelControllerClient,1000, false, true); this.testInvalidPermissionsXmlDeployment("test-permissions-xml-without-max-boot-threads.jar"); } finally { removeDeploymentScanner(modelControllerClient); container.stop(); } } private void testInvalidPermissionsXmlDeployment(final String deploymentName) throws Exception { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class); // add an empty (a.k.a invalid content) in permissions.xml jar.addAsManifestResource(new StringAsset(""), "permissions.xml"); // "deploy" it by placing it in the deployment directory jar.as(ZipExporter.class).exportTo(new File(getDeployDir(), deploymentName)); final PathAddress deploymentPathAddr = PathAddress.pathAddress(ModelDescriptionConstants.DEPLOYMENT, deploymentName); // wait for the deployment to be picked up and completed (either with success or failure) waitForDeploymentToFinish(deploymentPathAddr); // the deployment is expected to fail due to a parsing error in the permissions.xml Assert.assertEquals("Deployment was expected to fail", "FAILED", deploymentState(modelControllerClient, deploymentPathAddr)); } private void waitForDeploymentToFinish(final PathAddress deploymentPathAddr) throws Exception { // Wait until deployed ... long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!exists(modelControllerClient, deploymentPathAddr) && System.currentTimeMillis() < timeout) { Thread.sleep(100); } Assert.assertTrue(exists(modelControllerClient, deploymentPathAddr)); } }
aloubyansky/wildfly-core
testsuite/manualmode/src/test/java/org/jboss/as/test/manualmode/secman/PermissionsDeploymentTestCase.java
Java
lgpl-2.1
7,442
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.type.comparator; import java.util.Comparator; import lucee.commons.lang.ComparatorUtil; import lucee.runtime.PageContext; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.PageException; import lucee.runtime.op.Caster; /** * Implementation of a Comparator, compares to Softregister Objects */ public final class SortRegisterComparator implements ExceptionComparator { private boolean isAsc; private PageException pageException=null; private boolean ignoreCase; private final Comparator comparator; /** * constructor of the class * @param isAsc is ascending or descending * @param ignoreCase do ignore case */ public SortRegisterComparator(PageContext pc,boolean isAsc, boolean ignoreCase, boolean localeSensitive) { this.isAsc=isAsc; this.ignoreCase=ignoreCase; comparator = ComparatorUtil.toComparator( ignoreCase?ComparatorUtil.SORT_TYPE_TEXT_NO_CASE:ComparatorUtil.SORT_TYPE_TEXT , isAsc, localeSensitive?ThreadLocalPageContext.getLocale(pc):null, null); } /** * @return Returns the expressionException. */ public PageException getPageException() { return pageException; } @Override public int compare(Object oLeft, Object oRight) { try { if(pageException!=null) return 0; else if(isAsc) return compareObjects(oLeft, oRight); else return compareObjects(oRight, oLeft); } catch (PageException e) { pageException=e; return 0; } } private int compareObjects(Object oLeft, Object oRight) throws PageException { String strLeft=Caster.toString(((SortRegister)oLeft).getValue()); String strRight=Caster.toString(((SortRegister)oRight).getValue()); return comparator.compare(strLeft, strRight); } }
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/type/comparator/SortRegisterComparator.java
Java
lgpl-2.1
2,517
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.services.backend.compiler; import java.io.File; import java.io.Serializable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.kie.workbench.common.services.backend.compiler.impl.WorkspaceCompilationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.uberfire.java.nio.file.Files; import org.uberfire.java.nio.file.Path; import org.uberfire.java.nio.file.Paths; public class BaseCompilerTest implements Serializable { protected static Path tmpRoot; protected String mavenRepoPath; protected static Logger logger = LoggerFactory.getLogger(BaseCompilerTest.class); protected String alternateSettingsAbsPath; protected WorkspaceCompilationInfo info; protected AFCompiler compiler; @BeforeClass public static void setup() { System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); } public BaseCompilerTest(String prjName) { try { mavenRepoPath = TestUtilMaven.getMavenRepo(); tmpRoot = Files.createTempDirectory("repo"); alternateSettingsAbsPath = new File("src/test/settings.xml").getAbsolutePath(); Path tmp = Files.createDirectories(Paths.get(tmpRoot.toString(), "dummy")); TestUtil.copyTree(Paths.get(prjName), tmp); info = new WorkspaceCompilationInfo(Paths.get(tmp.toUri())); } catch (Exception e) { logger.error(e.getMessage()); } } @AfterClass public static void tearDown() { System.clearProperty("org.uberfire.nio.git.daemon.enabled"); System.clearProperty("org.uberfire.nio.git.ssh.enabled"); if (tmpRoot != null) { TestUtil.rm(tmpRoot.toFile()); } } }
jomarko/kie-wb-common
kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-service/src/test/java/org/kie/workbench/common/services/backend/compiler/BaseCompilerTest.java
Java
apache-2.0
2,464
/* * 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.ode.ql.tree.nodes; public class Equality extends IdentifierToValueCMP { private static final long serialVersionUID = 8151616227509392901L; /** * @param identifier * @param value */ public Equality(Identifier identifier, Value value) { super(identifier, value); } }
Subasinghe/ode
bpel-ql/src/main/java/org/apache/ode/ql/tree/nodes/Equality.java
Java
apache-2.0
1,136
/* * Copyright 2000-2009 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.packageDependencies; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.AnalysisScopeBundle; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ForwardDependenciesBuilder extends DependenciesBuilder { private final Map<PsiFile, Set<PsiFile>> myDirectDependencies = new HashMap<PsiFile, Set<PsiFile>>(); public ForwardDependenciesBuilder(@NotNull Project project, @NotNull AnalysisScope scope) { super(project, scope); } public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final AnalysisScope scopeOfInterest) { super(project, scope, scopeOfInterest); } public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final int transitive) { super(project, scope); myTransitive = transitive; } @Override public String getRootNodeNameInUsageView(){ return AnalysisScopeBundle.message("forward.dependencies.usage.view.root.node.text"); } @Override public String getInitialUsagesPosition(){ return AnalysisScopeBundle.message("forward.dependencies.usage.view.initial.text"); } @Override public boolean isBackward(){ return false; } @Override public void analyze() { final PsiManager psiManager = PsiManager.getInstance(getProject()); psiManager.startBatchFilesProcessingMode(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex(); try { getScope().accept(new PsiRecursiveElementVisitor() { @Override public void visitFile(final PsiFile file) { visit(file, fileIndex, psiManager, 0); } }); } finally { psiManager.finishBatchFilesProcessingMode(); } } private void visit(final PsiFile file, final ProjectFileIndex fileIndex, final PsiManager psiManager, int depth) { final FileViewProvider viewProvider = file.getViewProvider(); if (viewProvider.getBaseLanguage() != file.getLanguage()) return; if (getScopeOfInterest() != null && !getScopeOfInterest().contains(file)) return; ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final VirtualFile virtualFile = file.getVirtualFile(); if (indicator != null) { if (indicator.isCanceled()) { throw new ProcessCanceledException(); } indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text")); if (virtualFile != null) { indicator.setText2(getRelativeToProjectPath(virtualFile)); } if ( myTotalFileCount > 0) { indicator.setFraction(((double)++ myFileCount) / myTotalFileCount); } } final boolean isInLibrary = virtualFile == null || fileIndex.isInLibrarySource(virtualFile) || fileIndex.isInLibraryClasses(virtualFile); final Set<PsiFile> collectedDeps = new HashSet<PsiFile>(); final HashSet<PsiFile> processed = new HashSet<PsiFile>(); collectedDeps.add(file); do { if (depth++ > getTransitiveBorder()) return; for (PsiFile psiFile : new HashSet<PsiFile>(collectedDeps)) { final VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { if (indicator != null) { indicator.setText2(getRelativeToProjectPath(vFile)); } if (!isInLibrary && (fileIndex.isInLibraryClasses(vFile) || fileIndex.isInLibrarySource(vFile))) { processed.add(psiFile); } } final Set<PsiFile> found = new HashSet<PsiFile>(); if (!processed.contains(psiFile)) { processed.add(psiFile); analyzeFileDependencies(psiFile, new DependencyProcessor() { @Override public void process(PsiElement place, PsiElement dependency) { PsiFile dependencyFile = dependency.getContainingFile(); if (dependencyFile != null) { if (viewProvider == dependencyFile.getViewProvider()) return; if (dependencyFile.isPhysical()) { final VirtualFile virtualFile = dependencyFile.getVirtualFile(); if (virtualFile != null && (fileIndex.isInContent(virtualFile) || fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile))) { found.add(dependencyFile); } } } } }); Set<PsiFile> deps = getDependencies().get(file); if (deps == null) { deps = new HashSet<PsiFile>(); getDependencies().put(file, deps); } deps.addAll(found); getDirectDependencies().put(psiFile, new HashSet<PsiFile>(found)); collectedDeps.addAll(found); psiManager.dropResolveCaches(); InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file); } } collectedDeps.removeAll(processed); } while (isTransitive() && !collectedDeps.isEmpty()); } @Override public Map<PsiFile, Set<PsiFile>> getDirectDependencies() { return myDirectDependencies; } }
romankagan/DDBWorkbench
platform/analysis-impl/src/com/intellij/packageDependencies/ForwardDependenciesBuilder.java
Java
apache-2.0
6,335
/** * JBoss, Home of Professional Open Source. * Copyright 2014 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.common.util; /** * Simple wrapper class which contains a result and an exception. * This can be useful for example when performing asynchronous operations * which do not immediately return, but could throw an exception. * * @param <R> The result of the operation * @param <E> The exception (if any) thrown during the operation. */ public class ResultWrapper<R, E extends Exception> { private E exception; private R result; public ResultWrapper(R result) { this.result = result; } public ResultWrapper(R result, E exception) { this.result = result; this.exception = exception; } /** Returns null if no exception was thrown */ /** * @return */ public E getException() { return exception; } public R getResult() { return result; } }
ruhan1/pnc
common/src/main/java/org/jboss/pnc/common/util/ResultWrapper.java
Java
apache-2.0
1,569
/* * Copyright 2015 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.widgets.common.client.colorpicker.dialog; import com.google.gwt.event.shared.EventHandler; public interface DialogClosedHandler extends EventHandler { void dialogClosed(DialogClosedEvent event); }
wmedvede/uberfire-extensions
uberfire-widgets/uberfire-widgets-commons/src/main/java/org/uberfire/ext/widgets/common/client/colorpicker/dialog/DialogClosedHandler.java
Java
apache-2.0
849
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.LogMediatorInputConnector} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class LogMediatorInputConnectorItemProvider extends InputConnectorItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LogMediatorInputConnectorItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns LogMediatorInputConnector.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/LogMediatorInputConnector")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("_UI_LogMediatorInputConnector_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
nwnpallewela/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/LogMediatorInputConnectorItemProvider.java
Java
apache-2.0
2,890
/** * 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.yarn.server.api.protocolrecords.impl.pb; import org.apache.hadoop.thirdparty.protobuf.TextFormat; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationIdPBImpl; import org.apache.hadoop.yarn.proto.YarnProtos; import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProtoOrBuilder; import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProto; import org.apache.hadoop.yarn.server.api.protocolrecords.GetTimelineCollectorContextRequest; public class GetTimelineCollectorContextRequestPBImpl extends GetTimelineCollectorContextRequest { private GetTimelineCollectorContextRequestProto proto = GetTimelineCollectorContextRequestProto.getDefaultInstance(); private GetTimelineCollectorContextRequestProto.Builder builder = null; private boolean viaProto = false; private ApplicationId appId = null; public GetTimelineCollectorContextRequestPBImpl() { builder = GetTimelineCollectorContextRequestProto.newBuilder(); } public GetTimelineCollectorContextRequestPBImpl( GetTimelineCollectorContextRequestProto proto) { this.proto = proto; viaProto = true; } public GetTimelineCollectorContextRequestProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } private void mergeLocalToBuilder() { if (appId != null) { builder.setAppId(convertToProtoFormat(this.appId)); } } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = GetTimelineCollectorContextRequestProto.newBuilder(proto); } viaProto = false; } @Override public ApplicationId getApplicationId() { if (this.appId != null) { return this.appId; } GetTimelineCollectorContextRequestProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasAppId()) { return null; } this.appId = convertFromProtoFormat(p.getAppId()); return this.appId; } @Override public void setApplicationId(ApplicationId id) { maybeInitBuilder(); if (id == null) { builder.clearAppId(); } this.appId = id; } private ApplicationIdPBImpl convertFromProtoFormat( YarnProtos.ApplicationIdProto p) { return new ApplicationIdPBImpl(p); } private YarnProtos.ApplicationIdProto convertToProtoFormat(ApplicationId t) { return ((ApplicationIdPBImpl)t).getProto(); } }
steveloughran/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/GetTimelineCollectorContextRequestPBImpl.java
Java
apache-2.0
3,988
/* * 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.codeInsight.template.impl; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.hash.LinkedHashMap; /** * @author Maxim.Mossienko */ public class TemplateImplUtil { public static LinkedHashMap<String, Variable> parseVariables(CharSequence text) { LinkedHashMap<String, Variable> variables = new LinkedHashMap<String, Variable>(); TemplateTextLexer lexer = new TemplateTextLexer(); lexer.start(text); while (true) { IElementType tokenType = lexer.getTokenType(); if (tokenType == null) break; int start = lexer.getTokenStart(); int end = lexer.getTokenEnd(); String token = text.subSequence(start, end).toString(); if (tokenType == TemplateTokenType.VARIABLE) { String name = token.substring(1, token.length() - 1); if (!variables.containsKey(name)) { variables.put(name, new Variable(name, "", "", true)); } } lexer.advance(); } return variables; } public static boolean isValidVariableName(String varName) { return parseVariables("$" + varName + "$").containsKey(varName); } }
kdwink/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateImplUtil.java
Java
apache-2.0
1,752
/* * 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.common.io.stream; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.CheckedBiConsumer; import org.elasticsearch.common.CheckedFunction; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.test.ESTestCase; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.iterableWithSize; public class StreamTests extends ESTestCase { public void testBooleanSerialization() throws IOException { final BytesStreamOutput output = new BytesStreamOutput(); output.writeBoolean(false); output.writeBoolean(true); final BytesReference bytesReference = output.bytes(); final BytesRef bytesRef = bytesReference.toBytesRef(); assertThat(bytesRef.length, equalTo(2)); final byte[] bytes = bytesRef.bytes; assertThat(bytes[0], equalTo((byte) 0)); assertThat(bytes[1], equalTo((byte) 1)); final StreamInput input = bytesReference.streamInput(); assertFalse(input.readBoolean()); assertTrue(input.readBoolean()); final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet()); set.remove((byte) 0); set.remove((byte) 1); final byte[] corruptBytes = new byte[]{randomFrom(set)}; final BytesReference corrupt = new BytesArray(corruptBytes); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readBoolean()); final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]); assertThat(e, hasToString(containsString(message))); } public void testOptionalBooleanSerialization() throws IOException { final BytesStreamOutput output = new BytesStreamOutput(); output.writeOptionalBoolean(false); output.writeOptionalBoolean(true); output.writeOptionalBoolean(null); final BytesReference bytesReference = output.bytes(); final BytesRef bytesRef = bytesReference.toBytesRef(); assertThat(bytesRef.length, equalTo(3)); final byte[] bytes = bytesRef.bytes; assertThat(bytes[0], equalTo((byte) 0)); assertThat(bytes[1], equalTo((byte) 1)); assertThat(bytes[2], equalTo((byte) 2)); final StreamInput input = bytesReference.streamInput(); final Boolean maybeFalse = input.readOptionalBoolean(); assertNotNull(maybeFalse); assertFalse(maybeFalse); final Boolean maybeTrue = input.readOptionalBoolean(); assertNotNull(maybeTrue); assertTrue(maybeTrue); assertNull(input.readOptionalBoolean()); final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet()); set.remove((byte) 0); set.remove((byte) 1); set.remove((byte) 2); final byte[] corruptBytes = new byte[]{randomFrom(set)}; final BytesReference corrupt = new BytesArray(corruptBytes); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readOptionalBoolean()); final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]); assertThat(e, hasToString(containsString(message))); } public void testRandomVLongSerialization() throws IOException { for (int i = 0; i < 1024; i++) { long write = randomLong(); BytesStreamOutput out = new BytesStreamOutput(); out.writeZLong(write); long read = out.bytes().streamInput().readZLong(); assertEquals(write, read); } } public void testSpecificVLongSerialization() throws IOException { List<Tuple<Long, byte[]>> values = Arrays.asList( new Tuple<>(0L, new byte[]{0}), new Tuple<>(-1L, new byte[]{1}), new Tuple<>(1L, new byte[]{2}), new Tuple<>(-2L, new byte[]{3}), new Tuple<>(2L, new byte[]{4}), new Tuple<>(Long.MIN_VALUE, new byte[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, 1}), new Tuple<>(Long.MAX_VALUE, new byte[]{-2, -1, -1, -1, -1, -1, -1, -1, -1, 1}) ); for (Tuple<Long, byte[]> value : values) { BytesStreamOutput out = new BytesStreamOutput(); out.writeZLong(value.v1()); assertArrayEquals(Long.toString(value.v1()), value.v2(), BytesReference.toBytes(out.bytes())); BytesReference bytes = new BytesArray(value.v2()); assertEquals(Arrays.toString(value.v2()), (long) value.v1(), bytes.streamInput().readZLong()); } } public void testLinkedHashMap() throws IOException { int size = randomIntBetween(1, 1024); boolean accessOrder = randomBoolean(); List<Tuple<String, Integer>> list = new ArrayList<>(size); LinkedHashMap<String, Integer> write = new LinkedHashMap<>(size, 0.75f, accessOrder); for (int i = 0; i < size; i++) { int value = randomInt(); list.add(new Tuple<>(Integer.toString(i), value)); write.put(Integer.toString(i), value); } if (accessOrder) { // randomize access order Collections.shuffle(list, random()); for (Tuple<String, Integer> entry : list) { // touch the entries to set the access order write.get(entry.v1()); } } BytesStreamOutput out = new BytesStreamOutput(); out.writeGenericValue(write); LinkedHashMap<String, Integer> read = (LinkedHashMap<String, Integer>) out.bytes().streamInput().readGenericValue(); assertEquals(size, read.size()); int index = 0; for (Map.Entry<String, Integer> entry : read.entrySet()) { assertEquals(list.get(index).v1(), entry.getKey()); assertEquals(list.get(index).v2(), entry.getValue()); index++; } } public void testFilterStreamInputDelegatesAvailable() throws IOException { final int length = randomIntBetween(1, 1024); StreamInput delegate = StreamInput.wrap(new byte[length]); FilterStreamInput filterInputStream = new FilterStreamInput(delegate) { }; assertEquals(filterInputStream.available(), length); // read some bytes final int bytesToRead = randomIntBetween(1, length); filterInputStream.readBytes(new byte[bytesToRead], 0, bytesToRead); assertEquals(filterInputStream.available(), length - bytesToRead); } public void testInputStreamStreamInputDelegatesAvailable() throws IOException { final int length = randomIntBetween(1, 1024); ByteArrayInputStream is = new ByteArrayInputStream(new byte[length]); InputStreamStreamInput streamInput = new InputStreamStreamInput(is); assertEquals(streamInput.available(), length); // read some bytes final int bytesToRead = randomIntBetween(1, length); streamInput.readBytes(new byte[bytesToRead], 0, bytesToRead); assertEquals(streamInput.available(), length - bytesToRead); } public void testReadArraySize() throws IOException { BytesStreamOutput stream = new BytesStreamOutput(); byte[] array = new byte[randomIntBetween(1, 10)]; for (int i = 0; i < array.length; i++) { array[i] = randomByte(); } stream.writeByteArray(array); InputStreamStreamInput streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), array .length - 1); expectThrows(EOFException.class, streamInput::readByteArray); streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), BytesReference.toBytes(stream .bytes()).length); assertArrayEquals(array, streamInput.readByteArray()); } public void testWritableArrays() throws IOException { final String[] strings = generateRandomStringArray(10, 10, false, true); WriteableString[] sourceArray = Arrays.stream(strings).<WriteableString>map(WriteableString::new).toArray(WriteableString[]::new); WriteableString[] targetArray; BytesStreamOutput out = new BytesStreamOutput(); if (randomBoolean()) { if (randomBoolean()) { sourceArray = null; } out.writeOptionalArray(sourceArray); targetArray = out.bytes().streamInput().readOptionalArray(WriteableString::new, WriteableString[]::new); } else { out.writeArray(sourceArray); targetArray = out.bytes().streamInput().readArray(WriteableString::new, WriteableString[]::new); } assertThat(targetArray, equalTo(sourceArray)); } public void testArrays() throws IOException { final String[] strings; final String[] deserialized; Writeable.Writer<String> writer = StreamOutput::writeString; Writeable.Reader<String> reader = StreamInput::readString; BytesStreamOutput out = new BytesStreamOutput(); if (randomBoolean()) { if (randomBoolean()) { strings = null; } else { strings = generateRandomStringArray(10, 10, false, true); } out.writeOptionalArray(writer, strings); deserialized = out.bytes().streamInput().readOptionalArray(reader, String[]::new); } else { strings = generateRandomStringArray(10, 10, false, true); out.writeArray(writer, strings); deserialized = out.bytes().streamInput().readArray(reader, String[]::new); } assertThat(deserialized, equalTo(strings)); } public void testCollection() throws IOException { class FooBar implements Writeable { private final int foo; private final int bar; private FooBar(final int foo, final int bar) { this.foo = foo; this.bar = bar; } private FooBar(final StreamInput in) throws IOException { this.foo = in.readInt(); this.bar = in.readInt(); } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeInt(foo); out.writeInt(bar); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FooBar that = (FooBar) o; return foo == that.foo && bar == that.bar; } @Override public int hashCode() { return Objects.hash(foo, bar); } } runWriteReadCollectionTest( () -> new FooBar(randomInt(), randomInt()), StreamOutput::writeCollection, in -> in.readList(FooBar::new)); } public void testStringCollection() throws IOException { runWriteReadCollectionTest(() -> randomUnicodeOfLength(16), StreamOutput::writeStringCollection, StreamInput::readStringList); } private <T> void runWriteReadCollectionTest( final Supplier<T> supplier, final CheckedBiConsumer<StreamOutput, Collection<T>, IOException> writer, final CheckedFunction<StreamInput, Collection<T>, IOException> reader) throws IOException { final int length = randomIntBetween(0, 10); final Collection<T> collection = new ArrayList<>(length); for (int i = 0; i < length; i++) { collection.add(supplier.get()); } try (BytesStreamOutput out = new BytesStreamOutput()) { writer.accept(out, collection); try (StreamInput in = out.bytes().streamInput()) { assertThat(collection, equalTo(reader.apply(in))); } } } public void testSetOfLongs() throws IOException { final int size = randomIntBetween(0, 6); final Set<Long> sourceSet = new HashSet<>(size); for (int i = 0; i < size; i++) { sourceSet.add(randomLongBetween(i * 1000, (i + 1) * 1000 - 1)); } assertThat(sourceSet, iterableWithSize(size)); final BytesStreamOutput out = new BytesStreamOutput(); out.writeCollection(sourceSet, StreamOutput::writeLong); final Set<Long> targetSet = out.bytes().streamInput().readSet(StreamInput::readLong); assertThat(targetSet, equalTo(sourceSet)); } public void testInstantSerialization() throws IOException { final Instant instant = Instant.now(); try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeInstant(instant); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readInstant(); assertEquals(instant, serialized); } } } public void testOptionalInstantSerialization() throws IOException { final Instant instant = Instant.now(); try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeOptionalInstant(instant); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readOptionalInstant(); assertEquals(instant, serialized); } } final Instant missing = null; try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeOptionalInstant(missing); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readOptionalInstant(); assertEquals(missing, serialized); } } } static final class WriteableString implements Writeable { final String string; WriteableString(String string) { this.string = string; } WriteableString(StreamInput in) throws IOException { this(in.readString()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteableString that = (WriteableString) o; return string.equals(that.string); } @Override public int hashCode() { return string.hashCode(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(string); } } }
strapdata/elassandra
server/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
Java
apache-2.0
16,395
/* * 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.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.session.SessionRepository; import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration; /** * Redis backed session configuration. * * @author Andy Wilkinson * @author Tommy Ludwig * @author Eddú Meléndez * @author Stephane Nicoll * @author Vedran Pavic */ @Configuration @ConditionalOnClass({ RedisTemplate.class, RedisOperationsSessionRepository.class }) @ConditionalOnMissingBean(SessionRepository.class) @ConditionalOnBean(RedisConnectionFactory.class) @Conditional(SessionCondition.class) @EnableConfigurationProperties(RedisSessionProperties.class) class RedisSessionConfiguration { @Configuration public static class SpringBootRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration { private SessionProperties sessionProperties; @Autowired public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties) { this.sessionProperties = sessionProperties; Integer timeout = this.sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds(timeout); } setRedisNamespace(redisSessionProperties.getNamespace()); setRedisFlushMode(redisSessionProperties.getFlushMode()); } } }
bbrouwer/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java
Java
apache-2.0
2,669
/* * 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.samza.operators.spec; import java.util.Collection; /** * Spec for stateful operators. */ public interface StatefulOperatorSpec { /** * Get the store descriptors for stores required by this operator. * * @return store descriptors for this operator's stores */ Collection<StoreDescriptor> getStoreDescriptors(); }
fredji97/samza
samza-core/src/main/java/org/apache/samza/operators/spec/StatefulOperatorSpec.java
Java
apache-2.0
1,163
/* * 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.accumulo.core.client.lexicoder; /** * An encoder represents a typed object that can be encoded/decoded to/from a byte array. * * @since 1.6.0 */ public interface Encoder<T> { byte[] encode(T object); T decode(byte[] bytes) throws IllegalArgumentException; }
milleruntime/accumulo
core/src/main/java/org/apache/accumulo/core/client/lexicoder/Encoder.java
Java
apache-2.0
1,095
package me.kafeitu.activiti.chapter15.leave; import me.kafeitu.activiti.chapter15.leave.ws.LeaveWebService; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * 测试请假流程的Webservice基础功能 * @author: Henry Yan */ public class LeaveWebServiceBusinessTest { /** * 发布并启动WebService */ @Before public void before() { LeaveWebserviceUtil.startServer(); } /** * 需要总经理审批 * @throws ParseException */ @Test public void testTrue() throws ParseException, MalformedURLException { /* // CXF方式 JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create();*/ // 标准方式 URL url = new URL(LeaveWebserviceUtil.WEBSERVICE_WSDL_URL); QName qname = new QName(LeaveWebserviceUtil.WEBSERVICE_URI, "LeaveWebService"); Service service = Service.create(url, qname); LeaveWebService leaveWebService = service.getPort(LeaveWebService.class); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-05 17:30"); assertTrue(audit); } /** * 不需要总经理审批 * @throws ParseException */ @Test public void testFalse() throws ParseException { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create(); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-04 17:30"); assertFalse(audit); } @After public void after() { LeaveWebserviceUtil.stopServer(); } }
kutala/activiti-in-action-codes
bpmn20-example/src/test/java/me/kafeitu/activiti/chapter15/leave/LeaveWebServiceBusinessTest.java
Java
apache-2.0
2,672
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.catalog.springboot; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.CatalogHelper; import org.apache.camel.catalog.RuntimeProvider; /** * A Spring Boot based {@link RuntimeProvider} which only includes the supported Camel components, data formats, and languages * which can be installed in Spring Boot using the starter dependencies. */ public class SpringBootRuntimeProvider implements RuntimeProvider { private static final String COMPONENT_DIR = "org/apache/camel/catalog/springboot/components"; private static final String DATAFORMAT_DIR = "org/apache/camel/catalog/springboot/dataformats"; private static final String LANGUAGE_DIR = "org/apache/camel/catalog/springboot/languages"; private static final String OTHER_DIR = "org/apache/camel/catalog/springboot/others"; private static final String COMPONENTS_CATALOG = "org/apache/camel/catalog/springboot/components.properties"; private static final String DATA_FORMATS_CATALOG = "org/apache/camel/catalog/springboot/dataformats.properties"; private static final String LANGUAGE_CATALOG = "org/apache/camel/catalog/springboot/languages.properties"; private static final String OTHER_CATALOG = "org/apache/camel/catalog/springboot/others.properties"; private CamelCatalog camelCatalog; @Override public CamelCatalog getCamelCatalog() { return camelCatalog; } @Override public void setCamelCatalog(CamelCatalog camelCatalog) { this.camelCatalog = camelCatalog; } @Override public String getProviderName() { return "springboot"; } @Override public String getProviderGroupId() { return "org.apache.camel"; } @Override public String getProviderArtifactId() { return "camel-catalog-provider-springboot"; } @Override public String getComponentJSonSchemaDirectory() { return COMPONENT_DIR; } @Override public String getDataFormatJSonSchemaDirectory() { return DATAFORMAT_DIR; } @Override public String getLanguageJSonSchemaDirectory() { return LANGUAGE_DIR; } @Override public String getOtherJSonSchemaDirectory() { return OTHER_DIR; } @Override public List<String> findComponentNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(COMPONENTS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findDataFormatNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(DATA_FORMATS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findLanguageNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(LANGUAGE_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findOtherNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(OTHER_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } }
onders86/camel
platforms/camel-catalog-provider-springboot/src/main/java/org/apache/camel/catalog/springboot/SpringBootRuntimeProvider.java
Java
apache-2.0
4,859
/* * 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.hive.metastore.events; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.hive.metastore.IHMSHandler; import org.apache.hadoop.hive.metastore.api.Database; /** * Database read event */ @InterfaceAudience.Public @InterfaceStability.Stable public class PreReadDatabaseEvent extends PreEventContext { private final Database db; public PreReadDatabaseEvent(Database db, IHMSHandler handler) { super(PreEventType.READ_DATABASE, handler); this.db = db; } /** * @return the db */ public Database getDatabase() { return db; } }
alanfgates/hive
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/events/PreReadDatabaseEvent.java
Java
apache-2.0
1,483
package org.keycloak.example.oauth; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.logging.Logger; import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.AdapterUtils; import org.keycloak.servlet.ServletOAuthClient; import org.keycloak.util.JsonSerialization; import org.keycloak.util.UriUtils; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @version $Revision: 1 $ */ @ApplicationScoped @Named("databaseClient") public class DatabaseClient { @Inject @ServletRequestQualifier private HttpServletRequest request; @Inject private HttpServletResponse response; @Inject private FacesContext facesContext; @Inject private ServletOAuthClient oauthClient; @Inject private UserData userData; private static final Logger logger = Logger.getLogger(DatabaseClient.class); public void retrieveAccessToken() { try { oauthClient.redirectRelative("client.jsf", request, response); } catch (IOException e) { throw new RuntimeException(e); } } static class TypedList extends ArrayList<String> {} public void sendCustomersRequest() { List<String> customers = sendRequestToDBApplication(getBaseUrl() + "/database/customers"); userData.setCustomers(customers); } public void sendProductsRequest() { List<String> products = sendRequestToDBApplication(getBaseUrl() + "/database/products"); userData.setProducts(products); } protected List<String> sendRequestToDBApplication(String dbUri) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(dbUri); try { if (userData.isHasAccessToken()) { get.addHeader("Authorization", "Bearer " + userData.getAccessToken()); } HttpResponse response = client.execute(get); switch (response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } case 401: facesContext.addMessage(null, new FacesMessage("Status: 401. Request not authenticated! You need to retrieve access token first.")); break; case 403: facesContext.addMessage(null, new FacesMessage("Status: 403. Access token has insufficient privileges")); break; default: facesContext.addMessage(null, new FacesMessage("Status: " + response.getStatusLine() + ". Not able to retrieve data. See log for details")); logger.warn("Error occured. Status: " + response.getStatusLine()); } return null; } catch (IOException e) { e.printStackTrace(); facesContext.addMessage(null, new FacesMessage("Unknown error. See log for details")); return null; } } public String getBaseUrl() { KeycloakSecurityContext session = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName()); return AdapterUtils.getOriginForRestCalls(request.getRequestURL().toString(), session); } }
eugene-chow/keycloak
examples/demo-template/third-party-cdi/src/main/java/org/keycloak/example/oauth/DatabaseClient.java
Java
apache-2.0
4,047
/** * 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.hive.ql.optimizer.stats.annotation; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx; import org.apache.hadoop.hive.ql.parse.ParseContext; import org.apache.hadoop.hive.ql.plan.Statistics; public class AnnotateStatsProcCtx implements NodeProcessorCtx { private ParseContext pctx; private HiveConf conf; private Statistics andExprStats = null; public AnnotateStatsProcCtx(ParseContext pctx) { this.setParseContext(pctx); if(pctx != null) { this.setConf(pctx.getConf()); } else { this.setConf(null); } } public HiveConf getConf() { return conf; } public void setConf(HiveConf conf) { this.conf = conf; } public ParseContext getParseContext() { return pctx; } public void setParseContext(ParseContext pctx) { this.pctx = pctx; } public Statistics getAndExprStats() { return andExprStats; } public void setAndExprStats(Statistics andExprStats) { this.andExprStats = andExprStats; } }
cschenyuan/hive-hack
ql/src/java/org/apache/hadoop/hive/ql/optimizer/stats/annotation/AnnotateStatsProcCtx.java
Java
apache-2.0
1,861
/* 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.flex.forks.batik.svggen; import java.awt.Composite; import java.awt.Paint; import java.awt.Rectangle; import java.awt.image.BufferedImageOp; /** * The ExtensionHandler interface allows the user to handle * Java 2D API extensions that map to SVG concepts (such as custom * Paints, Composites or BufferedImageOp filters). * * @author <a href="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a> * @version $Id: ExtensionHandler.java 478176 2006-11-22 14:50:50Z dvholten $ */ public interface ExtensionHandler { /** * @param paint Custom Paint to be converted to SVG * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGPaintDescriptor */ SVGPaintDescriptor handlePaint(Paint paint, SVGGeneratorContext generatorContext); /** * @param composite Custom Composite to be converted to SVG. * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGCompositeDescriptor which contains a valid SVG filter, * or null if the composite cannot be handled * */ SVGCompositeDescriptor handleComposite(Composite composite, SVGGeneratorContext generatorContext); /** * @param filter Custom filter to be converted to SVG. * @param filterRect Rectangle, in device space, that defines the area * to which filtering applies. May be null, meaning that the * area is undefined. * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGFilterDescriptor which contains a valid SVG filter, * or null if the composite cannot be handled */ SVGFilterDescriptor handleFilter(BufferedImageOp filter, Rectangle filterRect, SVGGeneratorContext generatorContext); }
adufilie/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/svggen/ExtensionHandler.java
Java
apache-2.0
2,772
package org.bouncycastle.crypto.test; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Vector; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.NaccacheSternEngine; import org.bouncycastle.crypto.generators.NaccacheSternKeyPairGenerator; import org.bouncycastle.crypto.params.NaccacheSternKeyGenerationParameters; import org.bouncycastle.crypto.params.NaccacheSternKeyParameters; import org.bouncycastle.crypto.params.NaccacheSternPrivateKeyParameters; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test case for NaccacheStern cipher. For details on this cipher, please see * * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf * * Performs the following tests: * <ul> * <li> Toy example from the NaccacheSternPaper </li> * <li> 768 bit test with text "Now is the time for all good men." (ripped from RSA test) and * the same test with the first byte replaced by 0xFF </li> * <li> 1024 bit test analog to 768 bit test </li> * </ul> */ public class NaccacheSternTest extends SimpleTest { static final boolean debug = false; static final NaccacheSternEngine cryptEng = new NaccacheSternEngine(); static final NaccacheSternEngine decryptEng = new NaccacheSternEngine(); static { cryptEng.setDebug(debug); decryptEng.setDebug(debug); } // Values from NaccacheStern paper static final BigInteger a = BigInteger.valueOf(101); static final BigInteger u1 = BigInteger.valueOf(3); static final BigInteger u2 = BigInteger.valueOf(5); static final BigInteger u3 = BigInteger.valueOf(7); static final BigInteger b = BigInteger.valueOf(191); static final BigInteger v1 = BigInteger.valueOf(11); static final BigInteger v2 = BigInteger.valueOf(13); static final BigInteger v3 = BigInteger.valueOf(17); static final BigInteger ONE = BigInteger.valueOf(1); static final BigInteger TWO = BigInteger.valueOf(2); static final BigInteger sigma = u1.multiply(u2).multiply(u3).multiply(v1) .multiply(v2).multiply(v3); static final BigInteger p = TWO.multiply(a).multiply(u1).multiply(u2) .multiply(u3).add(ONE); static final BigInteger q = TWO.multiply(b).multiply(v1).multiply(v2) .multiply(v3).add(ONE); static final BigInteger n = p.multiply(q); static final BigInteger phi_n = p.subtract(ONE).multiply(q.subtract(ONE)); static final BigInteger g = BigInteger.valueOf(131); static final Vector smallPrimes = new Vector(); // static final BigInteger paperTest = BigInteger.valueOf(202); static final String input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; static final BigInteger paperTest = BigInteger.valueOf(202); // // to check that we handling byte extension by big number correctly. // static final String edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; public String getName() { return "NaccacheStern"; } public void performTest() { // Test with given key from NaccacheSternPaper (totally insecure) // First the Parameters from the NaccacheStern Paper // (see http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf ) smallPrimes.addElement(u1); smallPrimes.addElement(u2); smallPrimes.addElement(u3); smallPrimes.addElement(v1); smallPrimes.addElement(v2); smallPrimes.addElement(v3); NaccacheSternKeyParameters pubParameters = new NaccacheSternKeyParameters(false, g, n, sigma.bitLength()); NaccacheSternPrivateKeyParameters privParameters = new NaccacheSternPrivateKeyParameters(g, n, sigma.bitLength(), smallPrimes, phi_n); AsymmetricCipherKeyPair pair = new AsymmetricCipherKeyPair(pubParameters, privParameters); // Initialize Engines with KeyPair if (debug) { System.out.println("initializing encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing decryption engine"); } decryptEng.init(false, pair.getPrivate()); byte[] data = paperTest.toByteArray(); if (!new BigInteger(data).equals(new BigInteger(enDeCrypt(data)))) { fail("failed NaccacheStern paper test"); } // // key generation test // // // 768 Bit test // if (debug) { System.out.println(); System.out.println("768 Bit TEST"); } // specify key generation parameters NaccacheSternKeyGenerationParameters genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 768, 8, 30, debug); // Initialize Key generator and generate key pair NaccacheSternKeyPairGenerator pGen = new NaccacheSternKeyPairGenerator(); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() < 768) { System.out.println("FAILED: key size is <786 bit, exactly " + ((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() + " bit"); fail("failed key generation (768) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } // // 1024 Bit Test // /* if (debug) { System.out.println(); System.out.println("1024 Bit TEST"); } // specify key generation parameters genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 1024, 8, 40); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() < 1024) { if (debug) { System.out.println("FAILED: key size is <1024 bit, exactly " + ((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() + " bit"); } fail("failed key generation (1024) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); if (debug) { System.out.println("Data is " + new BigInteger(1, data)); } // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } */ // END OF TEST CASE try { new NaccacheSternEngine().processBlock(new byte[]{ 1 }, 0, 1); fail("failed initialisation check"); } catch (IllegalStateException e) { // expected } catch (InvalidCipherTextException e) { fail("failed initialisation check"); } if (debug) { System.out.println("All tests successful"); } } private byte[] enDeCrypt(byte[] input) { // create work array byte[] data = new byte[input.length]; System.arraycopy(input, 0, data, 0, data.length); // Perform encryption like in the paper from Naccache-Stern if (debug) { System.out.println("encrypting data. Data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = cryptEng.processData(data); } catch (InvalidCipherTextException e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("enrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = decryptEng.processData(data); } catch (InvalidCipherTextException e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("decrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } return data; } public static void main(String[] args) { runTest(new NaccacheSternTest()); } }
sake/bouncycastle-java
test/src/org/bouncycastle/crypto/test/NaccacheSternTest.java
Java
mit
11,131
package aima.core.probability.util; import java.util.HashSet; import java.util.Map; import java.util.Set; import aima.core.probability.RandomVariable; import aima.core.probability.domain.Domain; import aima.core.probability.proposition.TermProposition; /** * Default implementation of the RandomVariable interface. * * Note: Also implements the TermProposition interface so its easy to use * RandomVariables in conjunction with propositions about them in the * Probability Model APIs. * * @author Ciaran O'Reilly */ public class RandVar implements RandomVariable, TermProposition { private String name = null; private Domain domain = null; private Set<RandomVariable> scope = new HashSet<RandomVariable>(); public RandVar(String name, Domain domain) { ProbUtil.checkValidRandomVariableName(name); if (null == domain) { throw new IllegalArgumentException( "Domain of RandomVariable must be specified."); } this.name = name; this.domain = domain; this.scope.add(this); } // // START-RandomVariable @Override public String getName() { return name; } @Override public Domain getDomain() { return domain; } // END-RandomVariable // // // START-TermProposition @Override public RandomVariable getTermVariable() { return this; } @Override public Set<RandomVariable> getScope() { return scope; } @Override public Set<RandomVariable> getUnboundScope() { return scope; } @Override public boolean holds(Map<RandomVariable, Object> possibleWorld) { return possibleWorld.containsKey(getTermVariable()); } // END-TermProposition // @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof RandomVariable)) { return false; } // The name (not the name:domain combination) uniquely identifies a // Random Variable RandomVariable other = (RandomVariable) o; return this.name.equals(other.getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return getName(); } }
aima-java/aima-java
aima-core/src/main/java/aima/core/probability/util/RandVar.java
Java
mit
2,171
package aima.core.probability.bayes.exact; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import aima.core.probability.CategoricalDistribution; import aima.core.probability.Factor; import aima.core.probability.RandomVariable; import aima.core.probability.bayes.BayesInference; import aima.core.probability.bayes.BayesianNetwork; import aima.core.probability.bayes.FiniteNode; import aima.core.probability.bayes.Node; import aima.core.probability.proposition.AssignmentProposition; import aima.core.probability.util.ProbabilityTable; /** * Artificial Intelligence A Modern Approach (3rd Edition): Figure 14.11, page * 528.<br> * <br> * * <pre> * function ELIMINATION-ASK(X, e, bn) returns a distribution over X * inputs: X, the query variable * e, observed values for variables E * bn, a Bayesian network specifying joint distribution P(X<sub>1</sub>, ..., X<sub>n</sub>) * * factors <- [] * for each var in ORDER(bn.VARS) do * factors <- [MAKE-FACTOR(var, e) | factors] * if var is hidden variable the factors <- SUM-OUT(var, factors) * return NORMALIZE(POINTWISE-PRODUCT(factors)) * </pre> * * Figure 14.11 The variable elimination algorithm for inference in Bayesian * networks. <br> * <br> * <b>Note:</b> The implementation has been extended to handle queries with * multiple variables. <br> * * @author Ciaran O'Reilly */ public class EliminationAsk implements BayesInference { // private static final ProbabilityTable _identity = new ProbabilityTable( new double[] { 1.0 }); public EliminationAsk() { } // function ELIMINATION-ASK(X, e, bn) returns a distribution over X /** * The ELIMINATION-ASK algorithm in Figure 14.11. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @return a distribution over the query variables. */ public CategoricalDistribution eliminationAsk(final RandomVariable[] X, final AssignmentProposition[] e, final BayesianNetwork bn) { Set<RandomVariable> hidden = new HashSet<RandomVariable>(); List<RandomVariable> VARS = new ArrayList<RandomVariable>(); calculateVariables(X, e, bn, hidden, VARS); // factors <- [] List<Factor> factors = new ArrayList<Factor>(); // for each var in ORDER(bn.VARS) do for (RandomVariable var : order(bn, VARS)) { // factors <- [MAKE-FACTOR(var, e) | factors] factors.add(0, makeFactor(var, e, bn)); // if var is hidden variable then factors <- SUM-OUT(var, factors) if (hidden.contains(var)) { factors = sumOut(var, factors, bn); } } // return NORMALIZE(POINTWISE-PRODUCT(factors)) Factor product = pointwiseProduct(factors); // Note: Want to ensure the order of the product matches the // query variables return ((ProbabilityTable) product.pointwiseProductPOS(_identity, X)) .normalize(); } // // START-BayesInference public CategoricalDistribution ask(final RandomVariable[] X, final AssignmentProposition[] observedEvidence, final BayesianNetwork bn) { return this.eliminationAsk(X, observedEvidence, bn); } // END-BayesInference // // // PROTECTED METHODS // /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. Calculate the hidden variables from the * Bayesian Network. The default implementation does not perform any of * these.<br> * <br> * Two calcuations to be performed here in order to optimize iteration over * the Bayesian Network:<br> * 1. Calculate the hidden variables to be enumerated over. An optimization * (AIMA3e pg. 528) is to remove 'every variable that is not an ancestor of * a query variable or evidence variable as it is irrelevant to the query' * (i.e. sums to 1). 2. The subset of variables from the Bayesian Network to * be retained after irrelevant hidden variables have been removed. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @param hidden * to be populated with the relevant hidden variables Y. * @param bnVARS * to be populated with the subset of the random variables * comprising the Bayesian Network with any irrelevant hidden * variables removed. */ protected void calculateVariables(final RandomVariable[] X, final AssignmentProposition[] e, final BayesianNetwork bn, Set<RandomVariable> hidden, Collection<RandomVariable> bnVARS) { bnVARS.addAll(bn.getVariablesInTopologicalOrder()); hidden.addAll(bnVARS); for (RandomVariable x : X) { hidden.remove(x); } for (AssignmentProposition ap : e) { hidden.removeAll(ap.getScope()); } return; } /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. The default implementation does not * perform any of these.<br> * * @param bn * the Bayesian Network over which the query is being made. Note, * is necessary to provide this in order to be able to determine * the dependencies between variables. * @param vars * a subset of the RandomVariables making up the Bayesian * Network, with any irrelevant hidden variables alreay removed. * @return a possibly opimal ordering for the random variables to be * iterated over by the algorithm. For example, one fairly effective * ordering is a greedy one: eliminate whichever variable minimizes * the size of the next factor to be constructed. */ protected List<RandomVariable> order(BayesianNetwork bn, Collection<RandomVariable> vars) { // Note: Trivial Approach: // For simplicity just return in the reverse order received, // i.e. received will be the default topological order for // the Bayesian Network and we want to ensure the network // is iterated from bottom up to ensure when hidden variables // are come across all the factors dependent on them have // been seen so far. List<RandomVariable> order = new ArrayList<RandomVariable>(vars); Collections.reverse(order); return order; } // // PRIVATE METHODS // private Factor makeFactor(RandomVariable var, AssignmentProposition[] e, BayesianNetwork bn) { Node n = bn.getNode(var); if (!(n instanceof FiniteNode)) { throw new IllegalArgumentException( "Elimination-Ask only works with finite Nodes."); } FiniteNode fn = (FiniteNode) n; List<AssignmentProposition> evidence = new ArrayList<AssignmentProposition>(); for (AssignmentProposition ap : e) { if (fn.getCPT().contains(ap.getTermVariable())) { evidence.add(ap); } } return fn.getCPT().getFactorFor( evidence.toArray(new AssignmentProposition[evidence.size()])); } private List<Factor> sumOut(RandomVariable var, List<Factor> factors, BayesianNetwork bn) { List<Factor> summedOutFactors = new ArrayList<Factor>(); List<Factor> toMultiply = new ArrayList<Factor>(); for (Factor f : factors) { if (f.contains(var)) { toMultiply.add(f); } else { // This factor does not contain the variable // so no need to sum out - see AIMA3e pg. 527. summedOutFactors.add(f); } } summedOutFactors.add(pointwiseProduct(toMultiply).sumOut(var)); return summedOutFactors; } private Factor pointwiseProduct(List<Factor> factors) { Factor product = factors.get(0); for (int i = 1; i < factors.size(); i++) { product = product.pointwiseProduct(factors.get(i)); } return product; } }
aima-java/aima-java
aima-core/src/main/java/aima/core/probability/bayes/exact/EliminationAsk.java
Java
mit
8,132
/** * A network library for processing which supports UDP, TCP and Multicast. * * (c) 2004-2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @author Andreas Schlegel http://www.sojamo.de/libraries/oscP5 * @modified 12/19/2011 * @version 0.9.8 */ package netP5; import java.net.DatagramPacket; import java.util.Vector; /** * * @author andreas schlegel * */ public class UdpServer extends AbstractUdpServer implements UdpPacketListener { protected Object _myParent; protected NetPlug _myNetPlug; /** * new UDP server. * by default the buffersize of a udp packet is 1536 bytes. you can set * your own individual buffersize with the third parameter int in the constructor. * @param theObject Object * @param thePort int * @param theBufferSize int */ public UdpServer( final Object theObject, final int thePort, final int theBufferSize) { super(null, thePort, theBufferSize); _myParent = theObject; _myListener = this; _myNetPlug = new NetPlug(_myParent); start(); } public UdpServer( final Object theObject, final int thePort) { super(null, thePort, 1536); _myParent = theObject; _myListener = this; _myNetPlug = new NetPlug(_myParent); start(); } /** * @invisible * @param theListener * @param thePort * @param theBufferSize */ public UdpServer( final UdpPacketListener theListener, final int thePort, final int theBufferSize) { super(theListener, thePort, theBufferSize); } /** * @invisible * @param theListener * @param theAddress * @param thePort * @param theBufferSize */ protected UdpServer( final UdpPacketListener theListener, final String theAddress, final int thePort, final int theBufferSize) { super(theListener, theAddress, thePort, theBufferSize); } /** * @invisible * @param thePacket DatagramPacket * @param thePort int */ public void process(DatagramPacket thePacket, int thePort) { _myNetPlug.process(thePacket,thePort); } /** * add a listener to the udp server. each incoming packet will be forwarded * to the listener. * @param theListener * @related NetListener */ public void addListener(NetListener theListener) { _myNetPlug.addListener(theListener); } /** * * @param theListener * @related NetListener */ public void removeListener(NetListener theListener) { _myNetPlug.removeListener(theListener); } /** * * @param theIndex * @related NetListener * @return */ public NetListener getListener(int theIndex) { return _myNetPlug.getListener(theIndex); } /** * @related NetListener * @return */ public Vector getListeners() { return _myNetPlug.getListeners(); } }
Avnerus/pulse-midburn
oscP5/src/netP5/UdpServer.java
Java
mit
3,640
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.innogysmarthome.internal.listener; import org.openhab.binding.innogysmarthome.internal.InnogyWebSocket; /** * The {@link EventListener} is called by the {@link InnogyWebSocket} on new Events and if the {@link InnogyWebSocket} * closed the connection. * * @author Oliver Kuhl - Initial contribution */ public interface EventListener { /** * This method is called, whenever a new event comes from the innogy service (like a device change for example). * * @param msg */ public void onEvent(String msg); /** * This method is called, when the evenRunner stops abnormally (statuscode <> 1000). */ public void connectionClosed(); }
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.innogysmarthome/src/main/java/org/openhab/binding/innogysmarthome/internal/listener/EventListener.java
Java
epl-1.0
1,030
/* * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.jtt.optimize; import org.junit.Test; import org.graalvm.compiler.jtt.JTTTest; /* * Test case for local load elimination. It makes sure that the second field store is not eliminated, because * it is recognized that the first store changes the field "field1", so it is no longer guaranteed that it * has its default value 0. */ public class LLE_01 extends JTTTest { private static class TestClass { int field1; } public static int test() { TestClass o = new TestClass(); o.field1 = 1; o.field1 = 0; return o.field1; } @Test public void run0() throws Throwable { runTest("test"); } }
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/LLE_01.java
Java
gpl-2.0
1,754
/* * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.hotspot.replacements; import java.lang.reflect.Method; import java.util.EnumMap; import org.graalvm.compiler.api.directives.GraalDirectives; import org.graalvm.compiler.api.replacements.Snippet; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.hotspot.replacements.arraycopy.ArrayCopyCallNode; import org.graalvm.compiler.nodes.java.DynamicNewArrayNode; import org.graalvm.compiler.nodes.java.NewArrayNode; import org.graalvm.compiler.replacements.Snippets; import jdk.vm.ci.meta.JavaKind; public class ObjectCloneSnippets implements Snippets { public static final EnumMap<JavaKind, Method> arrayCloneMethods = new EnumMap<>(JavaKind.class); static { arrayCloneMethods.put(JavaKind.Boolean, getCloneMethod("booleanArrayClone", boolean[].class)); arrayCloneMethods.put(JavaKind.Byte, getCloneMethod("byteArrayClone", byte[].class)); arrayCloneMethods.put(JavaKind.Char, getCloneMethod("charArrayClone", char[].class)); arrayCloneMethods.put(JavaKind.Short, getCloneMethod("shortArrayClone", short[].class)); arrayCloneMethods.put(JavaKind.Int, getCloneMethod("intArrayClone", int[].class)); arrayCloneMethods.put(JavaKind.Float, getCloneMethod("floatArrayClone", float[].class)); arrayCloneMethods.put(JavaKind.Long, getCloneMethod("longArrayClone", long[].class)); arrayCloneMethods.put(JavaKind.Double, getCloneMethod("doubleArrayClone", double[].class)); arrayCloneMethods.put(JavaKind.Object, getCloneMethod("objectArrayClone", Object[].class)); } private static Method getCloneMethod(String name, Class<?> param) { try { return ObjectCloneSnippets.class.getDeclaredMethod(name, param); } catch (SecurityException | NoSuchMethodException e) { throw new GraalError(e); } } @Snippet public static boolean[] booleanArrayClone(boolean[] src) { boolean[] result = (boolean[]) NewArrayNode.newUninitializedArray(Boolean.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Boolean); return result; } @Snippet public static byte[] byteArrayClone(byte[] src) { byte[] result = (byte[]) NewArrayNode.newUninitializedArray(Byte.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Byte); return result; } @Snippet public static short[] shortArrayClone(short[] src) { short[] result = (short[]) NewArrayNode.newUninitializedArray(Short.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Short); return result; } @Snippet public static char[] charArrayClone(char[] src) { char[] result = (char[]) NewArrayNode.newUninitializedArray(Character.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Char); return result; } @Snippet public static int[] intArrayClone(int[] src) { int[] result = (int[]) NewArrayNode.newUninitializedArray(Integer.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Int); return result; } @Snippet public static float[] floatArrayClone(float[] src) { float[] result = (float[]) NewArrayNode.newUninitializedArray(Float.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Float); return result; } @Snippet public static long[] longArrayClone(long[] src) { long[] result = (long[]) NewArrayNode.newUninitializedArray(Long.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Long); return result; } @Snippet public static double[] doubleArrayClone(double[] src) { double[] result = (double[]) NewArrayNode.newUninitializedArray(Double.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Double); return result; } @Snippet public static Object[] objectArrayClone(Object[] src) { /* Since this snippet is lowered early the array must be initialized */ Object[] result = (Object[]) DynamicNewArrayNode.newArray(GraalDirectives.guardingNonNull(src.getClass().getComponentType()), src.length, JavaKind.Object); ArrayCopyCallNode.disjointUninitializedArraycopy(src, 0, result, 0, src.length, JavaKind.Object); return result; } }
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/replacements/ObjectCloneSnippets.java
Java
gpl-2.0
5,679
package org.zarroboogs.weibo.dao; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.zarroboogs.util.net.HttpUtility; import org.zarroboogs.util.net.WeiboException; import org.zarroboogs.util.net.HttpUtility.HttpMethod; import org.zarroboogs.utils.ImageUtility; import org.zarroboogs.utils.WeiBoURLs; import org.zarroboogs.utils.file.FileLocationMethod; import org.zarroboogs.utils.file.FileManager; import org.zarroboogs.weibo.support.asyncdrawable.TaskCache; import android.graphics.Bitmap; import android.text.TextUtils; import java.util.HashMap; import java.util.Map; public class MapDao { public Bitmap getMap() throws WeiboException { String url = WeiBoURLs.STATIC_MAP; Map<String, String> map = new HashMap<String, String>(); map.put("access_token", access_token); String coordinates = String.valueOf(lat) + "," + String.valueOf(lan); map.put("center_coordinate", coordinates); map.put("zoom", "14"); map.put("size", "600x380"); String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map); String mapUrl = ""; try { JSONObject jsonObject = new JSONObject(jsonData); JSONArray array = jsonObject.optJSONArray("map"); jsonObject = array.getJSONObject(0); mapUrl = jsonObject.getString("image_url"); } catch (JSONException e) { } if (TextUtils.isEmpty(mapUrl)) { return null; } String filePath = FileManager.getFilePathFromUrl(mapUrl, FileLocationMethod.map); boolean downloaded = TaskCache.waitForPictureDownload(mapUrl, null, filePath, FileLocationMethod.map); if (!downloaded) { return null; } Bitmap bitmap = ImageUtility.readNormalPic(FileManager.getFilePathFromUrl(mapUrl, FileLocationMethod.map), -1, -1); return bitmap; } public MapDao(String token, double lan, double lat) { this.access_token = token; this.lan = lan; this.lat = lat; } private String access_token; private double lan; private double lat; }
tsdl2013/iBeebo
app/src/main/java/org/zarroboogs/weibo/dao/MapDao.java
Java
gpl-3.0
2,199
package crazypants.enderio.machine.capbank.network; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import cofh.api.energy.IEnergyContainerItem; import crazypants.enderio.EnderIO; import crazypants.enderio.machine.capbank.TileCapBank; public class InventoryImpl implements IInventory { public static boolean isInventoryEmtpy(TileCapBank cap) { for (ItemStack st : cap.getInventory()) { if(st != null) { return false; } } return true; } public static boolean isInventoryEmtpy(ItemStack[] inv) { if(inv == null) { return true; } for (ItemStack st : inv) { if(st != null) { return false; } } return true; } private ItemStack[] inventory; private TileCapBank capBank; public InventoryImpl() { } public TileCapBank getCapBank() { return capBank; } public void setCapBank(TileCapBank cap) { capBank = cap; if(cap == null) { inventory = null; return; } inventory = cap.getInventory(); } public boolean isEmtpy() { return isInventoryEmtpy(inventory); } public ItemStack[] getStacks() { return inventory; } @Override public ItemStack getStackInSlot(int slot) { if(inventory == null) { return null; } if(slot < 0 || slot >= inventory.length) { return null; } return inventory[slot]; } @Override public ItemStack decrStackSize(int fromSlot, int amount) { if(inventory == null) { return null; } if(fromSlot < 0 || fromSlot >= inventory.length) { return null; } ItemStack item = inventory[fromSlot]; if(item == null) { return null; } if(item.stackSize <= amount) { ItemStack result = item.copy(); inventory[fromSlot] = null; return result; } item.stackSize -= amount; return item.copy(); } @Override public void setInventorySlotContents(int slot, ItemStack itemstack) { if(inventory == null) { return; } if(slot < 0 || slot >= inventory.length) { return; } inventory[slot] = itemstack; } @Override public int getSizeInventory() { return 4; } //--- constant values @Override public ItemStack getStackInSlotOnClosing(int p_70304_1_) { return null; } @Override public String getInventoryName() { return EnderIO.blockCapBank.getUnlocalizedName() + ".name"; } @Override public boolean hasCustomInventoryName() { return false; } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isUseableByPlayer(EntityPlayer p_70300_1_) { return true; } @Override public boolean isItemValidForSlot(int slot, ItemStack itemstack) { if(itemstack == null) { return false; } return itemstack.getItem() instanceof IEnergyContainerItem; } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public void markDirty() { } }
Samernieve/EnderIO
src/main/java/crazypants/enderio/machine/capbank/network/InventoryImpl.java
Java
unlicense
3,083
/** * 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.zookeeper.server.quorum; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.apache.jute.InputArchive; import org.apache.jute.OutputArchive; import org.apache.zookeeper.MockPacket; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.proto.ConnectRequest; import org.apache.zookeeper.proto.ReplyHeader; import org.apache.zookeeper.proto.RequestHeader; import org.apache.zookeeper.proto.SetWatches; import org.apache.zookeeper.server.MockNIOServerCnxn; import org.apache.zookeeper.server.NIOServerCnxn; import org.apache.zookeeper.server.NIOServerCnxnFactory; import org.apache.zookeeper.server.MockSelectorThread; import org.apache.zookeeper.server.ZKDatabase; import org.apache.zookeeper.server.ZooTrace; import org.apache.zookeeper.server.persistence.FileTxnSnapLog; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Demonstrate ZOOKEEPER-1382 : Watches leak on expired session */ @RunWith(Parameterized.class) public class WatchLeakTest { protected static final Logger LOG = LoggerFactory .getLogger(WatchLeakTest.class); final long SESSION_ID = 0xBABEL; private final boolean sessionTimedout; public WatchLeakTest(boolean sessionTimedout) { this.sessionTimedout = sessionTimedout; } @Parameters public static Collection<Object[]> configs() { return Arrays.asList(new Object[][] { { false }, { true }, }); } /** * Check that if session has expired then no watch can be set */ @Test public void testWatchesLeak() throws Exception { NIOServerCnxnFactory serverCnxnFactory = mock(NIOServerCnxnFactory.class); final SelectionKey sk = new FakeSK(); MockSelectorThread selectorThread = mock(MockSelectorThread.class); when(selectorThread.addInterestOpsUpdateRequest(any(SelectionKey.class))).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { SelectionKey sk = (SelectionKey)invocation.getArguments()[0]; NIOServerCnxn nioSrvCnx = (NIOServerCnxn)sk.attachment(); sk.interestOps(nioSrvCnx.getInterestOps()); return true; } }); ZKDatabase database = new ZKDatabase(null); database.setlastProcessedZxid(2L); QuorumPeer quorumPeer = mock(QuorumPeer.class); FileTxnSnapLog logfactory = mock(FileTxnSnapLog.class); // Directories are not used but we need it to avoid NPE when(logfactory.getDataDir()).thenReturn(new File("")); when(logfactory.getSnapDir()).thenReturn(new File("")); FollowerZooKeeperServer fzks = null; try { // Create a new follower fzks = new FollowerZooKeeperServer(logfactory, quorumPeer, database); fzks.startup(); fzks.setServerCnxnFactory(serverCnxnFactory); quorumPeer.follower = new MyFollower(quorumPeer, fzks); LOG.info("Follower created"); // Simulate a socket channel between a client and a follower final SocketChannel socketChannel = createClientSocketChannel(); // Create the NIOServerCnxn that will handle the client requests final MockNIOServerCnxn nioCnxn = new MockNIOServerCnxn(fzks, socketChannel, sk, serverCnxnFactory, selectorThread); sk.attach(nioCnxn); // Send the connection request as a client do nioCnxn.doIO(sk); LOG.info("Client connection sent"); // Send the valid or invalid session packet to the follower QuorumPacket qp = createValidateSessionPacketResponse(!sessionTimedout); quorumPeer.follower.processPacket(qp); LOG.info("Session validation sent"); // OK, now the follower knows that the session is valid or invalid, let's try // to send the watches nioCnxn.doIO(sk); // wait for the the request processor to do his job Thread.sleep(1000L); LOG.info("Watches processed"); // If session has not been validated, there must be NO watches int watchCount = database.getDataTree().getWatchCount(); if (sessionTimedout) { // Session has not been re-validated ! LOG.info("session is not valid, watches = {}", watchCount); assertEquals("Session is not valid so there should be no watches", 0, watchCount); } else { // Session has been re-validated LOG.info("session is valid, watches = {}", watchCount); assertEquals("Session is valid so the watch should be there", 1, watchCount); } } finally { if (fzks != null) { fzks.shutdown(); } } } /** * A follower with no real leader connection */ public static class MyFollower extends Follower { /** * Create a follower with a mocked leader connection * * @param self * @param zk */ MyFollower(QuorumPeer self, FollowerZooKeeperServer zk) { super(self, zk); leaderOs = mock(OutputArchive.class); leaderIs = mock(InputArchive.class); bufferedOutput = mock(BufferedOutputStream.class); } } /** * Simulate the behavior of a real selection key */ private static class FakeSK extends SelectionKey { @Override public SelectableChannel channel() { return null; } @Override public Selector selector() { return mock(Selector.class); } @Override public boolean isValid() { return true; } @Override public void cancel() { } @Override public int interestOps() { return ops; } private int ops = OP_WRITE + OP_READ; @Override public SelectionKey interestOps(int ops) { this.ops = ops; return this; } @Override public int readyOps() { boolean reading = (ops & OP_READ) != 0; boolean writing = (ops & OP_WRITE) != 0; if (reading && writing) { LOG.info("Channel is ready for reading and writing"); } else if (reading) { LOG.info("Channel is ready for reading only"); } else if (writing) { LOG.info("Channel is ready for writing only"); } return ops; } } /** * Create a watches message with a single watch on / * * @return a message that attempts to set 1 watch on / */ private ByteBuffer createWatchesMessage() { List<String> dataWatches = new ArrayList<String>(1); dataWatches.add("/"); List<String> existWatches = Collections.emptyList(); List<String> childWatches = Collections.emptyList(); SetWatches sw = new SetWatches(1L, dataWatches, existWatches, childWatches); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.setWatches); h.setXid(-8); MockPacket p = new MockPacket(h, new ReplyHeader(), sw, null, null); return p.createAndReturnBB(); } /** * This is the secret that we use to generate passwords, for the moment it * is more of a sanity check. */ static final private long superSecret = 0XB3415C00L; /** * Create a connection request * * @return a serialized connection request */ private ByteBuffer createConnRequest() { Random r = new Random(SESSION_ID ^ superSecret); byte p[] = new byte[16]; r.nextBytes(p); ConnectRequest conReq = new ConnectRequest(0, 1L, 30000, SESSION_ID, p); MockPacket packet = new MockPacket(null, null, conReq, null, null, false); return packet.createAndReturnBB(); } /** * Mock a client channel with a connection request and a watches message * inside. * * @return a socket channel * @throws IOException */ private SocketChannel createClientSocketChannel() throws IOException { SocketChannel socketChannel = mock(SocketChannel.class); Socket socket = mock(Socket.class); InetSocketAddress socketAddress = new InetSocketAddress(1234); when(socket.getRemoteSocketAddress()).thenReturn(socketAddress); when(socketChannel.socket()).thenReturn(socket); // Send watches packet to server connection final ByteBuffer connRequest = createConnRequest(); final ByteBuffer watchesMessage = createWatchesMessage(); final ByteBuffer request = ByteBuffer.allocate(connRequest.limit() + watchesMessage.limit()); request.put(connRequest); request.put(watchesMessage); Answer<Integer> answer = new Answer<Integer>() { int i = 0; @Override public Integer answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); ByteBuffer bb = (ByteBuffer) args[0]; for (int k = 0; k < bb.limit(); k++) { bb.put(request.get(i)); i = i + 1; } return bb.limit(); } }; when(socketChannel.read(any(ByteBuffer.class))).thenAnswer(answer); return socketChannel; } /** * Forge an invalid session packet as a LEADER do * * @param valid <code>true</code> to create a valid session message * * @throws Exception */ private QuorumPacket createValidateSessionPacketResponse(boolean valid) throws Exception { QuorumPacket qp = createValidateSessionPacket(); ByteArrayInputStream bis = new ByteArrayInputStream(qp.getData()); DataInputStream dis = new DataInputStream(bis); long id = dis.readLong(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeLong(id); // false means that the session has expired dos.writeBoolean(valid); qp.setData(bos.toByteArray()); return qp; } /** * Forge an validate session packet as a LEARNER do * * @return * @throws Exception */ private QuorumPacket createValidateSessionPacket() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(SESSION_ID); dos.writeInt(3000); dos.close(); QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1, baos.toByteArray(), null); return qp; } }
bit1129/open-source-projects
src/java/test/org/apache/zookeeper/server/quorum/WatchLeakTest.java
Java
apache-2.0
12,847
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.cli.command.shell; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import org.springframework.boot.cli.command.AbstractCommand; import org.springframework.boot.cli.command.Command; import org.springframework.boot.cli.command.status.ExitStatus; import org.springframework.boot.loader.tools.RunProcess; import org.springframework.util.StringUtils; /** * Special {@link Command} used to run a process from the shell. NOTE: this command is not * directly installed into the shell. * * @author Phillip Webb */ class RunProcessCommand extends AbstractCommand { private final String[] command; private volatile RunProcess process; RunProcessCommand(String... command) { super(null, null); this.command = command; } @Override public ExitStatus run(String... args) throws Exception { return run(Arrays.asList(args)); } protected ExitStatus run(Collection<String> args) throws IOException { this.process = new RunProcess(this.command); int code = this.process.run(true, StringUtils.toStringArray(args)); if (code == 0) { return ExitStatus.OK; } else { return new ExitStatus(code, "EXTERNAL_ERROR"); } } public boolean handleSigInt() { return this.process.handleSigInt(); } }
hello2009chen/spring-boot
spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/RunProcessCommand.java
Java
apache-2.0
1,906
/** * This class is generated by jOOQ */ package io.cattle.platform.core.model.tables; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.0" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class AgentTable extends org.jooq.impl.TableImpl<io.cattle.platform.core.model.tables.records.AgentRecord> { private static final long serialVersionUID = -328097319; /** * The singleton instance of <code>cattle.agent</code> */ public static final io.cattle.platform.core.model.tables.AgentTable AGENT = new io.cattle.platform.core.model.tables.AgentTable(); /** * The class holding records for this type */ @Override public java.lang.Class<io.cattle.platform.core.model.tables.records.AgentRecord> getRecordType() { return io.cattle.platform.core.model.tables.records.AgentRecord.class; } /** * The column <code>cattle.agent.id</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>cattle.agent.name</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>cattle.agent.account_id</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ACCOUNT_ID = createField("account_id", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * The column <code>cattle.agent.kind</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> KIND = createField("kind", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>cattle.agent.uuid</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> UUID = createField("uuid", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, ""); /** * The column <code>cattle.agent.description</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(1024), this, ""); /** * The column <code>cattle.agent.state</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> STATE = createField("state", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, ""); /** * The column <code>cattle.agent.created</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, ""); /** * The column <code>cattle.agent.removed</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> REMOVED = createField("removed", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, ""); /** * The column <code>cattle.agent.remove_time</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> REMOVE_TIME = createField("remove_time", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, ""); /** * The column <code>cattle.agent.data</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Map<String,Object>> DATA = createField("data", org.jooq.impl.SQLDataType.CLOB.length(16777215).asConvertedDataType(new io.cattle.platform.db.jooq.converter.DataConverter()), this, ""); /** * The column <code>cattle.agent.uri</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> URI = createField("uri", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>cattle.agent.managed_config</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Boolean> MANAGED_CONFIG = createField("managed_config", org.jooq.impl.SQLDataType.BIT.nullable(false).defaulted(true), this, ""); /** * The column <code>cattle.agent.agent_group_id</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> AGENT_GROUP_ID = createField("agent_group_id", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * The column <code>cattle.agent.zone_id</code>. */ public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ZONE_ID = createField("zone_id", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * Create a <code>cattle.agent</code> table reference */ public AgentTable() { this("agent", null); } /** * Create an aliased <code>cattle.agent</code> table reference */ public AgentTable(java.lang.String alias) { this(alias, io.cattle.platform.core.model.tables.AgentTable.AGENT); } private AgentTable(java.lang.String alias, org.jooq.Table<io.cattle.platform.core.model.tables.records.AgentRecord> aliased) { this(alias, aliased, null); } private AgentTable(java.lang.String alias, org.jooq.Table<io.cattle.platform.core.model.tables.records.AgentRecord> aliased, org.jooq.Field<?>[] parameters) { super(alias, io.cattle.platform.core.model.CattleTable.CATTLE, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public org.jooq.Identity<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> getIdentity() { return io.cattle.platform.core.model.Keys.IDENTITY_AGENT; } /** * {@inheritDoc} */ @Override public org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord> getPrimaryKey() { return io.cattle.platform.core.model.Keys.KEY_AGENT_PRIMARY; } /** * {@inheritDoc} */ @Override public java.util.List<org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord>> getKeys() { return java.util.Arrays.<org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord>>asList(io.cattle.platform.core.model.Keys.KEY_AGENT_PRIMARY, io.cattle.platform.core.model.Keys.KEY_AGENT_IDX_AGENT_UUID); } /** * {@inheritDoc} */ @Override public java.util.List<org.jooq.ForeignKey<io.cattle.platform.core.model.tables.records.AgentRecord, ?>> getReferences() { return java.util.Arrays.<org.jooq.ForeignKey<io.cattle.platform.core.model.tables.records.AgentRecord, ?>>asList(io.cattle.platform.core.model.Keys.FK_AGENT__ACCOUNT_ID, io.cattle.platform.core.model.Keys.FK_AGENT__AGENT_GROUP_ID, io.cattle.platform.core.model.Keys.FK_AGENT__ZONE_ID); } /** * {@inheritDoc} */ @Override public io.cattle.platform.core.model.tables.AgentTable as(java.lang.String alias) { return new io.cattle.platform.core.model.tables.AgentTable(alias, this); } /** * Rename this table */ public io.cattle.platform.core.model.tables.AgentTable rename(java.lang.String name) { return new io.cattle.platform.core.model.tables.AgentTable(name, null); } }
sonchang/cattle
code/iaas/model/src/main/java/io/cattle/platform/core/model/tables/AgentTable.java
Java
apache-2.0
7,604
/* * 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.ml; import com.facebook.presto.operator.scalar.AbstractTestFunctions; import org.testng.annotations.BeforeClass; import static com.facebook.presto.metadata.FunctionExtractor.extractFunctions; abstract class AbstractTestMLFunctions extends AbstractTestFunctions { @BeforeClass protected void registerFunctions() { functionAssertions.getMetadata().registerBuiltInFunctions( extractFunctions(new MLPlugin().getFunctions())); } }
prestodb/presto
presto-ml/src/test/java/com/facebook/presto/ml/AbstractTestMLFunctions.java
Java
apache-2.0
1,068
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.kie.test.objects; public interface Building { public Integer getDoors(); }
droolsjbpm/jbpm
jbpm-services/jbpm-kie-services/src/test/java/org/jbpm/kie/test/objects/Building.java
Java
apache-2.0
720
/* * 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.client.util; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ignite.internal.client.GridClientPredicate; import org.apache.ignite.internal.util.typedef.internal.U; import org.jetbrains.annotations.Nullable; /** * Controls key to node affinity using consistent hash algorithm. This class is thread-safe * and does not have to be externally synchronized. * <p> * For a good explanation of what consistent hashing is, you can refer to * <a href="http://weblogs.java.net/blog/tomwhite/archive/2007/11/consistent_hash.html">Tom White's Blog</a>. */ public class GridClientConsistentHash<N> { /** Prime number. */ private static final int PRIME = 15485857; /** Random generator. */ private static final Random RAND = new Random(); /** Affinity seed. */ private final Object affSeed; /** Map of hash assignments. */ private final NavigableMap<Integer, SortedSet<N>> circle = new TreeMap<>(); /** Read/write lock. */ private final ReadWriteLock rw = new ReentrantReadWriteLock(); /** Distinct nodes in the hash. */ private Collection<N> nodes = new HashSet<>(); /** Nodes comparator to resolve hash codes collisions. */ private Comparator<N> nodesComp; /** * Constructs consistent hash using empty affinity seed and {@code MD5} hasher function. */ public GridClientConsistentHash() { this(null, null); } /** * Constructs consistent hash using given affinity seed and {@code MD5} hasher function. * * @param affSeed Affinity seed (will be used as key prefix for hashing). */ public GridClientConsistentHash(Object affSeed) { this(null, affSeed); } /** * Constructs consistent hash using given affinity seed and hasher function. * * @param nodesComp Nodes comparator to resolve hash codes collisions. * If {@code null} natural order will be used. * @param affSeed Affinity seed (will be used as key prefix for hashing). */ public GridClientConsistentHash(Comparator<N> nodesComp, Object affSeed) { this.nodesComp = nodesComp; this.affSeed = affSeed == null ? new Integer(PRIME) : affSeed; } /** * Adds nodes to consistent hash algorithm (if nodes are {@code null} or empty, then no-op). * * @param nodes Nodes to add. * @param replicas Number of replicas for every node. */ public void addNodes(Collection<N> nodes, int replicas) { if (nodes == null || nodes.isEmpty()) return; rw.writeLock().lock(); try { for (N node : nodes) addNode(node, replicas); } finally { rw.writeLock().unlock(); } } /** * Adds a node to consistent hash algorithm. * * @param node New node (if {@code null} then no-op). * @param replicas Number of replicas for the node. * @return {@code True} if node was added, {@code false} if it is {@code null} or * is already contained in the hash. */ public boolean addNode(N node, int replicas) { if (node == null) return false; long seed = affSeed.hashCode() * 31 + hash(node); rw.writeLock().lock(); try { if (!nodes.add(node)) return false; int hash = hash(seed); SortedSet<N> set = circle.get(hash); if (set == null) circle.put(hash, set = new TreeSet<>(nodesComp)); set.add(node); for (int i = 1; i <= replicas; i++) { seed = seed * affSeed.hashCode() + i; hash = hash(seed); set = circle.get(hash); if (set == null) circle.put(hash, set = new TreeSet<>(nodesComp)); set.add(node); } return true; } finally { rw.writeLock().unlock(); } } /** * Removes a node and all of its replicas. * * @param node Node to remove (if {@code null}, then no-op). * @return {@code True} if node was removed, {@code false} if node is {@code null} or * not present in hash. */ public boolean removeNode(N node) { if (node == null) return false; rw.writeLock().lock(); try { if (!nodes.remove(node)) return false; for (Iterator<SortedSet<N>> it = circle.values().iterator(); it.hasNext();) { SortedSet<N> set = it.next(); if (!set.remove(node)) continue; if (set.isEmpty()) it.remove(); } return true; } finally { rw.writeLock().unlock(); } } /** * Gets number of distinct nodes, excluding replicas, in consistent hash. * * @return Number of distinct nodes, excluding replicas, in consistent hash. */ public int count() { rw.readLock().lock(); try { return nodes.size(); } finally { rw.readLock().unlock(); } } /** * Gets size of all nodes (including replicas) in consistent hash. * * @return Size of all nodes (including replicas) in consistent hash. */ public int size() { rw.readLock().lock(); try { int size = 0; for (SortedSet<N> set : circle.values()) size += set.size(); return size; } finally { rw.readLock().unlock(); } } /** * Checks if consistent hash has nodes added to it. * * @return {@code True} if consistent hash is empty, {@code false} otherwise. */ public boolean isEmpty() { return count() == 0; } /** * Gets set of all distinct nodes in the consistent hash (in no particular order). * * @return Set of all distinct nodes in the consistent hash. */ public Set<N> nodes() { rw.readLock().lock(); try { return new HashSet<>(nodes); } finally { rw.readLock().unlock(); } } /** * Picks a random node from consistent hash. * * @return Random node from consistent hash or {@code null} if there are no nodes. */ public N random() { return node(RAND.nextLong()); } /** * Gets node for a key. * * @param key Key. * @return Node. */ public N node(Object key) { int hash = hash(key); rw.readLock().lock(); try { Map.Entry<Integer, SortedSet<N>> firstEntry = circle.firstEntry(); if (firstEntry == null) return null; Map.Entry<Integer, SortedSet<N>> tailEntry = circle.tailMap(hash, true).firstEntry(); // Get first node hash in the circle clock-wise. return circle.get(tailEntry == null ? firstEntry.getKey() : tailEntry.getKey()).first(); } finally { rw.readLock().unlock(); } } /** * Gets node for a given key. * * @param key Key to get node for. * @param inc Optional inclusion set. Only nodes contained in this set may be returned. * If {@code null}, then all nodes may be included. * @return Node for key, or {@code null} if node was not found. */ public N node(Object key, Collection<N> inc) { return node(key, inc, null); } /** * Gets node for a given key. * * @param key Key to get node for. * @param inc Optional inclusion set. Only nodes contained in this set may be returned. * If {@code null}, then all nodes may be included. * @param exc Optional exclusion set. Only nodes not contained in this set may be returned. * If {@code null}, then all nodes may be returned. * @return Node for key, or {@code null} if node was not found. */ public N node(Object key, @Nullable final Collection<N> inc, @Nullable final Collection<N> exc) { if (inc == null && exc == null) return node(key); return node(key, new GridClientPredicate<N>() { @Override public boolean apply(N n) { return (inc == null || inc.contains(n)) && (exc == null || !exc.contains(n)); } }); } /** * Gets node for a given key. * * @param key Key to get node for. * @param p Optional predicate for node filtering. * @return Node for key, or {@code null} if node was not found. */ public N node(Object key, GridClientPredicate<N>... p) { if (p == null || p.length == 0) return node(key); int hash = hash(key); rw.readLock().lock(); try { final int size = nodes.size(); if (size == 0) return null; Set<N> failed = null; // Move clock-wise starting from selected position 'hash'. for (SortedSet<N> set : circle.tailMap(hash, true).values()) { for (N n : set) { if (failed != null && failed.contains(n)) continue; if (apply(p, n)) return n; if (failed == null) failed = new HashSet<>(); failed.add(n); if (failed.size() == size) return null; } } // // Copy-paste is used to escape several new objects creation. // // Wrap around moving clock-wise from the circle start. for (SortedSet<N> set : circle.headMap(hash, false).values()) { // Circle head. for (N n : set) { if (failed != null && failed.contains(n)) continue; if (apply(p, n)) return n; if (failed == null) failed = U.newHashSet(size); failed.add(n); if (failed.size() == size) return null; } } return null; } finally { rw.readLock().unlock(); } } /** * Apply predicate to the node. * * @param p Predicate. * @param n Node. * @return {@code True} if filter passed or empty. */ private boolean apply(GridClientPredicate<N>[] p, N n) { if (p != null) { for (GridClientPredicate<? super N> r : p) { if (r != null && !r.apply(n)) return false; } } return true; } /** * Gets hash code for a given object. * * @param o Object to get hash code for. * @return Hash code. */ public static int hash(Object o) { int h = o == null ? 0 : o instanceof byte[] ? Arrays.hashCode((byte[])o) : o.hashCode(); // Spread bits to hash code. h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); } /** {@inheritDoc} */ @Override public String toString() { return getClass().getSimpleName() + " [affSeed=" + affSeed + ", circle=" + circle + ", nodesComp=" + nodesComp + ", nodes=" + nodes + "]"; } }
samaitra/ignite
modules/core/src/main/java/org/apache/ignite/internal/client/util/GridClientConsistentHash.java
Java
apache-2.0
12,863
/* * 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.logging.log4j; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.ObjectMessage; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.spi.AbstractLogger; import org.junit.Test; import static org.junit.Assert.*; /** * */ public class AbstractLoggerTest extends AbstractLogger { private static class LogEvent { String markerName; Message data; Throwable t; public LogEvent(final String markerName, final Message data, final Throwable t) { this.markerName = markerName; this.data = data; this.t = t; } } private static final long serialVersionUID = 1L; private static Level currentLevel; private LogEvent currentEvent; private static Throwable t = new UnsupportedOperationException("Test"); private static Class<AbstractLogger> obj = AbstractLogger.class; private static String pattern = "{}, {}"; private static String p1 = "Long Beach"; private static String p2 = "California"; private static Message simple = new SimpleMessage("Hello"); private static Message object = new ObjectMessage(obj); private static Message param = new ParameterizedMessage(pattern, p1, p2); private static String marker = "TEST"; private static LogEvent[] events = new LogEvent[] { new LogEvent(null, simple, null), new LogEvent(marker, simple, null), new LogEvent(null, simple, t), new LogEvent(marker, simple, t), new LogEvent(null, object, null), new LogEvent(marker, object, null), new LogEvent(null, object, t), new LogEvent(marker, object, t), new LogEvent(null, param, null), new LogEvent(marker, param, null), new LogEvent(null, simple, null), new LogEvent(null, simple, t), new LogEvent(marker, simple, null), new LogEvent(marker, simple, t), new LogEvent(marker, simple, null), }; @Override public Level getLevel() { return currentLevel; } @Override public boolean isEnabled(final Level level, final Marker marker, final Message data, final Throwable t) { assertTrue("Incorrect Level. Expected " + currentLevel + ", actual " + level, level.equals(currentLevel)); if (marker == null) { if (currentEvent.markerName != null) { fail("Incorrect marker. Expected " + currentEvent.markerName + ", actual is null"); } } else { if (currentEvent.markerName == null) { fail("Incorrect marker. Expected null. Actual is " + marker.getName()); } else { assertTrue("Incorrect marker. Expected " + currentEvent.markerName + ", actual " + marker.getName(), currentEvent.markerName.equals(marker.getName())); } } if (data == null) { if (currentEvent.data != null) { fail("Incorrect message. Expected " + currentEvent.data + ", actual is null"); } } else { if (currentEvent.data == null) { fail("Incorrect message. Expected null. Actual is " + data.getFormattedMessage()); } else { assertTrue("Incorrect message type. Expected " + currentEvent.data + ", actual " + data, data.getClass().isAssignableFrom(currentEvent.data.getClass())); assertTrue("Incorrect message. Expected " + currentEvent.data.getFormattedMessage() + ", actual " + data.getFormattedMessage(), currentEvent.data.getFormattedMessage().equals(data.getFormattedMessage())); } } if (t == null) { if (currentEvent.t != null) { fail("Incorrect Throwable. Expected " + currentEvent.t + ", actual is null"); } } else { if (currentEvent.t == null) { fail("Incorrect Throwable. Expected null. Actual is " + t); } else { assertTrue("Incorrect Throwable. Expected " + currentEvent.t + ", actual " + t, currentEvent.t.equals(t)); } } return true; } @Override public boolean isEnabled(final Level level, final Marker marker, final Object data, final Throwable t) { return isEnabled(level, marker, new ObjectMessage(data), t); } @Override public boolean isEnabled(final Level level, final Marker marker, final String data) { return isEnabled(level, marker, new SimpleMessage(data), null); } @Override public boolean isEnabled(final Level level, final Marker marker, final String data, final Object... p1) { return isEnabled(level, marker, new ParameterizedMessage(data, p1), null); } @Override public boolean isEnabled(final Level level, final Marker marker, final String data, final Throwable t) { return isEnabled(level, marker, new SimpleMessage(data), t); } @Override public void logMessage(final String fqcn, final Level level, final Marker marker, final Message data, final Throwable t) { assertTrue("Incorrect Level. Expected " + currentLevel + ", actual " + level, level.equals(currentLevel)); if (marker == null) { if (currentEvent.markerName != null) { fail("Incorrect marker. Expected " + currentEvent.markerName + ", actual is null"); } } else { if (currentEvent.markerName == null) { fail("Incorrect marker. Expected null. Actual is " + marker.getName()); } else { assertTrue("Incorrect marker. Expected " + currentEvent.markerName + ", actual " + marker.getName(), currentEvent.markerName.equals(marker.getName())); } } if (data == null) { if (currentEvent.data != null) { fail("Incorrect message. Expected " + currentEvent.data + ", actual is null"); } } else { if (currentEvent.data == null) { fail("Incorrect message. Expected null. Actual is " + data.getFormattedMessage()); } else { assertTrue("Incorrect message type. Expected " + currentEvent.data + ", actual " + data, data.getClass().isAssignableFrom(currentEvent.data.getClass())); assertTrue("Incorrect message. Expected " + currentEvent.data.getFormattedMessage() + ", actual " + data.getFormattedMessage(), currentEvent.data.getFormattedMessage().equals(data.getFormattedMessage())); } } if (t == null) { if (currentEvent.t != null) { fail("Incorrect Throwable. Expected " + currentEvent.t + ", actual is null"); } } else { if (currentEvent.t == null) { fail("Incorrect Throwable. Expected null. Actual is " + t); } else { assertTrue("Incorrect Throwable. Expected " + currentEvent.t + ", actual " + t, currentEvent.t.equals(t)); } } } @Test public void testDebug() { currentLevel = Level.DEBUG; currentEvent = events[0]; debug("Hello"); debug(null, "Hello"); currentEvent = events[1]; debug(MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; debug("Hello", t); debug(null, "Hello", t); currentEvent = events[3]; debug(MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; debug(obj); currentEvent = events[5]; debug(MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; debug(obj, t); debug(null, obj, t); currentEvent = events[7]; debug(MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; debug(pattern, p1, p2); currentEvent = events[9]; debug(MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; debug(simple); debug(null, simple); debug(null, simple, null); currentEvent = events[11]; debug(simple, t); debug(null, simple, t); currentEvent = events[12]; debug(MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; debug(MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; debug(MarkerManager.getMarker("TEST"), simple); } @Test public void testError() { currentLevel = Level.ERROR; currentEvent = events[0]; error("Hello"); error(null, "Hello"); currentEvent = events[1]; error(MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; error("Hello", t); error(null, "Hello", t); currentEvent = events[3]; error(MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; error(obj); currentEvent = events[5]; error(MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; error(obj, t); error(null, obj, t); currentEvent = events[7]; error(MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; error(pattern, p1, p2); currentEvent = events[9]; error(MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; error(simple); error(null, simple); error(null, simple, null); currentEvent = events[11]; error(simple, t); error(null, simple, t); currentEvent = events[12]; error(MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; error(MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; error(MarkerManager.getMarker("TEST"), simple); } @Test public void testFatal() { currentLevel = Level.FATAL; currentEvent = events[0]; fatal("Hello"); fatal(null, "Hello"); currentEvent = events[1]; fatal(MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; fatal("Hello", t); fatal(null, "Hello", t); currentEvent = events[3]; fatal(MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; fatal(obj); currentEvent = events[5]; fatal(MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; fatal(obj, t); fatal(null, obj, t); currentEvent = events[7]; fatal(MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; fatal(pattern, p1, p2); currentEvent = events[9]; fatal(MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; fatal(simple); fatal(null, simple); fatal(null, simple, null); currentEvent = events[11]; fatal(simple, t); fatal(null, simple, t); currentEvent = events[12]; fatal(MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; fatal(MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; fatal(MarkerManager.getMarker("TEST"), simple); } @Test public void testInfo() { currentLevel = Level.INFO; currentEvent = events[0]; info("Hello"); info(null, "Hello"); currentEvent = events[1]; info(MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; info("Hello", t); info(null, "Hello", t); currentEvent = events[3]; info(MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; info(obj); currentEvent = events[5]; info(MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; info(obj, t); info(null, obj, t); currentEvent = events[7]; info(MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; info(pattern, p1, p2); currentEvent = events[9]; info(MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; info(simple); info(null, simple); info(null, simple, null); currentEvent = events[11]; info(simple, t); info(null, simple, t); currentEvent = events[12]; info(MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; info(MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; info(MarkerManager.getMarker("TEST"), simple); } @Test public void testLogDebug() { currentLevel = Level.DEBUG; currentEvent = events[0]; log(Level.DEBUG, "Hello"); log(Level.DEBUG, null, "Hello"); currentEvent = events[1]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; log(Level.DEBUG, "Hello", t); log(Level.DEBUG, null, "Hello", t); currentEvent = events[3]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; log(Level.DEBUG, obj); currentEvent = events[5]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; log(Level.DEBUG, obj, t); log(Level.DEBUG, null, obj, t); currentEvent = events[7]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; log(Level.DEBUG, pattern, p1, p2); currentEvent = events[9]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; log(Level.DEBUG, simple); log(Level.DEBUG, null, simple); log(Level.DEBUG, null, simple, null); currentEvent = events[11]; log(Level.DEBUG, simple, t); log(Level.DEBUG, null, simple, t); currentEvent = events[12]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; log(Level.DEBUG, MarkerManager.getMarker("TEST"), simple); } @Test public void testLogError() { currentLevel = Level.ERROR; currentEvent = events[0]; log(Level.ERROR, "Hello"); log(Level.ERROR, null, "Hello"); currentEvent = events[1]; log(Level.ERROR, MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; log(Level.ERROR, "Hello", t); log(Level.ERROR, null, "Hello", t); currentEvent = events[3]; log(Level.ERROR, MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; log(Level.ERROR, obj); currentEvent = events[5]; log(Level.ERROR, MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; log(Level.ERROR, obj, t); log(Level.ERROR, null, obj, t); currentEvent = events[7]; log(Level.ERROR, MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; log(Level.ERROR, pattern, p1, p2); currentEvent = events[9]; log(Level.ERROR, MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; log(Level.ERROR, simple); log(Level.ERROR, null, simple); log(Level.ERROR, null, simple, null); currentEvent = events[11]; log(Level.ERROR, simple, t); log(Level.ERROR, null, simple, t); currentEvent = events[12]; log(Level.ERROR, MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; log(Level.ERROR, MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; log(Level.ERROR, MarkerManager.getMarker("TEST"), simple); } @Test public void testLogFatal() { currentLevel = Level.FATAL; currentEvent = events[0]; log(Level.FATAL, "Hello"); log(Level.FATAL, null, "Hello"); currentEvent = events[1]; log(Level.FATAL, MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; log(Level.FATAL, "Hello", t); log(Level.FATAL, null, "Hello", t); currentEvent = events[3]; log(Level.FATAL, MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; log(Level.FATAL, obj); currentEvent = events[5]; log(Level.FATAL, MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; log(Level.FATAL, obj, t); log(Level.FATAL, null, obj, t); currentEvent = events[7]; log(Level.FATAL, MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; log(Level.FATAL, pattern, p1, p2); currentEvent = events[9]; log(Level.FATAL, MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; log(Level.FATAL, simple); log(Level.FATAL, null, simple); log(Level.FATAL, null, simple, null); currentEvent = events[11]; log(Level.FATAL, simple, t); log(Level.FATAL, null, simple, t); currentEvent = events[12]; log(Level.FATAL, MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; log(Level.FATAL, MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; log(Level.FATAL, MarkerManager.getMarker("TEST"), simple); } @Test public void testLogInfo() { currentLevel = Level.INFO; currentEvent = events[0]; log(Level.INFO, "Hello"); log(Level.INFO, null, "Hello"); currentEvent = events[1]; log(Level.INFO, MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; log(Level.INFO, "Hello", t); log(Level.INFO, null, "Hello", t); currentEvent = events[3]; log(Level.INFO, MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; log(Level.INFO, obj); currentEvent = events[5]; log(Level.INFO, MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; log(Level.INFO, obj, t); log(Level.INFO, null, obj, t); currentEvent = events[7]; log(Level.INFO, MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; log(Level.INFO, pattern, p1, p2); currentEvent = events[9]; log(Level.INFO, MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; log(Level.INFO, simple); log(Level.INFO, null, simple); log(Level.INFO, null, simple, null); currentEvent = events[11]; log(Level.INFO, simple, t); log(Level.INFO, null, simple, t); currentEvent = events[12]; log(Level.INFO, MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; log(Level.INFO, MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; log(Level.INFO, MarkerManager.getMarker("TEST"), simple); } @Test public void testLogTrace() { currentLevel = Level.TRACE; currentEvent = events[0]; log(Level.TRACE, "Hello"); log(Level.TRACE, null, "Hello"); currentEvent = events[1]; log(Level.TRACE, MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; log(Level.TRACE, "Hello", t); log(Level.TRACE, null, "Hello", t); currentEvent = events[3]; log(Level.TRACE, MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; log(Level.TRACE, obj); currentEvent = events[5]; log(Level.TRACE, MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; log(Level.TRACE, obj, t); log(Level.TRACE, null, obj, t); currentEvent = events[7]; log(Level.TRACE, MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; log(Level.TRACE, pattern, p1, p2); currentEvent = events[9]; log(Level.TRACE, MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; log(Level.TRACE, simple); log(Level.TRACE, null, simple); log(Level.TRACE, null, simple, null); currentEvent = events[11]; log(Level.TRACE, simple, t); log(Level.TRACE, null, simple, t); currentEvent = events[12]; log(Level.TRACE, MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; log(Level.TRACE, MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; log(Level.TRACE, MarkerManager.getMarker("TEST"), simple); } @Test public void testLogWarn() { currentLevel = Level.WARN; currentEvent = events[0]; log(Level.WARN, "Hello"); log(Level.WARN, null, "Hello"); currentEvent = events[1]; log(Level.WARN, MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; log(Level.WARN, "Hello", t); log(Level.WARN, null, "Hello", t); currentEvent = events[3]; log(Level.WARN, MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; log(Level.WARN, obj); currentEvent = events[5]; log(Level.WARN, MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; log(Level.WARN, obj, t); log(Level.WARN, null, obj, t); currentEvent = events[7]; log(Level.WARN, MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; log(Level.WARN, pattern, p1, p2); currentEvent = events[9]; log(Level.WARN, MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; log(Level.WARN, simple); log(Level.WARN, null, simple); log(Level.WARN, null, simple, null); currentEvent = events[11]; log(Level.WARN, simple, t); log(Level.WARN, null, simple, t); currentEvent = events[12]; log(Level.WARN, MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; log(Level.WARN, MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; log(Level.WARN, MarkerManager.getMarker("TEST"), simple); } @Test public void testTrace() { currentLevel = Level.TRACE; currentEvent = events[0]; trace("Hello"); trace(null, "Hello"); currentEvent = events[1]; trace(MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; trace("Hello", t); trace(null, "Hello", t); currentEvent = events[3]; trace(MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; trace(obj); currentEvent = events[5]; trace(MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; trace(obj, t); trace(null, obj, t); currentEvent = events[7]; trace(MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; trace(pattern, p1, p2); currentEvent = events[9]; trace(MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; trace(simple); trace(null, simple); trace(null, simple, null); currentEvent = events[11]; trace(simple, t); trace(null, simple, t); currentEvent = events[12]; trace(MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; trace(MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; trace(MarkerManager.getMarker("TEST"), simple); } @Test public void testWarn() { currentLevel = Level.WARN; currentEvent = events[0]; warn("Hello"); warn(null, "Hello"); currentEvent = events[1]; warn(MarkerManager.getMarker("TEST"), "Hello"); currentEvent = events[2]; warn("Hello", t); warn(null, "Hello", t); currentEvent = events[3]; warn(MarkerManager.getMarker("TEST"), "Hello", t); currentEvent = events[4]; warn(obj); currentEvent = events[5]; warn(MarkerManager.getMarker("TEST"), obj); currentEvent = events[6]; warn(obj, t); warn(null, obj, t); currentEvent = events[7]; warn(MarkerManager.getMarker("TEST"), obj, t); currentEvent = events[8]; warn(pattern, p1, p2); currentEvent = events[9]; warn(MarkerManager.getMarker("TEST"), pattern, p1, p2); currentEvent = events[10]; warn(simple); warn(null, simple); warn(null, simple, null); currentEvent = events[11]; warn(simple, t); warn(null, simple, t); currentEvent = events[12]; warn(MarkerManager.getMarker("TEST"), simple, null); currentEvent = events[13]; warn(MarkerManager.getMarker("TEST"), simple, t); currentEvent = events[14]; warn(MarkerManager.getMarker("TEST"), simple); } }
MagicWiz/log4j2
log4j-api/src/test/java/org/apache/logging/log4j/AbstractLoggerTest.java
Java
apache-2.0
26,624
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.segment.data; import io.druid.java.util.common.IAE; import java.io.IOException; public abstract class SingleValueIndexedIntsWriter implements IndexedIntsWriter { @Override public void add(Object obj) throws IOException { if (obj == null) { addValue(0); } else if (obj instanceof Integer) { addValue(((Number) obj).intValue()); } else if (obj instanceof int[]) { int[] vals = (int[]) obj; if (vals.length == 0) { addValue(0); } else { addValue(vals[0]); } } else { throw new IAE("Unsupported single value type: " + obj.getClass()); } } protected abstract void addValue(int val) throws IOException; }
erikdubbelboer/druid
processing/src/main/java/io/druid/segment/data/SingleValueIndexedIntsWriter.java
Java
apache-2.0
1,515
/* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.executor.cdi; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceUnit; import org.jbpm.shared.services.impl.TransactionalCommandService; @ApplicationScoped public class ExecutorDatabaseProducer { private EntityManagerFactory emf; @PersistenceUnit(unitName = "org.jbpm.executor") @ApplicationScoped @Produces public EntityManagerFactory getEntityManagerFactory() { if (this.emf == null) { // this needs to be here for non EE containers this.emf = Persistence.createEntityManagerFactory("org.jbpm.executor"); } return this.emf; } @Produces public TransactionalCommandService produceCommandService(EntityManagerFactory emf) { return new TransactionalCommandService(emf); } }
pleacu/jbpm
jbpm-services/jbpm-executor-cdi/src/test/java/org/jbpm/executor/cdi/ExecutorDatabaseProducer.java
Java
apache-2.0
1,548
// "Replace with 'Stream.mapToLong().sum()'" "true" import java.util.Collection; import java.util.List; class Test { void foo(List<List<String>> s) { long count = s.stream().peek(System.out::println).flatMap(Collection::stream).c<caret>ount(); } }
smmribeiro/intellij-community
java/java-tests/testData/inspection/inefficientStreamCount/beforePeekFlatMapCount.java
Java
apache-2.0
257
/* * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jsyntaxpane.components; import jsyntaxpane.actions.*; import java.awt.Color; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.Token; /** * This class contains static utility methods to make highliting in text * components easier. * * @author Ayman Al-Sairafi */ public class Markers { // This subclass is used in our highlighting code public static class SimpleMarker extends DefaultHighlighter.DefaultHighlightPainter { public SimpleMarker(Color color) { super(color); } } /** * Removes only our private highlights * This is public so that we can remove the highlights when the editorKit * is unregistered. SimpleMarker can be null, in which case all instances of * our Markers are removed. * @param component the text component whose markers are to be removed * @param marker the SimpleMarker to remove */ public static void removeMarkers(JTextComponent component, SimpleMarker marker) { Highlighter hilite = component.getHighlighter(); Highlighter.Highlight[] hilites = hilite.getHighlights(); for (int i = 0; i < hilites.length; i++) { if (hilites[i].getPainter() instanceof SimpleMarker) { SimpleMarker hMarker = (SimpleMarker) hilites[i].getPainter(); if (marker == null || hMarker.equals(marker)) { hilite.removeHighlight(hilites[i]); } } } } /** * Remove all the markers from an JEditorPane * @param editorPane */ public static void removeMarkers(JTextComponent editorPane) { removeMarkers(editorPane, null); } /** * add highlights for the given Token on the given pane * @param pane * @param token * @param marker */ public static void markToken(JTextComponent pane, Token token, SimpleMarker marker) { markText(pane, token.start, token.end(), marker); } /** * add highlights for the given region on the given pane * @param pane * @param start * @param end * @param marker */ public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) { try { Highlighter hiliter = pane.getHighlighter(); int selStart = pane.getSelectionStart(); int selEnd = pane.getSelectionEnd(); // if there is no selection or selection does not overlap if(selStart == selEnd || end < selStart || start > selStart) { hiliter.addHighlight(start, end, marker); return; } // selection starts within the highlight, highlight before slection if(selStart > start && selStart < end ) { hiliter.addHighlight(start, selStart, marker); } // selection ends within the highlight, highlight remaining if(selEnd > start && selEnd < end ) { hiliter.addHighlight(selEnd, end, marker); } } catch (BadLocationException ex) { // nothing we can do if the request is out of bound LOG.log(Level.SEVERE, null, ex); } } /** * Mark all text in the document that matches the given pattern * @param pane control to use * @param pattern pattern to match * @param marker marker to use for highlighting */ public static void markAll(JTextComponent pane, Pattern pattern, SimpleMarker marker) { SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(pane); if(sDoc == null || pattern == null) { return; } Matcher matcher = sDoc.getMatcher(pattern); // we may not have any matcher (due to undo or something, so don't do anything. if(matcher==null) { return; } while(matcher.find()) { markText(pane, matcher.start(), matcher.end(), marker); } } private static final Logger LOG = Logger.getLogger(Markers.class.getName()); }
zqq90/webit-editor
src/main/java/jsyntaxpane/components/Markers.java
Java
bsd-3-clause
4,976
package org.knowm.xchange.ccex.dto.account; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; public class CCEXBalance { private String Currency; private BigDecimal Balance; private BigDecimal Available; private BigDecimal Pending; private String CryptoAddress; public CCEXBalance( @JsonProperty("Currency") String currency, @JsonProperty("Balance") BigDecimal balance, @JsonProperty("Available") BigDecimal available, @JsonProperty("Pending") BigDecimal pending, @JsonProperty("CryptoAddress") String cryptoAddress) { super(); Currency = currency; Balance = balance; Available = available; Pending = pending; CryptoAddress = cryptoAddress; } public String getCurrency() { return Currency; } public void setCurrency(String currency) { Currency = currency; } public BigDecimal getBalance() { return Balance; } public void setBalance(BigDecimal balance) { Balance = balance; } public BigDecimal getAvailable() { return Available; } public void setAvailable(BigDecimal available) { Available = available; } public BigDecimal getPending() { return Pending; } public void setPending(BigDecimal pending) { Pending = pending; } public String getCryptoAddress() { return CryptoAddress; } public void setCryptoAddress(String cryptoAddress) { CryptoAddress = cryptoAddress; } @Override public String toString() { return "CCEXBalance [Currency=" + Currency + ", Balance=" + Balance + ", Available=" + Available + ", Pending=" + Pending + ", CryptoAddress=" + CryptoAddress + "]"; } }
timmolter/XChange
xchange-ccex/src/main/java/org/knowm/xchange/ccex/dto/account/CCEXBalance.java
Java
mit
1,759
package org.jboss.windup.config.phase; import org.jboss.windup.config.AbstractRuleProvider; import org.ocpsoft.rewrite.config.Rule; /** * Previous: {@link PostReportRenderingPhase}<br/> * Next: {@link PostFinalizePhase} * * <p> * This occurs at the end of execution. {@link Rule}s in this phase are responsible for any cleanup of resources that * may have been opened during {@link Rule}s from earlier {@link AbstractRuleProvider}s. * </p> * * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> * */ public class FinalizePhase extends RulePhase { public FinalizePhase() { super(FinalizePhase.class); } @Override public Class<? extends RulePhase> getExecuteAfter() { return PostReportRenderingPhase.class; } @Override public Class<? extends RulePhase> getExecuteBefore() { return null; } }
sgilda/windup
config/api/src/main/java/org/jboss/windup/config/phase/FinalizePhase.java
Java
epl-1.0
892
package org.jnbt; /* * JNBT License * * Copyright (c) 2010 Graham Edgecombe * 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 JNBT team 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. */ /** * The <code>TAG_Float</code> tag. * @author Graham Edgecombe * */ public final class FloatTag extends Tag { /** * The value. */ private final float value; /** * Creates the tag. * @param name The name. * @param value The value. */ public FloatTag(String name, float value) { super(name); this.value = value; } @Override public Float getValue() { return value; } @Override public String toString() { String name = getName(); String append = ""; if(name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Float" + append + ": " + value; } }
ferrybig/Enderstone
src/org/jnbt/FloatTag.java
Java
gpl-3.0
2,294
/* * Copyright (C) 2010 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.google.doclava; import java.util.ArrayList; public class ParsedTagInfo extends TagInfo { private ContainerInfo mContainer; private String mCommentText; private Comment mComment; ParsedTagInfo(String name, String kind, String text, ContainerInfo base, SourcePositionInfo sp) { super(name, kind, text, SourcePositionInfo.findBeginning(sp, text)); mContainer = base; mCommentText = text; } public TagInfo[] commentTags() { if (mComment == null) { mComment = new Comment(mCommentText, mContainer, position()); } return mComment.tags(); } protected void setCommentText(String comment) { mCommentText = comment; } public static <T extends ParsedTagInfo> TagInfo[] joinTags(T[] tags) { ArrayList<TagInfo> list = new ArrayList<TagInfo>(); final int N = tags.length; for (int i = 0; i < N; i++) { TagInfo[] t = tags[i].commentTags(); final int M = t.length; for (int j = 0; j < M; j++) { list.add(t[j]); } } return list.toArray(new TagInfo[list.size()]); } }
kwf2030/doclava
src/main/java/com/google/doclava/ParsedTagInfo.java
Java
apache-2.0
1,692
/* * 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.gobblin.data.management.retention.action; import java.io.IOException; import java.util.List; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.typesafe.config.Config; import org.apache.gobblin.data.management.policy.VersionSelectionPolicy; import org.apache.gobblin.data.management.version.DatasetVersion; import org.apache.gobblin.data.management.version.FileStatusAware; import org.apache.gobblin.data.management.version.FileSystemDatasetVersion; import org.apache.gobblin.util.ConfigUtils; /** * A {@link RetentionAction} that is used to change the permissions/owner/group of a {@link FileSystemDatasetVersion} */ @Slf4j public class AccessControlAction extends RetentionAction { /** * Optional - The permission mode to set on selected versions either in octal or symbolic format. E.g 750 */ private static final String MODE_KEY = "mode"; /** * Optional - The owner to set on selected versions */ private static final String OWNER_KEY = "owner"; /** * Optional - The group to set on selected versions */ private static final String GROUP_KEY = "group"; private final Optional<FsPermission> permission; private final Optional<String> owner; private final Optional<String> group; @VisibleForTesting @Getter private final VersionSelectionPolicy<DatasetVersion> selectionPolicy; @VisibleForTesting AccessControlAction(Config actionConfig, FileSystem fs, Config jobConfig) { super(actionConfig, fs, jobConfig); this.permission = actionConfig.hasPath(MODE_KEY) ? Optional.of(new FsPermission(actionConfig.getString(MODE_KEY))) : Optional .<FsPermission> absent(); this.owner = Optional.fromNullable(ConfigUtils.getString(actionConfig, OWNER_KEY, null)); this.group = Optional.fromNullable(ConfigUtils.getString(actionConfig, GROUP_KEY, null)); this.selectionPolicy = createSelectionPolicy(actionConfig, jobConfig); } /** * Applies {@link #selectionPolicy} on <code>allVersions</code> and modifies permission/owner to the selected {@link DatasetVersion}s * where necessary. * <p> * This action only available for {@link FileSystemDatasetVersion}. It simply skips the operation if a different type * of {@link DatasetVersion} is passed. * </p> * {@inheritDoc} * @see org.apache.gobblin.data.management.retention.action.RetentionAction#execute(java.util.List) */ @Override public void execute(List<DatasetVersion> allVersions) throws IOException { // Select version on which access control actions need to performed for (DatasetVersion datasetVersion : this.selectionPolicy.listSelectedVersions(allVersions)) { executeOnVersion(datasetVersion); } } private void executeOnVersion(DatasetVersion datasetVersion) throws IOException { // Perform action if it is a FileSystemDatasetVersion if (datasetVersion instanceof FileSystemDatasetVersion) { FileSystemDatasetVersion fsDatasetVersion = (FileSystemDatasetVersion) datasetVersion; // If the version is filestatus aware, use the filestatus to ignore permissions update when the path already has // the desired permissions if (datasetVersion instanceof FileStatusAware) { for (FileStatus fileStatus : ((FileStatusAware)datasetVersion).getFileStatuses()) { if (needsPermissionsUpdate(fileStatus) || needsOwnerUpdate(fileStatus) || needsGroupUpdate(fileStatus)) { updatePermissionsAndOwner(fileStatus.getPath()); } } } else { for (Path path : fsDatasetVersion.getPaths()) { updatePermissionsAndOwner(path); } } } } private boolean needsPermissionsUpdate(FileStatus fileStatus) { return this.permission.isPresent() && !this.permission.get().equals(fileStatus.getPermission()); } private boolean needsOwnerUpdate(FileStatus fileStatus) { return this.owner.isPresent() && !StringUtils.equals(owner.get(), fileStatus.getOwner()); } private boolean needsGroupUpdate(FileStatus fileStatus) { return this.group.isPresent() && !StringUtils.equals(group.get(), fileStatus.getGroup()); } private void updatePermissionsAndOwner(Path path) throws IOException { boolean atLeastOneOperationFailed = false; if (this.fs.exists(path)) { try { // Update permissions if set in config if (this.permission.isPresent()) { if (!this.isSimulateMode) { this.fs.setPermission(path, this.permission.get()); log.debug("Set permissions for {} to {}", path, this.permission.get()); } else { log.info("Simulating set permissions for {} to {}", path, this.permission.get()); } } } catch (IOException e) { log.error(String.format("Setting permissions failed on %s", path), e); atLeastOneOperationFailed = true; } // Update owner and group if set in config if (this.owner.isPresent() || this.group.isPresent()) { if (!this.isSimulateMode) { this.fs.setOwner(path, this.owner.orNull(), this.group.orNull()); log.debug("Set owner and group for {} to {}:{}", path, this.owner.orNull(), this.group.orNull()); } else { log.info("Simulating set owner and group for {} to {}:{}", path, this.owner.orNull(), this.group.orNull()); } } if (atLeastOneOperationFailed) { throw new RuntimeException(String.format( "At least one failure happened while processing %s. Look for previous logs for failures", path)); } } } }
aditya1105/gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/action/AccessControlAction.java
Java
apache-2.0
6,736
/* * 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.spi.checkpoint.jdbc; import org.apache.ignite.spi.checkpoint.*; import org.apache.ignite.testframework.junits.spi.*; import org.hsqldb.jdbc.*; /** * Grid jdbc checkpoint SPI custom config self test. */ @GridSpiTest(spi = JdbcCheckpointSpi.class, group = "Checkpoint SPI") public class JdbcCheckpointSpiCustomConfigSelfTest extends GridCheckpointSpiAbstractTest<JdbcCheckpointSpi> { /** {@inheritDoc} */ @Override protected void spiConfigure(JdbcCheckpointSpi spi) throws Exception { jdbcDataSource ds = new jdbcDataSource(); ds.setDatabase("jdbc:hsqldb:mem:gg_test_" + getClass().getSimpleName()); ds.setUser("sa"); ds.setPassword(""); spi.setDataSource(ds); spi.setCheckpointTableName("custom_config_checkpoints"); spi.setKeyFieldName("key"); spi.setValueFieldName("value"); spi.setValueFieldType("longvarbinary"); spi.setExpireDateFieldName("expire_date"); super.spiConfigure(spi); } }
akuznetsov-gridgain/ignite
modules/core/src/test/java/org/apache/ignite/spi/checkpoint/jdbc/JdbcCheckpointSpiCustomConfigSelfTest.java
Java
apache-2.0
1,829
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis.config; import com.google.common.cache.Cache; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.analysis.BlazeDirectories; import com.google.devtools.build.lib.analysis.ConfigurationCollectionFactory; import com.google.devtools.build.lib.analysis.config.BuildConfiguration.Fragment; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.util.Preconditions; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A factory class for {@link BuildConfiguration} instances. This is unfortunately more complex, * and should be simplified in the future, if * possible. Right now, creating a {@link BuildConfiguration} instance involves * creating the instance itself and the related configurations; the main method * is {@link #createConfigurations}. * * <p>Avoid calling into this class, and instead use the skyframe infrastructure to obtain * configuration instances. * * <p>Blaze currently relies on the fact that all {@link BuildConfiguration} * instances used in a build can be constructed ahead of time by this class. */ @ThreadCompatible // safe as long as separate instances are used public final class ConfigurationFactory { private final List<ConfigurationFragmentFactory> configurationFragmentFactories; private final ConfigurationCollectionFactory configurationCollectionFactory; public ConfigurationFactory( ConfigurationCollectionFactory configurationCollectionFactory, ConfigurationFragmentFactory... fragmentFactories) { this(configurationCollectionFactory, ImmutableList.copyOf(fragmentFactories)); } public ConfigurationFactory( ConfigurationCollectionFactory configurationCollectionFactory, List<ConfigurationFragmentFactory> fragmentFactories) { this.configurationCollectionFactory = Preconditions.checkNotNull(configurationCollectionFactory); this.configurationFragmentFactories = ImmutableList.copyOf(fragmentFactories); } /** * Creates a set of build configurations with top-level configuration having the given options. * * <p>The rest of the configurations are created based on the set of transitions available. */ @Nullable public BuildConfiguration createConfigurations( Cache<String, BuildConfiguration> cache, PackageProviderForConfigurations loadedPackageProvider, BuildOptions buildOptions, EventHandler errorEventListener) throws InvalidConfigurationException, InterruptedException { return configurationCollectionFactory.createConfigurations(this, cache, loadedPackageProvider, buildOptions, errorEventListener); } /** * Returns a {@link com.google.devtools.build.lib.analysis.config.BuildConfiguration} based on the * given set of build options. * * <p>If the configuration has already been created, re-uses it, otherwise, creates a new one. */ @Nullable public BuildConfiguration getConfiguration( PackageProviderForConfigurations loadedPackageProvider, BuildOptions buildOptions, boolean actionsDisabled, Cache<String, BuildConfiguration> cache) throws InvalidConfigurationException, InterruptedException { String cacheKey = buildOptions.computeCacheKey(); BuildConfiguration result = cache.getIfPresent(cacheKey); if (result != null) { return result; } Map<Class<? extends Fragment>, Fragment> fragments = new HashMap<>(); // Create configuration fragments for (ConfigurationFragmentFactory factory : configurationFragmentFactories) { Class<? extends Fragment> fragmentType = factory.creates(); Fragment fragment = loadedPackageProvider.getFragment(buildOptions, fragmentType); if (fragment != null && fragments.get(fragment.getClass()) == null) { fragments.put(fragment.getClass(), fragment); } } BlazeDirectories directories = loadedPackageProvider.getDirectories(); if (loadedPackageProvider.valuesMissing()) { return null; } result = new BuildConfiguration(directories, fragments, buildOptions, actionsDisabled); cache.put(cacheKey, result); return result; } public List<ConfigurationFragmentFactory> getFactories() { return configurationFragmentFactories; } }
iamthearm/bazel
src/main/java/com/google/devtools/build/lib/analysis/config/ConfigurationFactory.java
Java
apache-2.0
5,071
/* * 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.jackrabbit.oak.plugins.document.blob.ds; import java.util.Date; import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore; import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreUtils; import org.apache.jackrabbit.oak.plugins.document.DocumentMK; import org.apache.jackrabbit.oak.plugins.document.MongoBlobGCTest; import org.apache.jackrabbit.oak.plugins.document.MongoUtils; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; /** * Test for MongoMK GC with {@link DataStoreBlobStore} * */ public class MongoDataStoreBlobGCTest extends MongoBlobGCTest { protected Date startDate; protected DataStoreBlobStore blobStore; @BeforeClass public static void setUpBeforeClass() throws Exception { try { Assume.assumeNotNull(DataStoreUtils.getBlobStore()); } catch (Exception e) { Assume.assumeNoException(e); } } @Override protected DocumentMK.Builder addToBuilder(DocumentMK.Builder mk) { return super.addToBuilder(mk).setBlobStore(blobStore); } @Before @Override public void setUpConnection() throws Exception { startDate = new Date(); blobStore = DataStoreUtils.getBlobStore(folder.newFolder()); super.setUpConnection(); } }
trekawek/jackrabbit-oak
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/blob/ds/MongoDataStoreBlobGCTest.java
Java
apache-2.0
2,161
/* * 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.drill.exec.physical.impl.validate; import java.util.List; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.ops.ExecutorFragmentContext; import org.apache.drill.exec.physical.config.IteratorValidator; import org.apache.drill.exec.physical.impl.BatchCreator; import org.apache.drill.exec.record.RecordBatch; import org.apache.drill.shaded.guava.com.google.common.base.Preconditions; public class IteratorValidatorCreator implements BatchCreator<IteratorValidator>{ static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(IteratorValidatorCreator.class); @Override public IteratorValidatorBatchIterator getBatch(ExecutorFragmentContext context, IteratorValidator config, List<RecordBatch> children) throws ExecutionSetupException { Preconditions.checkArgument(children.size() == 1); RecordBatch child = children.iterator().next(); IteratorValidatorBatchIterator iter = new IteratorValidatorBatchIterator(child, config.isRepeatable); boolean validateBatches = context.getOptions().getOption(ExecConstants.ENABLE_VECTOR_VALIDATOR) || context.getConfig().getBoolean(ExecConstants.ENABLE_VECTOR_VALIDATION); iter.enableBatchValidation(validateBatches); logger.trace("Iterator validation enabled for " + child.getClass().getSimpleName() + (validateBatches ? " with vector validation" : "")); return iter; } }
apache/drill
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorCreator.java
Java
apache-2.0
2,373
/* * JBoss, Home of Professional Open Source. * Copyright 2014 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 io.undertow.predicate; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import io.undertow.server.HttpServerExchange; import io.undertow.util.HttpString; import io.undertow.util.Methods; /** * A predicate that returns true if the request is idempotent * according to the HTTP RFC. * * @author Stuart Douglas */ public class IdempotentPredicate implements Predicate { public static final IdempotentPredicate INSTANCE = new IdempotentPredicate(); private static final Set<HttpString> METHODS; static { Set<HttpString> methods = new HashSet<>(); methods.add(Methods.GET); methods.add(Methods.DELETE); methods.add(Methods.PUT); methods.add(Methods.HEAD); methods.add(Methods.OPTIONS); METHODS = Collections.unmodifiableSet(methods); } @Override public boolean resolve(HttpServerExchange value) { return METHODS.contains(value.getRequestMethod()); } public static class Builder implements PredicateBuilder { @Override public String name() { return "idempotent"; } @Override public Map<String, Class<?>> parameters() { return Collections.emptyMap(); } @Override public Set<String> requiredParameters() { return Collections.emptySet(); } @Override public String defaultParameter() { return null; } @Override public Predicate build(Map<String, Object> config) { return INSTANCE; } } }
stuartwdouglas/undertow
core/src/main/java/io/undertow/predicate/IdempotentPredicate.java
Java
apache-2.0
2,348
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf.converter; import javax.xml.transform.TransformerException; import org.w3c.dom.Element; import org.apache.camel.Converter; import org.apache.camel.component.cxf.CxfPayload; import org.apache.camel.converter.jaxp.DomConverter; // This converter is used to show how to override the CxfPayload default toString converter @Converter public final class MyCxfCustomerConverter { private MyCxfCustomerConverter() { //Helper class } @Converter public static String cxfPayloadToString(final CxfPayload<?> payload) { DomConverter converter = new DomConverter(); StringBuilder buf = new StringBuilder(); for (Object element : payload.getBody()) { String elementString = ""; try { elementString = converter.toString((Element) element, null); } catch (TransformerException e) { elementString = element.toString(); } buf.append(elementString); } return buf.toString(); } }
nikhilvibhav/camel
components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/MyCxfCustomerConverter.java
Java
apache-2.0
1,868
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.krad.util; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.comparators.ComparableComparator; import org.kuali.rice.core.api.exception.KualiException; import org.kuali.rice.core.api.util.type.TypeUtils; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * BeanPropertyComparator compares the two beans using multiple property names * * */ public class BeanPropertyComparator implements Comparator, Serializable { private static final long serialVersionUID = -2675700473766186018L; boolean ignoreCase; private List propertyNames; private Comparator stringComparator; private Comparator booleanComparator; private Comparator genericComparator; /** * Constructs a PropertyComparator for comparing beans using the properties named in the given List * * <p>if the List is null, the beans will be compared directly * by Properties will be compared in the order in which they are listed. Case will be ignored * in String comparisons.</p> * * @param propertyNames List of property names (as Strings) used to compare beans */ public BeanPropertyComparator(List propertyNames) { this(propertyNames, true); } /** * Constructs a PropertyComparator for comparing beans using the properties named in the given List. * * <p>Properties will be compared * in the order in which they are listed. Case will be ignored if ignoreCase is true.</p> * * @param propertyNames List of property names (as Strings) used to compare beans * @param ignoreCase if true, case will be ignored during String comparisons */ public BeanPropertyComparator(List propertyNames, boolean ignoreCase) { if (propertyNames == null) { throw new IllegalArgumentException("invalid (null) propertyNames list"); } if (propertyNames.size() == 0) { throw new IllegalArgumentException("invalid (empty) propertyNames list"); } this.propertyNames = Collections.unmodifiableList(propertyNames); this.ignoreCase = ignoreCase; if (ignoreCase) { this.stringComparator = String.CASE_INSENSITIVE_ORDER; } else { this.stringComparator = ComparableComparator.getInstance(); } this.booleanComparator = new Comparator() { public int compare(Object o1, Object o2) { int compared = 0; Boolean b1 = (Boolean) o1; Boolean b2 = (Boolean) o2; if (!b1.equals(b2)) { if (b1.equals(Boolean.FALSE)) { compared = -1; } else { compared = 1; } } return compared; } }; this.genericComparator = ComparableComparator.getInstance(); } /** * Compare two JavaBeans by the properties given to the constructor. * * @param o1 Object The first bean to get data from to compare against * @param o2 Object The second bean to get data from to compare * @return int negative or positive based on order */ public int compare(Object o1, Object o2) { int compared = 0; try { for (Iterator i = propertyNames.iterator(); (compared == 0) && i.hasNext();) { String currentProperty = i.next().toString(); // choose appropriate comparator Comparator currentComparator = null; try { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o1, currentProperty); Class propertyClass = propertyDescriptor.getPropertyType(); if (propertyClass.equals(String.class)) { currentComparator = this.stringComparator; } else if (TypeUtils.isBooleanClass(propertyClass)) { currentComparator = this.booleanComparator; } else { currentComparator = this.genericComparator; } } catch (NullPointerException e) { throw new BeanComparisonException("unable to find property '" + o1.getClass().getName() + "." + currentProperty + "'", e); } // compare the values Object value1 = PropertyUtils.getProperty(o1, currentProperty); Object value2 = PropertyUtils.getProperty(o2, currentProperty); /* Fix for KULRICE-5170 : BeanPropertyComparator throws exception when a null value is found in sortable non-string data type column */ if ( value1 == null && value2 == null) return 0; else if ( value1 == null) return -1; else if ( value2 == null ) return 1; /* End KULRICE-5170 Fix*/ compared = currentComparator.compare(value1, value2); } } catch (IllegalAccessException e) { throw new BeanComparisonException("unable to compare property values", e); } catch (NoSuchMethodException e) { throw new BeanComparisonException("unable to compare property values", e); } catch (InvocationTargetException e) { throw new BeanComparisonException("unable to compare property values", e); } return compared; } public static class BeanComparisonException extends KualiException { private static final long serialVersionUID = 2622379680100640029L; /** * @param message * @param t */ public BeanComparisonException(String message, Throwable t) { super(message, t); } } }
jruchcolo/rice-cd
rice-framework/krad-app-framework/src/main/java/org/kuali/rice/krad/util/BeanPropertyComparator.java
Java
apache-2.0
6,807