index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateDocument.java
/* * Copyright 2017 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.cloudformation.templates.editor; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.eclipse.jface.text.Document; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.cloudformation.templates.TemplateArrayNode; import com.amazonaws.eclipse.cloudformation.templates.TemplateNode; import com.amazonaws.eclipse.cloudformation.templates.TemplateNodePath.PathNode; import com.amazonaws.eclipse.cloudformation.templates.TemplateObjectNode; public class TemplateDocument extends Document { public static interface TemplateDocumentListener { void onTemplateDocumentChanged(); } private final List<TemplateDocumentListener> listeners = new ArrayList<>(); private TemplateNode model; /** The path from the root to the current position in the Json Document.*/ private List<PathNode> subPaths; public void addTemplateDocumentListener(TemplateDocumentListener listener) { listeners.add(listener); } public void removeTemplateDocumentListener(TemplateDocumentListener listener) { listeners.remove(listener); } public TemplateNode getModel() { return model; } public void setModel(TemplateNode root) { this.model = root; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { for (TemplateDocumentListener listener : listeners) { listener.onTemplateDocumentChanged(); } } }); } public TemplateNode lookupNodeByPath(List<PathNode> subPaths) { TemplateNode node = model; if (subPaths.isEmpty() || !subPaths.get(0).getFieldName().equals(TemplateNode.ROOT_PATH)) { throw new RuntimeException("Unexpected path encountered"); } for (int i = 1; i < subPaths.size(); ++i) { PathNode subPath = subPaths.get(i); if (node != null && node instanceof TemplateObjectNode) { TemplateObjectNode object = (TemplateObjectNode) node; String path = subPath.getFieldName(); node = object.get(path); } else if (node != null && node instanceof TemplateArrayNode) { TemplateArrayNode array = (TemplateArrayNode) node; node = array.getMembers().get(subPath.getIndex()); } else { throw new RuntimeException("Unexpected node structure"); } } return node; } public TemplateNode findNode(int documentOffset) { return findNode(documentOffset, model); } private TemplateNode findNode(int documentOffset, TemplateNode node) { if (node.getStartLocation().getCharOffset() > documentOffset) { throw new RuntimeException("Out of bounds in node search"); } if (node instanceof TemplateObjectNode) { TemplateObjectNode object = (TemplateObjectNode)node; for (Entry<String, TemplateNode> entry : object.getFields()) { entry.getKey(); if (match(documentOffset, entry.getValue())) { return findNode(documentOffset, entry.getValue()); } } } else if (node instanceof TemplateArrayNode) { TemplateArrayNode array = (TemplateArrayNode)node; for (TemplateNode member : array.getMembers()) { if (match(documentOffset, member)) { return findNode(documentOffset, member); } } } return node; } public void setSubPaths(List<PathNode> subPaths) { this.subPaths = subPaths; } public List<PathNode> getSubPaths(int offset) { if (subPaths != null && !subPaths.isEmpty()) { return subPaths; } else { TemplateNode node = findNode(offset); return node.getSubPaths(); } } private boolean match(int offset, TemplateNode node) { return offset >= node.getStartLocation().getCharOffset() && offset <= node.getEndLocation().getCharOffset(); } }
8,100
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateContentOutlinePage.java
/* * Copyright 2012 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.cloudformation.templates.editor; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.views.contentoutline.ContentOutlinePage; import com.amazonaws.eclipse.cloudformation.templates.TemplateArrayNode; import com.amazonaws.eclipse.cloudformation.templates.TemplateNode; import com.amazonaws.eclipse.cloudformation.templates.TemplateObjectNode; import com.amazonaws.eclipse.cloudformation.templates.TemplateValueNode; import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateDocument.TemplateDocumentListener; import com.fasterxml.jackson.core.JsonLocation; public class TemplateContentOutlinePage extends ContentOutlinePage implements TemplateDocumentListener { private final TemplateDocument document; public TemplateContentOutlinePage(TemplateDocument document) { this.document = document; } @Override public void dispose() { // TODO: Remove the document listener super.dispose(); } @Override public void createControl(Composite parent) { super.createControl(parent); final TreeViewer viewer = getTreeViewer(); viewer.setContentProvider(new TemplateOutlineContentProvider()); viewer.setLabelProvider(new TemplateOutlineLabelProvider()); viewer.addSelectionChangedListener(this); viewer.setAutoExpandLevel(2); viewer.addOpenListener(new IOpenListener() { @Override public void open(OpenEvent event) { TemplateOutlineNode selectedNode = (TemplateOutlineNode)((StructuredSelection)event.getSelection()).getFirstElement(); JsonLocation startLocation = selectedNode.getNode().getStartLocation(); JsonLocation endLocation = selectedNode.getNode().getEndLocation(); IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if (activeEditor != null) { TemplateEditor templateEditor = (TemplateEditor)activeEditor; templateEditor.setHighlightRange( (int)startLocation.getCharOffset(), (int)endLocation.getCharOffset() - (int)startLocation.getCharOffset(), true); } } }); document.addTemplateDocumentListener(this); updateContent(); } // TODO: move/rename me private Set<String> expandedPaths = new HashSet<>(); private void updateContent() { TreeViewer viewer = getTreeViewer(); if (document.getModel() == null) return; expandedPaths = new HashSet<>(); for (Object obj : viewer.getExpandedElements()) { TemplateOutlineNode expandedNode = (TemplateOutlineNode)obj; expandedPaths.add(expandedNode.getNode().getPath()); } viewer.setInput(new TemplateOutlineNode("ROOT", document.getModel())); for (TreeItem treeItem : viewer.getTree().getItems()) { expandTreeItems(treeItem, expandedPaths); } } private void expandTreeItems(TreeItem treeItem, Set<String> paths) { TemplateOutlineNode node = (TemplateOutlineNode)treeItem.getData(); if (node == null) return; if (paths.contains(node.getNode().getPath())) { getTreeViewer().setExpandedState(node, true); getTreeViewer().refresh(node, true); } for (TreeItem child : treeItem.getItems()) { expandTreeItems(child, paths); } } public class TemplateOutlineLabelProvider implements ILabelProvider { @Override public void dispose() {} @Override public void addListener(ILabelProviderListener listener) {} @Override public void removeListener(ILabelProviderListener listener) {} @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public Image getImage(Object element) { return null; } @Override public String getText(Object element) { if (element instanceof TemplateOutlineNode == false) return null; TemplateOutlineNode node = (TemplateOutlineNode)element; return node.getText(); } } public class TemplateOutlineNode { private final String text; private TemplateNode node; public TemplateOutlineNode(String text, TemplateNode node) { this.text = text; this.node = node; } @Override public boolean equals(Object arg0) { if (arg0 instanceof TemplateOutlineNode == false) return false; TemplateOutlineNode other = (TemplateOutlineNode)arg0; return (other.getNode().equals(node)); } public TemplateNode getNode() { return node; } @Override public int hashCode() { if (node == null) { return 0; } return node.hashCode(); } public String getText() { return text; } public TemplateOutlineNode[] getChildren() { if (node == null) return new TemplateOutlineNode[0]; List<TemplateOutlineNode> children = new ArrayList<>(); if (node instanceof TemplateObjectNode) { TemplateObjectNode object = (TemplateObjectNode)node; for (Entry<String, TemplateNode> entry : object.getFields()) { if (entry.getValue() instanceof TemplateValueNode) { children.add(new TemplateOutlineNode(entry.getKey() + ": " + ((TemplateValueNode)entry.getValue()).getText(), entry.getValue())); } else { children.add(new TemplateOutlineNode(entry.getKey(), entry.getValue())); } } } else if (node instanceof TemplateArrayNode) { TemplateArrayNode array = (TemplateArrayNode)node; for (TemplateNode node : array.getMembers()) { if (node instanceof TemplateObjectNode) children.add(new TemplateOutlineNode("{Object}", node)); if (node instanceof TemplateArrayNode) children.add(new TemplateOutlineNode("{Array}", node)); if (node instanceof TemplateValueNode) children.add(new TemplateOutlineNode(((TemplateValueNode)node).getText(), node)); } } return children.toArray(new TemplateOutlineNode[0]); } } public class TemplateOutlineContentProvider implements ITreeContentProvider { @Override public void dispose() {} private TemplateOutlineNode root; @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput == null) { root = null; } else if (newInput instanceof TemplateOutlineNode) { root = (TemplateOutlineNode)newInput; } else if (newInput instanceof TemplateObjectNode) { root = new TemplateOutlineNode("ROOT/", (TemplateObjectNode)newInput); } else { throw new RuntimeException("Unexpected input!!!"); } } @Override public Object[] getElements(Object inputElement) { return getChildren(inputElement); } @Override public Object[] getChildren(Object parentElement) { if (root == null) return new Object[0]; if (parentElement instanceof TemplateOutlineNode) { return ((TemplateOutlineNode)parentElement).getChildren(); } return null; } @Override public Object getParent(Object element) { return null; } @Override public boolean hasChildren(Object element) { if (element instanceof TemplateOutlineNode) { return ((TemplateOutlineNode) element).getChildren().length > 0; } else { return false; } } } @Override public void onTemplateDocumentChanged() { updateContent(); } }
8,101
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateReconcilingStrategy.java
/* * Copyright 2012 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.cloudformation.templates.editor; import java.util.Iterator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.reconciler.DirtyRegion; import org.eclipse.jface.text.reconciler.IReconcilingStrategy; import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.ISourceViewer; import com.amazonaws.eclipse.cloudformation.templates.TemplateNodeParser; import com.fasterxml.jackson.core.JsonParseException; public class TemplateReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension { private IDocument document; private IProgressMonitor monitor; private final ISourceViewer sourceViewer; public TemplateReconcilingStrategy(ISourceViewer sourceViewer) { this.sourceViewer = sourceViewer; } @Override public void setDocument(IDocument document) { this.document = document; } @Override public void reconcile(IRegion partition) { reconcile(); } @Override public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { reconcile(); } /** * Reconciles the Json document extracted from the Json Editor. */ private void reconcile() { TemplateDocument templateDocument = (TemplateDocument) this.document; TemplateNodeParser parser = new TemplateNodeParser(); parser.parse(templateDocument); if (parser.getJsonParseException() != null) { Exception e = parser.getJsonParseException(); if (e instanceof JsonParseException) { JsonParseException jpe = (JsonParseException) e; IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); if (annotationModel != null) { Annotation annotation = new Annotation("org.eclipse.ui.workbench.texteditor.error", true, jpe.getMessage()); annotationModel.addAnnotation(annotation, new Position((int)jpe.getLocation().getCharOffset(), 10)); } else { throw new RuntimeException("No AnnotationModel configured"); } } } else { removeAllAnnotations(); } if (monitor != null) monitor.done(); } /** Clears all annotations from the annotation model. */ private void removeAllAnnotations() { IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); if (annotationModel == null) return; Iterator<?> annotationIterator = annotationModel.getAnnotationIterator(); while (annotationIterator.hasNext()) { Annotation annotation = (Annotation)annotationIterator.next(); annotationModel.removeAnnotation(annotation); } } @Override public void setProgressMonitor(IProgressMonitor monitor) { this.monitor = monitor; } @Override public void initialReconcile() { reconcile(); } }
8,102
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateScanner.java
/* * Copyright 2012 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.cloudformation.templates.editor; import static com.amazonaws.eclipse.cloudformation.preferences.EditorPreferences.TokenPreference.buildTemplateToken; import static com.amazonaws.eclipse.cloudformation.preferences.TemplateTokenPreferenceNames.INTRINSIC_FUNCTION; import static com.amazonaws.eclipse.cloudformation.preferences.TemplateTokenPreferenceNames.KEY; import static com.amazonaws.eclipse.cloudformation.preferences.TemplateTokenPreferenceNames.PSEUDO_PARAMETER; import static com.amazonaws.eclipse.cloudformation.preferences.TemplateTokenPreferenceNames.RESOURCE_TYPE; import static com.amazonaws.eclipse.cloudformation.preferences.TemplateTokenPreferenceNames.VALUE; import java.util.HashSet; import java.util.Set; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.rules.ICharacterScanner; import org.eclipse.jface.text.rules.IRule; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.IWhitespaceDetector; import org.eclipse.jface.text.rules.IWordDetector; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.rules.Token; import org.eclipse.jface.text.rules.WhitespaceRule; import org.eclipse.jface.text.rules.WordRule; import com.amazonaws.eclipse.cloudformation.templates.schema.IntrinsicFunction; import com.amazonaws.eclipse.cloudformation.templates.schema.PseudoParameter; import com.amazonaws.eclipse.cloudformation.templates.schema.TemplateSchemaRules; public class TemplateScanner extends RuleBasedScanner { private final IPreferenceStore preferenceStore; private final Token INTRINSIC_FUNCTION_TOKEN; private final Token PSEUDO_PARAMETER_TOKEN; private final Token RESOURCE_TYPE_TOKEN; private final Token KEY_TOKEN; private final Token VALUE_TOKEN; private static final class TemplateWordDetector implements IWordDetector { private static final Set<Character> SYMBOLS = new HashSet<>(); static { SYMBOLS.add('['); SYMBOLS.add(']'); SYMBOLS.add('{'); SYMBOLS.add('}'); SYMBOLS.add(','); SYMBOLS.add(':'); SYMBOLS.add('"'); SYMBOLS.add('\''); } @Override public boolean isWordStart(char c) { if (Character.isWhitespace(c)) return false; if (SYMBOLS.contains(c)) return false; return true; } @Override public boolean isWordPart(char c) { if (Character.isWhitespace(c)) return false; // TODO: This one symbol isn't valid for a word start, // but is valid for a word part if (c == ':') return true; if (SYMBOLS.contains(c)) return false; return true; } } private static class TemplateWhitespaceDetector implements IWhitespaceDetector { @Override public boolean isWhitespace(char c) { return Character.isWhitespace(c); } } private static class TemplateWordRule extends WordRule { private final IToken keyToken; public TemplateWordRule(TemplateWordDetector templateWordDetector, IToken keyToken, IToken valueToken, boolean b) { super(templateWordDetector, valueToken, b); this.keyToken = keyToken; } @Override public IToken evaluate(ICharacterScanner scanner) { IToken token = super.evaluate(scanner); if (token == this.fDefaultToken) { int c = scanner.read(); int readAhead = 1; while (c == '"' || c != ICharacterScanner.EOF && Character.isWhitespace((char)c)) { c = scanner.read(); readAhead++; } for (int i = 0; i < readAhead; i++) scanner.unread(); if (c == ':') return keyToken; } return token; } } public TemplateScanner(IPreferenceStore store) { preferenceStore = store; INTRINSIC_FUNCTION_TOKEN = new Token(buildTemplateToken(preferenceStore, INTRINSIC_FUNCTION).toTextAttribute()); PSEUDO_PARAMETER_TOKEN = new Token(buildTemplateToken(preferenceStore, PSEUDO_PARAMETER).toTextAttribute()); RESOURCE_TYPE_TOKEN = new Token(buildTemplateToken(preferenceStore, RESOURCE_TYPE).toTextAttribute()); KEY_TOKEN = new Token(buildTemplateToken(preferenceStore, KEY).toTextAttribute()); VALUE_TOKEN = new Token(buildTemplateToken(preferenceStore, VALUE).toTextAttribute()); // TODO: Can we really ignore case for CloudFormation templates? WhitespaceRule whitespaceRule = new WhitespaceRule(new TemplateWhitespaceDetector()); TemplateWordRule templateWordRule = new TemplateWordRule(new TemplateWordDetector(), KEY_TOKEN, VALUE_TOKEN, true); TemplateSchemaRules schemaRules = TemplateSchemaRules.getInstance(); for (PseudoParameter pseudoParameter : schemaRules.getPseudoParameters()) { templateWordRule.addWord(pseudoParameter.getName(), PSEUDO_PARAMETER_TOKEN); } for (IntrinsicFunction intrinsicFunction : schemaRules.getIntrinsicFuntions()) { templateWordRule.addWord(intrinsicFunction.getName(), INTRINSIC_FUNCTION_TOKEN); } for (String resourceType : schemaRules.getResourceTypeNames()) { templateWordRule.addWord(resourceType, RESOURCE_TYPE_TOKEN); } setRules(new IRule[] { whitespaceRule, templateWordRule }); } public void resetTokens() { KEY_TOKEN.setData(buildTemplateToken(preferenceStore, KEY).toTextAttribute()); VALUE_TOKEN.setData(buildTemplateToken(preferenceStore, VALUE).toTextAttribute()); INTRINSIC_FUNCTION_TOKEN.setData(buildTemplateToken(preferenceStore, INTRINSIC_FUNCTION).toTextAttribute()); PSEUDO_PARAMETER_TOKEN.setData(buildTemplateToken(preferenceStore, PSEUDO_PARAMETER).toTextAttribute()); RESOURCE_TYPE_TOKEN.setData(buildTemplateToken(preferenceStore, RESOURCE_TYPE).toTextAttribute()); } public void dispose() {} }
8,103
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateEditor.java
/* * Copyright 2012 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.cloudformation.templates.editor; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension3; import org.eclipse.jface.text.source.DefaultCharacterPairMatcher; import org.eclipse.jface.text.source.ICharacterPairMatcher; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.editors.text.FileDocumentProvider; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.ide.FileStoreEditorInput; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin; import com.amazonaws.eclipse.cloudformation.preferences.TemplateTokenPreferenceNames; public class TemplateEditor extends TextEditor { //TODO put to preference page. public final static String EDITOR_MATCHING_BRACKETS = "com.amazonaws.cloudformation.matchingBrackets"; public final static String EDITOR_MATCHING_BRACKETS_COLOR= "com.amazonaws.cloudformation.matchingBracketsColor"; private final class TemplateDocumentProvider extends FileDocumentProvider { @Override protected IDocument createEmptyDocument() { return new TemplateDocument(); } } private IDocumentProvider createDocumentProvider(IEditorInput input) { if (input instanceof IFileEditorInput) { return new TemplateDocumentProvider(); } else if (input instanceof FileStoreEditorInput) { String message = "Unable to open templates from outside the workspace. Copy it into a workspace project first."; CloudFormationPlugin.getDefault().reportException(message, null); throw new RuntimeException(message); } else { return new TemplateDocumentProvider(); } } @Override protected void doSetInput(IEditorInput input) throws CoreException { setDocumentProvider(createDocumentProvider(input)); super.doSetInput(input); } @Override protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { super.configureSourceViewerDecorationSupport(support); char[] matchChars = {'(', ')', '[', ']', '{', '}'}; //which brackets to match ICharacterPairMatcher matcher = new DefaultCharacterPairMatcher(matchChars , IDocumentExtension3.DEFAULT_PARTITIONING); support.setCharacterPairMatcher(matcher); support.setMatchingCharacterPainterPreferenceKeys( EDITOR_MATCHING_BRACKETS, EDITOR_MATCHING_BRACKETS_COLOR); //Enable bracket highlighting in the preference store IPreferenceStore store = getPreferenceStore(); store.setDefault(EDITOR_MATCHING_BRACKETS, true); store.setDefault(EDITOR_MATCHING_BRACKETS_COLOR, "128,128,128"); } @Override protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer == null) { return; } ((TemplateSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChange(event); } finally { super.handlePreferenceStoreChanged(event); } } private TemplateContentOutlinePage myOutlinePage; public TemplateEditor() { setPreferenceStore(CloudFormationPlugin.getDefault().getPreferenceStore()); setSourceViewerConfiguration(new TemplateSourceViewerConfiguration()); } public TemplateDocument getTemplateDocument() { return (TemplateDocument)this.getDocumentProvider().getDocument(getEditorInput()); } /** * Returns true if the property change affects text presentation, so that the viewer could invalidate immediately. */ @Override protected boolean affectsTextPresentation(PropertyChangeEvent event) { return TemplateTokenPreferenceNames.isCloudFormationEditorProperty(event.getProperty()); } @Override public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { if (myOutlinePage == null) { TemplateDocument document = (TemplateDocument)this.getDocumentProvider().getDocument(getEditorInput()); if (document != null) { myOutlinePage = new TemplateContentOutlinePage(document); } } return myOutlinePage; } return super.getAdapter(required); } }
8,104
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/DocumentUtils.java
/* * Copyright 2013 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.cloudformation.templates.editor; import java.util.Stack; import org.eclipse.jface.text.BadLocationException; /** * Common utilities for searching through documents. */ public class DocumentUtils { /** * Starting at the given position in the specified document, this method * reads over chars until it finds a non-whitespace char and returns that * char. Return null if none is found. * * @param document * The document to search in. * @param position * The offset in the document to start searching at. * * @return The first non-whitespace char found after the specified position * in the document. */ public static Character readToNextChar(TemplateDocument document, int position) { try { while (true) { char c = document.getChar(position++); if (Character.isWhitespace(c)) continue; return c; } } catch (BadLocationException e) { return null; } } /** * Reads chars backwards, starting at the specified position in the * document, until it finds the first unmatched open brace (i.e. '[' or * '{'). If closed braces are found, they are pushed on a stack, so that the * nested opening brace matching that one is *not* returned. This method is * used to find the opening brace for the array or map that contains the * specified position. * * @param document * The document to search in. * @param position * The offset in the document to start searching at. * * @return The first unmatched open brace, which indicates the map or array * that contains the specified position. */ public static Character readToPreviousUnmatchedOpenBrace(TemplateDocument document, int position) { try { Stack<Character> stack = new Stack<>(); position--; while (true) { char c = document.getChar(position--); if (Character.isWhitespace(c)) continue; if (c == '}' || c == ']') { stack.push(c); } else if (c == '{' || c == '[') { if (stack.isEmpty()) return c; // Just assume the braces are nested correctly stack.pop(); } } } catch (BadLocationException e) { return null; } } /** * Searches the specified document, backwards, starting from the specified * position, looking for the first occurrence of the target character, and * returns the document position of that first occurrence. return -1 if none * is found. * * @param document * The document to search in. * @param position * The offset in the document to start searching at. * @param charToFind * The character being searched for. * * @return The document position of the first occurrence of the specified * target character, occurring before the specified starting * position in the document. */ public static int findPreviousCharPosition(TemplateDocument document, int position, char charToFind) { try { while (true) { position--; if (charToFind == document.getChar(position)) return position; } } catch (BadLocationException e) { return -1; } } /** * Searches the document backwards, starting at the specified position, * looking for the first non-whitespace character, and returns that * character. Return null if none is found. * * @param document * The document to search in. * @param position * The offset in the document to start searching at. * * @return The first non-whitespace character that occurs before the * specified position in the document. */ public static Character readToPreviousChar(TemplateDocument document, int position) { try { position--; while (true) { char c = document.getChar(position--); if (Character.isWhitespace(c)) continue; return c; } } catch (BadLocationException e) { return null; } } /** * Reads a string backwards from the current offset position to first * occurrence of a double quote. Return null if none is found or a new line is found. * * @param document * The document to search in. * @param position * The offset in the document to start searching at. * @return The string from the specified position to the first occurrence of * double quote. */ public static String readToPreviousQuote(TemplateDocument document, int position) { StringBuilder typedString = new StringBuilder(); char c; try { position--; while (true) { c = document.getChar(position--); if (c == '"') { break; } else if (c == '\n' || c == '\r') { return null; } typedString.append(c); } } catch (BadLocationException e) { return null; } return typedString.reverse().toString(); } }
8,105
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/validators/TemplateParameterValidators.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.cloudformation.validators; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; /** * A set of {@link #org.eclipse.core.databinding.validation.IValidator} for validating AWS CloudFormation template parameters. */ public class TemplateParameterValidators { public static IValidator newPatternValidator(final Pattern pattern, final String errorMessage) { return new IValidator() { @Override public IStatus validate(Object value) { Matcher matcher = pattern.matcher((CharSequence) value); if ( matcher.matches() ) { return ValidationStatus.ok(); } else { return ValidationStatus.error(errorMessage); } } }; } public static IValidator newMaxLengthValidator(final int maxLength, final String fieldName) { return new IValidator() { @Override public IStatus validate(Object value) { if ( ((String) value).length() > maxLength ) { return ValidationStatus.error(fieldName + " must be at most " + maxLength + " characters long"); } else { return ValidationStatus.ok(); } } }; } public static IValidator newMinLengthValidator(final int minLength, final String fieldName) { return new IValidator() { @Override public IStatus validate(Object value) { if ( ((String) value).length() < minLength ) { return ValidationStatus.error(fieldName + " must be at least " + minLength + " characters long"); } else { return ValidationStatus.ok(); } } }; } public static IValidator newMinValueValidator(final int minValue, final String fieldName) { return new IValidator() { @Override public IStatus validate(Object value) { String string = (String) value; try { if ( Integer.parseInt(string) < minValue ) { return ValidationStatus.error(fieldName + " must be at least " + minValue); } else { return ValidationStatus.ok(); } } catch ( Exception e ) { return ValidationStatus.error(fieldName + " must be at least " + minValue); } } }; } public static IValidator newMaxValueValidator(final int maxValue, final String fieldName) { return new IValidator() { @Override public IStatus validate(Object value) { String string = (String) value; try { if ( Integer.parseInt(string) > maxValue ) { return ValidationStatus.error(fieldName + " must be at most " + maxValue); } else { return ValidationStatus.ok(); } } catch ( Exception e ) { return ValidationStatus.error(fieldName + " must be at most " + maxValue); } } }; } }
8,106
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/UrlConstants.java
package com.amazonaws.eclipse.opsworks; import com.amazonaws.eclipse.core.ui.WebLinkListener; public class UrlConstants { public static final String OPSWORKS_CONSOLE_URL = "http://console.aws.amazon.com/opsworks"; public static final WebLinkListener webLinkListener = new WebLinkListener(); }
8,107
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/ServiceAPIUtils.java
package com.amazonaws.eclipse.opsworks; import java.util.LinkedList; import java.util.List; import com.amazonaws.services.opsworks.AWSOpsWorks; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.DescribeAppsRequest; import com.amazonaws.services.opsworks.model.DescribeInstancesRequest; import com.amazonaws.services.opsworks.model.DescribeLayersRequest; import com.amazonaws.services.opsworks.model.DescribeStacksRequest; import com.amazonaws.services.opsworks.model.Instance; import com.amazonaws.services.opsworks.model.Layer; import com.amazonaws.services.opsworks.model.Stack; public class ServiceAPIUtils { public static List<Stack> getAllStacks(AWSOpsWorks client) { return client.describeStacks(new DescribeStacksRequest()) .getStacks(); } public static List<Layer> getAllLayersInStack(AWSOpsWorks client, String stackId) { return client.describeLayers( new DescribeLayersRequest().withStackId(stackId)) .getLayers(); } public static List<Instance> getAllInstancesInStack(AWSOpsWorks client, String stackId) { return client.describeInstances( new DescribeInstancesRequest().withStackId(stackId)) .getInstances(); } public static List<Instance> getAllInstancesInLayer(AWSOpsWorks client, String layerId) { return client.describeInstances( new DescribeInstancesRequest().withLayerId(layerId)) .getInstances(); } public static List<App> getAllAppsInStack(AWSOpsWorks client, String stackId) { return client.describeApps( new DescribeAppsRequest().withStackId(stackId)) .getApps(); } public static List<App> getAllJavaAppsInStack(AWSOpsWorks client, String stackId) { List<App> allJavaApps = new LinkedList<>(); for (App app : getAllAppsInStack(client, stackId)) { if ("java".equalsIgnoreCase(app.getType())) { allJavaApps.add(app); } } return allJavaApps; } }
8,108
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/OpsWorksPlugin.java
package com.amazonaws.eclipse.opsworks; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.IStartup; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.opsworks.explorer.image.OpsWorksExplorerImages; public class OpsWorksPlugin extends AbstractUIPlugin implements IStartup { public static final String PLUGIN_ID = "com.amazonaws.eclipse.opsworks"; public static final String DEFAULT_REGION = "us-east-1"; private static OpsWorksPlugin plugin; @Override public void earlyStartup() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } @Override protected ImageRegistry createImageRegistry() { return OpsWorksExplorerImages.createImageRegistry(); } /** * Returns the shared plugin instance. * * @return the shared plugin instance. */ public static OpsWorksPlugin getDefault() { return plugin; } /** * Convenience method for reporting the exception to StatusManager */ public void reportException(String errorMessage, Throwable e) { StatusManager.getManager().handle( new Status(IStatus.ERROR, PLUGIN_ID, errorMessage, e), StatusManager.SHOW | StatusManager.LOG); } /** * Convenience method for logging a debug message at INFO level. */ public void logInfo(String debugMessage) { getLog().log(new Status(Status.INFO, PLUGIN_ID, debugMessage, null)); } }
8,109
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/handler/DeployProjectToOpsworksHandler.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.opsworks.deploy.handler; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.handlers.HandlerUtil; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.deploy.wizard.DeployProjectToOpsworksWizard; public class DeployProjectToOpsworksHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) .getActivePage().getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structurredSelection = (IStructuredSelection)selection; Object firstSeleciton = structurredSelection.getFirstElement(); if (firstSeleciton instanceof IProject) { IProject selectedProject = (IProject) firstSeleciton; try { WizardDialog wizardDialog = new WizardDialog( Display.getCurrent().getActiveShell(), new DeployProjectToOpsworksWizard(selectedProject)); wizardDialog.setMinimumPageSize(0, 600); wizardDialog.open(); } catch (Exception e) { OpsWorksPlugin.getDefault().reportException( "Failed to launch deployment wizard.", e); } } else { OpsWorksPlugin.getDefault().logInfo( "Invalid selection: " + firstSeleciton + " is not a project."); } } return null; } }
8,110
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/util/WTPWarUtils.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.opsworks.deploy.util; import java.io.File; import java.io.IOException; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jst.j2ee.datamodel.properties.IJ2EEComponentExportDataModelProperties; import org.eclipse.jst.j2ee.internal.web.archive.operations.WebComponentExportDataModelProvider; import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; /** * Utilities for exporting Web Tools Platform Java web application projects to * WAR files. */ public class WTPWarUtils { public static IPath exportProjectToWar(IProject project, IPath directory) { File tempFile; try { tempFile = File.createTempFile("aws-eclipse-", ".war", directory.toFile()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Unable to create web application archive: " + e.getMessage(), e); } return exportProjectToWar(project, directory, tempFile.getName()); } public static IPath exportProjectToWar(IProject project, IPath directory, String fileName) { IDataModel dataModel = DataModelFactory.createDataModel(new WebComponentExportDataModelProvider()); if (directory.toFile().exists() == false) { if (directory.toFile().mkdirs() == false) { throw new RuntimeException("Unable to create temp directory for web application archive."); } } String filename = new File(directory.toFile(), fileName).getAbsolutePath(); dataModel.setProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION, filename); dataModel.setProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, project.getName()); try { IDataModelOperation operation = dataModel.getDefaultOperation(); operation.execute(new NullProgressMonitor(), null); } catch (ExecutionException e) { // TODO: better error handling e.printStackTrace(); throw new RuntimeException("Unable to create web application archive: " + e.getMessage(), e); } return new Path(filename); } }
8,111
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/util/ZipUtils.java
package com.amazonaws.eclipse.opsworks.deploy.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; public class ZipUtils { public static void createZipFileOfDirectory(File srcDir, File zipOutput) throws IOException { if ( !srcDir.exists() || !srcDir.isDirectory() ) { throw new IllegalArgumentException( srcDir.getAbsolutePath() + " is not a directory!"); } if ( zipOutput.exists() && !zipOutput.isFile() ) { throw new IllegalArgumentException( zipOutput.getAbsolutePath() + " exists but is not a file!"); } ZipOutputStream zipOutputStream = null; String baseName = srcDir.getAbsolutePath() + File.pathSeparator; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutput)); addDirToZip(srcDir, zipOutputStream, baseName); } finally { IOUtils.closeQuietly(zipOutputStream); } } public static void unzipFileToDirectory(File zipFile, File targetDirectory) throws IOException { if ( !zipFile.exists() || !zipFile.isFile() ) { throw new IllegalArgumentException( zipFile.getAbsolutePath() + " is not a file!"); } if ( !targetDirectory.exists() || !targetDirectory.isDirectory() ) { throw new IllegalArgumentException( targetDirectory.getAbsolutePath() + " is not a directory!"); } if ( targetDirectory.listFiles().length != 0 ) { throw new IllegalArgumentException( targetDirectory.getAbsolutePath() + " is not empty!"); } ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String entryFileName = zipEntry.getName(); File newFile = new File(targetDirectory, entryFileName); if (!newFile.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath())) { throw new RuntimeException(newFile.getAbsolutePath() + " is outside of targetDirectory: " + targetDirectory.getAbsolutePath()); } if (zipEntry.isDirectory()) { if ( !newFile.exists() ) { newFile.mkdirs(); } else if ( !newFile.isDirectory() ) { throw new RuntimeException(newFile.getAbsolutePath() + " already exists and is not a directory!"); } } else { // File entry might be visited before its parent folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); try { IOUtils.copy(zis, fos); } finally { IOUtils.closeQuietly(fos); } } zipEntry = zis.getNextEntry(); } zis.closeEntry(); IOUtils.closeQuietly(zis); } private static void addDirToZip(File dir, ZipOutputStream zip, String baseName) throws IOException { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { addDirToZip(file, zip, baseName); } else { String entryName = file.getAbsolutePath().substring( baseName.length()); ZipEntry zipEntry = new ZipEntry(entryName); zip.putNextEntry(zipEntry); FileInputStream fileInput = new FileInputStream(file); try { IOUtils.copy(fileInput, zip); zip.closeEntry(); } finally { IOUtils.closeQuietly(fileInput); } } } } }
8,112
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/util/DeployUtils.java
package com.amazonaws.eclipse.opsworks.deploy.util; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.UUID; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel; import com.amazonaws.services.opsworks.AWSOpsWorks; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.AppType; import com.amazonaws.services.opsworks.model.CreateAppRequest; import com.amazonaws.services.opsworks.model.CreateDeploymentRequest; import com.amazonaws.services.opsworks.model.CreateDeploymentResult; import com.amazonaws.services.opsworks.model.DeploymentCommand; import com.amazonaws.services.opsworks.model.DeploymentCommandName; import com.amazonaws.services.opsworks.model.DescribeAppsRequest; import com.amazonaws.services.opsworks.model.EnvironmentVariable; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.PutObjectRequest; public class DeployUtils { public static File repackWarFileToZipFile(File warFile) throws IOException { File unpackDir = createTempDirectory(); File zipFile = File.createTempFile("eclipse-opsworks-content-zip-", null); // Unpack the .war file to the temp directory unpackWarFile(warFile, unpackDir); // Zip it ZipUtils.createZipFileOfDirectory(unpackDir, zipFile); return zipFile; } private static void unpackWarFile(File warFile, File targetDir) throws IOException { // Just treat the .war file as a zip file ZipUtils.unzipFileToDirectory(warFile, targetDir); } private static File createTempDirectory() throws IOException { File tempDir = File.createTempFile("eclipse-opsworks-deployment-content-dir-", null); if ( !tempDir.delete() ) { throw new RuntimeException("Could not delete temp file: " + tempDir.getAbsolutePath()); } if ( !tempDir.mkdirs() ) { throw new RuntimeException("Could not create temp directory: " + tempDir.getAbsolutePath()); } return tempDir; } /** * @return the deployment ID */ public static String runDeployment( DeployProjectToOpsworksWizardDataModel dataModel, IProgressMonitor progressMonitor) { OpsWorksPlugin.getDefault().logInfo( "Preparing for deployment: " + dataModel.toString()); /* * (1) Create a new OpsWorks app if necessary */ App targetApp = null; if (dataModel.getIsCreatingNewJavaApp()) { progressMonitor.subTask(String.format( "Create new Java app [%s]...", dataModel.getNewJavaAppName())); OpsWorksPlugin.getDefault().logInfo( "Making CreateApp API call..."); String endpoint = dataModel.getRegion().getServiceEndpoints() .get(ServiceAbbreviations.OPSWORKS); AWSOpsWorks client = AwsToolkitCore.getClientFactory() .getOpsWorksClientByEndpoint(endpoint); CreateAppRequest createAppRequest = new CreateAppRequest() .withName(dataModel.getNewJavaAppName()) .withStackId(dataModel.getExistingStack().getStackId()) .withType(AppType.Java) .withAppSource(dataModel.getS3ApplicationSource().toGenericSource()) .withEnableSsl(dataModel.isEnableSsl()); if (dataModel.getCustomDomains() != null && !dataModel.getCustomDomains().isEmpty()) { createAppRequest.setDomains(dataModel.getCustomDomains()); } if (dataModel.getEnvironmentVariables() != null && !dataModel.getEnvironmentVariables().isEmpty()) { List<EnvironmentVariable> vars = new LinkedList<>(); for (com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel.EnvironmentVariable envVar : dataModel .getEnvironmentVariables()) { vars.add(envVar.toSdkModel()); } createAppRequest.setEnvironment(vars); } if (dataModel.isEnableSsl()) { createAppRequest.setSslConfiguration(dataModel.getSslConfiguration().toSdkModel()); } String newAppId = client.createApp(createAppRequest) .getAppId(); targetApp = client .describeApps( new DescribeAppsRequest().withAppIds(newAppId)) .getApps().get(0); } else { targetApp = dataModel.getExistingJavaApp(); } progressMonitor.worked(30); /* * (2) Export application archive WAR file */ final IProject project = dataModel.getProject(); String uuid = UUID.randomUUID().toString(); String tempDirName = targetApp.getShortname() + "-" + uuid + "-deployment-dir"; File tempDir = new File( new File(System.getProperty("java.io.tmpdir")), tempDirName); File archiveContentDir = new File( tempDir, "archive-content"); progressMonitor.subTask("Export project to WAR file..."); OpsWorksPlugin.getDefault().logInfo( "Preparing to export project [" + project.getName() + "] to a WAR file [" + new File(archiveContentDir, "archive.war").getAbsolutePath() + "]."); File warFile = WTPWarUtils.exportProjectToWar( project, new Path(archiveContentDir.getAbsolutePath()), "archive.war").toFile(); OpsWorksPlugin.getDefault().logInfo( "WAR file created at [" + warFile.getAbsolutePath() + "]"); progressMonitor.worked(10); progressMonitor.subTask("Repackage the war file..."); /* * https://forums.aws.amazon.com/thread.jspa?messageID=557948&tstart=0 */ File zipArchive = null; try { zipArchive = repackWarFileToZipFile(warFile); } catch (IOException e) { OpsWorksPlugin.getDefault().reportException( "Error when packaging the web application into zip archive.", e); } progressMonitor.worked(5); /* * (3) Upload to S3 */ String bucketName = dataModel.getS3ApplicationSource().getBucketName(); String keyName = dataModel.getS3ApplicationSource().getKeyName(); AmazonS3 s3Client = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucketName); progressMonitor.subTask("Upload ZIP file to S3..."); OpsWorksPlugin.getDefault().logInfo( "Uploading zip file to S3 bucket [" + bucketName + "]."); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, zipArchive); if (dataModel.getS3ApplicationSource().isAsPublicHttpArchive()) { putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead); } s3Client.putObject(putObjectRequest); OpsWorksPlugin.getDefault().logInfo( "Upload succeed. [s3://" + bucketName + "/" + keyName + "]"); progressMonitor.worked(35); /* * (4) CreateDeployment */ progressMonitor.subTask("Initiate deployment..."); OpsWorksPlugin.getDefault().logInfo( "Making CreateDeployment API call..."); String endpoint = dataModel.getRegion().getServiceEndpoints() .get(ServiceAbbreviations.OPSWORKS); AWSOpsWorks client = AwsToolkitCore.getClientFactory() .getOpsWorksClientByEndpoint(endpoint); CreateDeploymentRequest createDeploymentRequest = new CreateDeploymentRequest() .withStackId(dataModel.getExistingStack().getStackId()) .withAppId(targetApp.getAppId()) .withCommand(new DeploymentCommand().withName(DeploymentCommandName.Deploy)); if (dataModel.getDeployComment() != null && !dataModel.getDeployComment().isEmpty()) { createDeploymentRequest.setComment(dataModel.getDeployComment()); } if (dataModel.getCustomChefJson() != null && !dataModel.getCustomChefJson().isEmpty()) { createDeploymentRequest.setCustomJson(dataModel.getCustomChefJson()); } CreateDeploymentResult result = client.createDeployment(createDeploymentRequest); OpsWorksPlugin.getDefault().logInfo( "Deployment submitted. Deployment ID [" + result.getDeploymentId() + "]"); progressMonitor.worked(20); return result.getDeploymentId(); } }
8,113
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/DeployProjectToOpsworksWizard.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.opsworks.deploy.wizard; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.deploy.util.DeployUtils; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel; import com.amazonaws.eclipse.opsworks.deploy.wizard.page.AppConfigurationPage; import com.amazonaws.eclipse.opsworks.deploy.wizard.page.DeploymentActionConfigurationPage; import com.amazonaws.eclipse.opsworks.deploy.wizard.page.TargetAppSelectionPage; import com.amazonaws.services.opsworks.AWSOpsWorks; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.Deployment; import com.amazonaws.services.opsworks.model.DescribeAppsRequest; import com.amazonaws.services.opsworks.model.DescribeDeploymentsRequest; public class DeployProjectToOpsworksWizard extends Wizard { private final DeployProjectToOpsworksWizardDataModel dataModel; public DeployProjectToOpsworksWizard(IProject project) { dataModel = new DeployProjectToOpsworksWizardDataModel(project); setNeedsProgressMonitor(true); } @Override public void addPages() { addPage(new TargetAppSelectionPage(dataModel)); addPage(new AppConfigurationPage(dataModel)); addPage(new DeploymentActionConfigurationPage(dataModel)); } @Override public boolean performFinish() { try { getContainer().run(true, false, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Deploying local project [" + dataModel.getProject().getName() + "] to OpsWorks", 110); final String deploymentId = DeployUtils.runDeployment(dataModel, monitor); // Open deployment progress tracker (10/110) monitor.subTask("Waiting for the deployment to finish..."); Job trackProgressJob = new Job("Waiting for the deployment to finish") { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(String.format( "Waiting deployment [%s] to finish...", deploymentId), IProgressMonitor.UNKNOWN); String endpoint = dataModel.getRegion().getServiceEndpoints() .get(ServiceAbbreviations.OPSWORKS); AWSOpsWorks client = AwsToolkitCore.getClientFactory() .getOpsWorksClientByEndpoint(endpoint); try { final Deployment deployment = waitTillDeploymentFinishes(client, deploymentId, monitor); if ("successful".equalsIgnoreCase(deployment.getStatus())) { final App appDetail = client .describeApps( new DescribeAppsRequest() .withAppIds(deployment .getAppId())) .getApps().get(0); Display.getDefault().syncExec(new Runnable() { @Override public void run() { MessageDialog.openInformation(Display .getDefault().getActiveShell(), "Deployment success", String.format( "Deployment [%s] succeeded (Instance count: %d). " + "The application will be available at %s://{instance-public-endpoint}/%s/", deployment.getDeploymentId(), deployment.getInstanceIds().size(), appDetail.isEnableSsl() ? "https" : "http", appDetail.getShortname())); } }); return ValidationStatus.ok(); } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { MessageDialog.openError(Display .getDefault().getActiveShell(), "Deployment failed", ""); } }); return ValidationStatus.error("The deployment failed."); } } catch (Exception e) { return ValidationStatus.error("Unable to query the progress of the deployment", e); } } private Deployment waitTillDeploymentFinishes( AWSOpsWorks client, String deploymentId, IProgressMonitor monitor) throws InterruptedException { while (true) { Deployment deployment = client .describeDeployments(new DescribeDeploymentsRequest() .withDeploymentIds(deploymentId)) .getDeployments().get(0); monitor.subTask(String.format( "Instance count: %d, Last status: %s", deployment.getInstanceIds().size(), deployment.getStatus())); if ("successful".equalsIgnoreCase(deployment.getStatus()) || "failed".equalsIgnoreCase(deployment.getStatus())) { return deployment; } Thread.sleep(5 * 1000); } } }; trackProgressJob.setUser(true); trackProgressJob.schedule(); monitor.worked(10); monitor.done(); } }); } catch (InvocationTargetException e) { OpsWorksPlugin.getDefault().reportException( "Unexpected error during deployment", e.getCause()); } catch (InterruptedException e) { OpsWorksPlugin.getDefault().reportException( "Unexpected InterruptedException during deployment", e.getCause()); } return true; } }
8,114
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/page/ExistingAppConfigurationReviewComposite.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.S3ApplicationSource; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.EnvironmentVariable; public class ExistingAppConfigurationReviewComposite extends Composite { private final App app; private final S3ApplicationSource parsedS3ApplicationSource; ExistingAppConfigurationReviewComposite(Composite parent, App app) { super(parent, SWT.NONE); this.app = app; parsedS3ApplicationSource = S3ApplicationSource.parse(app.getAppSource()); setLayout(new GridLayout(1, false)); createControls(this); } S3ApplicationSource getParsedS3ApplicationSource() { return parsedS3ApplicationSource; } private void createControls(Composite parent) { createBasicSettingSection(parent); createApplicationSourceSection(parent); createEnvironmentVariablesSection(parent); createCustomDomainsSection(parent); createSslSettingsSection(parent); } private void createBasicSettingSection(Composite parent) { Group settingsGroup = newGroup(parent, "Settings"); settingsGroup.setLayout(new GridLayout(2, true)); newFillingLabel(settingsGroup, "Name").setFont(JFaceResources.getBannerFont()); newFillingLabel(settingsGroup, app.getName()); newFillingLabel(settingsGroup, "Short name").setFont(JFaceResources.getBannerFont()); newFillingLabel(settingsGroup, app.getShortname()); newFillingLabel(settingsGroup, "OpsWorks ID").setFont(JFaceResources.getBannerFont()); newFillingLabel(settingsGroup, app.getAppId()); newFillingLabel(settingsGroup, "Type").setFont(JFaceResources.getBannerFont()); newFillingLabel(settingsGroup, toCamelCase(app.getType())); } private void createApplicationSourceSection(Composite parent) { Group applicationSourceGroup = newGroup(parent, "Application Source"); applicationSourceGroup.setLayout(new GridLayout(2, true)); S3ApplicationSource s3Source = S3ApplicationSource.parse(app.getAppSource()); if (s3Source == null) { newFillingLabel( applicationSourceGroup, String.format("Unrecognized application source %s:[%s]", app.getAppSource().getType(), app.getAppSource().getUrl()), 2); return; } newFillingLabel(applicationSourceGroup, "S3 bucket").setFont(JFaceResources.getBannerFont()); newFillingLabel(applicationSourceGroup, s3Source.getBucketName()); if (s3Source.getRegion() != null) { newFillingLabel(applicationSourceGroup, "Bucket region").setFont(JFaceResources.getBannerFont()); newFillingLabel(applicationSourceGroup, s3Source.getRegion().getName()); } newFillingLabel(applicationSourceGroup, "Key").setFont(JFaceResources.getBannerFont()); newFillingLabel(applicationSourceGroup, s3Source.getKeyName()); } private void createEnvironmentVariablesSection(Composite parent) { Group envVarGroup = newGroup(parent, "Environment Variables"); envVarGroup.setLayout(new GridLayout(2, true)); if (app.getEnvironment() == null || app.getEnvironment().isEmpty()) { newFillingLabel(envVarGroup, "None", 2); } for (EnvironmentVariable envVar : app.getEnvironment()) { newFillingLabel(envVarGroup, envVar.getKey()).setFont(JFaceResources.getBannerFont()); newFillingLabel(envVarGroup, envVar.getValue()); } } private void createCustomDomainsSection(Composite parent) { Group domainsGroup = newGroup(parent, "Custom Domains"); domainsGroup.setLayout(new GridLayout(1, true)); if (app.getDomains() == null || app.getDomains().isEmpty()) { newFillingLabel(domainsGroup, "None"); } for (String domain : app.getDomains()) { newFillingLabel(domainsGroup, domain); } } private void createSslSettingsSection(Composite parent) { Group sslSettingsGroup = newGroup(parent, "SSL Settings"); sslSettingsGroup.setLayout(new GridLayout(2, true)); newFillingLabel(sslSettingsGroup, "SSL enabled").setFont(JFaceResources.getBannerFont()); newFillingLabel(sslSettingsGroup, app.getEnableSsl() ? "Yes" : "No"); if (app.getEnableSsl()) { newFillingLabel(sslSettingsGroup, "SSL certificate").setFont(JFaceResources.getBannerFont()); newFillingLabel(sslSettingsGroup, app.getSslConfiguration().getCertificate()); newFillingLabel(sslSettingsGroup, "SSL certificate key").setFont(JFaceResources.getBannerFont()); newFillingLabel(sslSettingsGroup, app.getSslConfiguration().getPrivateKey()); newFillingLabel(sslSettingsGroup, "SSL certificates of CA").setFont(JFaceResources.getBannerFont()); newFillingLabel(sslSettingsGroup, app.getSslConfiguration().getChain()); } } private static String toCamelCase(String string) { if (string.length() == 0) { return ""; } else if (string.length() == 1) { return string.substring(0, 0).toUpperCase(); } else { return string.substring(0, 1).toUpperCase() + string.substring(1); } } }
8,115
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/page/WizardPageWithOnEnterHook.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.page; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardPage; /** * To emulate onEnter event for JFace wizard page. * http://www.eclipse.org/forums/index.php/t/88927/ */ abstract class WizardPageWithOnEnterHook extends WizardPage { protected WizardPageWithOnEnterHook(String pageName) { super(pageName); } protected abstract void onEnterPage(); @Override public final boolean canFlipToNextPage() { return isPageComplete() && getNextPage(false) != null; } @Override public final IWizardPage getNextPage() { return getNextPage(true); } private IWizardPage getNextPage(boolean aboutToShow) { IWizardPage nextPage = super.getNextPage(); if (aboutToShow && (nextPage instanceof WizardPageWithOnEnterHook)) { ((WizardPageWithOnEnterHook) nextPage).onEnterPage(); } return nextPage; } }
8,116
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/page/NewAppConfigurationComposite.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCheckbox; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newControlDecoration; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newText; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.databinding.BooleanValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel.EnvironmentVariable; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel.SslConfiguration; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.S3ApplicationSource; import com.amazonaws.eclipse.opsworks.explorer.image.OpsWorksExplorerImages; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.Bucket; public class NewAppConfigurationComposite extends Composite { private DeployProjectToOpsworksWizardDataModel dataModel; private final DataBindingContext bindingContext; private final AggregateValidationStatus aggregateValidationStatus; /** * @see #setValidationStatusChangeListener(IChangeListener) * @see #removeValidationStatusChangeListener() */ private IChangeListener validationStatusChangeListener; private IObservableValue bucketNameSelected = new WritableValue(); private ISWTObservableValue bucketNameComboObservable; private ISWTObservableValue keyNameTextObservable; private ISWTObservableValue enableSslCheckBoxObservable; private ISWTObservableValue certTextObservable; private ISWTObservableValue chainTextObservable; private ISWTObservableValue privateKeyTextObservable; private Combo bucketNameCombo; private Text keyNameText; private ControlDecoration keyNameTextDecoration; private Button enableSslCheckBox; private Text certText; private Text chainText; private Text privateKeyText; /* Constants */ private static final String LOADING = "Loading..."; private static final String NONE_FOUND = "None found"; NewAppConfigurationComposite(Composite parent, DeployProjectToOpsworksWizardDataModel dataModel) { super(parent, SWT.NONE); this.dataModel = dataModel; // Clear S3ApplicationSource this.dataModel.setS3ApplicationSource(new S3ApplicationSource()); this.bindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( bindingContext, AggregateValidationStatus.MAX_SEVERITY); setLayout(new GridLayout(1, false)); createControls(this); bindControls(); initializeValidators(); initializeDefaults(); loadS3BucketsAsync(); } /** * Set listener that will be notified whenever the validation status of this * composite is updated. This method removes the listener (if any) that is * currently registered to this composite - only one listener instance is * allowed at a time. */ public synchronized void setValidationStatusChangeListener(IChangeListener listener) { removeValidationStatusChangeListener(); validationStatusChangeListener = listener; aggregateValidationStatus.addChangeListener(listener); } /** * @see #setValidationStatusChangeListener(IChangeListener) */ public synchronized void removeValidationStatusChangeListener() { if (validationStatusChangeListener != null) { aggregateValidationStatus.removeChangeListener(validationStatusChangeListener); validationStatusChangeListener = null; } } public void updateValidationStatus() { Iterator<?> iterator = bindingContext.getBindings().iterator(); while (iterator.hasNext()) { Binding binding = (Binding)iterator.next(); binding.updateTargetToModel(); } } private void createControls(Composite parent) { createBasicSettingSection(parent); createApplicationSourceSection(parent); createEnvironmentVariablesSection(parent); createCustomDomainsSection(parent); createSslSettingsSection(parent); } private void bindControls() { bucketNameComboObservable = SWTObservables .observeSelection(bucketNameCombo); bindingContext.bindValue( bucketNameComboObservable, PojoObservables.observeValue( dataModel.getS3ApplicationSource(), S3ApplicationSource.BUCKET_NAME)); keyNameTextObservable = SWTObservables .observeText(keyNameText, SWT.Modify); bindingContext.bindValue( keyNameTextObservable, PojoObservables.observeValue( dataModel.getS3ApplicationSource(), S3ApplicationSource.KEY_NAME)); enableSslCheckBoxObservable = SWTObservables .observeSelection(enableSslCheckBox); bindingContext.bindValue( enableSslCheckBoxObservable, PojoObservables.observeValue( dataModel, DeployProjectToOpsworksWizardDataModel.ENABLE_SSL)); certTextObservable = SWTObservables .observeText(certText, SWT.Modify); bindingContext.bindValue( certTextObservable, PojoObservables.observeValue( dataModel.getSslConfiguration(), SslConfiguration.CERTIFICATE)); chainTextObservable = SWTObservables .observeText(chainText, SWT.Modify); bindingContext.bindValue( chainTextObservable, PojoObservables.observeValue( dataModel.getSslConfiguration(), SslConfiguration.CHAIN)); privateKeyTextObservable = SWTObservables .observeText(privateKeyText, SWT.Modify); bindingContext.bindValue( privateKeyTextObservable, PojoObservables.observeValue( dataModel.getSslConfiguration(), SslConfiguration.PRIVATE_KEY)); } private void initializeValidators() { bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( bucketNameSelected, new BooleanValidator("Please select a bucket for storing the application source"))); ChainValidator<String> keyNameValidator = new ChainValidator<>( keyNameTextObservable, new NotEmptyValidator("Please provide a valid S3 key name")); bindingContext.addValidationStatusProvider(keyNameValidator); new DecorationChangeListener(keyNameTextDecoration, keyNameValidator.getValidationStatus()); } private void initializeDefaults() { keyNameTextObservable.setValue("archive.zip"); enableSslCheckBoxObservable.setValue(false); certTextObservable.setValue(""); chainTextObservable.setValue(""); privateKeyTextObservable.setValue(""); } private void createBasicSettingSection(Composite parent) { Group settingsGroup = newGroup(parent, "Settings"); settingsGroup.setLayout(new GridLayout(3, true)); newFillingLabel(settingsGroup, "Name").setFont(JFaceResources.getBannerFont()); newFillingLabel(settingsGroup, dataModel.getNewJavaAppName(), 2); newFillingLabel(settingsGroup, "Type").setFont(JFaceResources.getBannerFont()); newFillingLabel(settingsGroup, "Java", 2); } private void createApplicationSourceSection(Composite parent) { Group applicationSourceGroup = newGroup(parent, "Application Source"); applicationSourceGroup.setLayout(new GridLayout(3, true)); newFillingLabel( applicationSourceGroup, "Specify the S3 location where your application source will be stored.", 3); newFillingLabel(applicationSourceGroup, "Bucket name").setFont(JFaceResources.getBannerFont()); bucketNameCombo = newCombo(applicationSourceGroup, 2); bucketNameCombo.setEnabled(false); bucketNameSelected.setValue(false); newFillingLabel(applicationSourceGroup, "Key name").setFont(JFaceResources.getBannerFont()); keyNameText = newText(applicationSourceGroup, "", 2); keyNameTextDecoration = newControlDecoration(keyNameText, "Enter a valid S3 key name"); } private void loadS3BucketsAsync() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { bucketNameCombo.setItems(new String[] {LOADING}); bucketNameCombo.select(0); } }); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { AmazonS3 client = AwsToolkitCore.getClientFactory().getS3Client(); List<Bucket> allBuckets = client.listBuckets(); if (allBuckets.isEmpty()) { bucketNameCombo.setItems(new String[] {NONE_FOUND}); bucketNameSelected.setValue(false); } else { List<String> allBucketNames = new LinkedList<>(); for (Bucket bucket : allBuckets) { allBucketNames.add(bucket.getName()); } bucketNameCombo.setItems(allBucketNames.toArray(new String[allBucketNames.size()])); bucketNameCombo.select(0); bucketNameCombo.setEnabled(true); bucketNameSelected.setValue(true); } } catch (Exception e) { OpsWorksPlugin.getDefault().reportException( "Failed to load S3 buckets.", e); } } }); } private void createEnvironmentVariablesSection(Composite parent) { final Group envVarGroup = newGroup(parent, "Environment Variables"); envVarGroup.setLayout(new GridLayout(4, true)); newFillingLabel( envVarGroup, "Specify the name and value of the environment variables for your application", 4); // Input box for new variables final Text keyText = newText(envVarGroup); keyText.setMessage("Key"); final Text valueText = newText(envVarGroup); valueText.setMessage("Value"); final Button checkBox = newCheckbox(envVarGroup, "Protected value", 1); Button addButton = new Button(envVarGroup, SWT.PUSH); addButton.setImage(OpsWorksPlugin.getDefault().getImageRegistry() .get(OpsWorksExplorerImages.IMG_ADD)); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (keyText.getText().isEmpty() && valueText.getText().isEmpty()) { return; } EnvironmentVariable newVar = new EnvironmentVariable(); newVar.setKey(keyText.getText()); newVar.setValue(valueText.getText()); newVar.setSecure(checkBox.getSelection()); dataModel.addEnvironmentVariable(newVar); addNewEnvironmentVariable(envVarGroup, newVar); keyText.setText(""); valueText.setText(""); checkBox.setSelection(false); NewAppConfigurationComposite.this.layout(true, true); } }); // Added variables for (EnvironmentVariable envVar : dataModel.getEnvironmentVariables()) { addNewEnvironmentVariable(envVarGroup, envVar); } } private void addNewEnvironmentVariable(Group parentGroup, EnvironmentVariable variable) { newFillingLabel(parentGroup, variable.getKey()).setFont(JFaceResources.getBannerFont()); newFillingLabel(parentGroup, variable.getValue()); newFillingLabel(parentGroup, variable.isSecure() ? "(Protected)" : "(Not protected)", 2); } private void createCustomDomainsSection(Composite parent) { final Group domainsGroup = newGroup(parent, "Custom Domains"); domainsGroup.setLayout(new GridLayout(2, true)); newFillingLabel( domainsGroup, "Add one or more custom domains for your application", 2); // Input box for new domains final Text domainText = newText(domainsGroup); domainText.setMessage("www.example.com"); Button addButton = new Button(domainsGroup, SWT.PUSH); addButton.setImage(OpsWorksPlugin.getDefault().getImageRegistry() .get(OpsWorksExplorerImages.IMG_ADD)); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (domainText.getText().isEmpty()) { return; } String newDomain = domainText.getText(); dataModel.addCustomDomain(newDomain); newFillingLabel(domainsGroup, "[+] " + newDomain, 2); NewAppConfigurationComposite.this.layout(true, true); } }); // Added domains for (String domain : dataModel.getCustomDomains()) { newFillingLabel(domainsGroup, "[+] " + domain, 2); } } private void createSslSettingsSection(Composite parent) { Group sslSettingsGroup = newGroup(parent, "SSL Settings"); enableSslCheckBox = newCheckbox(sslSettingsGroup, "SSL enabled", 1); final Group advancedSslSettings = newGroup(sslSettingsGroup, ""); advancedSslSettings.setLayout(new GridLayout(2, true)); newFillingLabel(advancedSslSettings, "SSL certificate").setFont(JFaceResources.getBannerFont()); certText = newText(advancedSslSettings, ""); certText.setEnabled(false); newFillingLabel(advancedSslSettings, "SSL certificate key").setFont(JFaceResources.getBannerFont()); privateKeyText = newText(advancedSslSettings, ""); privateKeyText.setEnabled(false); newFillingLabel(advancedSslSettings, "SSL certificates of CA").setFont(JFaceResources.getBannerFont()); chainText = newText(advancedSslSettings, ""); chainText.setEnabled(false); enableSslCheckBox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { boolean enabled = enableSslCheckBox.getSelection(); certText.setEnabled(enabled); privateKeyText.setEnabled(enabled); chainText.setEnabled(enabled); } }); } }
8,117
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/page/AppConfigurationPage.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.page; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.widgets.Composite; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel.SslConfiguration; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.S3ApplicationSource; import com.amazonaws.services.opsworks.model.Source; public class AppConfigurationPage extends WizardPageWithOnEnterHook { /* Data model */ private final DeployProjectToOpsworksWizardDataModel dataModel; /* UI widgets */ private final StackLayout stackLayout = new StackLayout(); private Composite stackComposite; private ExistingAppConfigurationReviewComposite existingAppConfigComposite; private NewAppConfigurationComposite newAppConfigurationComposite; /** * The validation status listener to be registered to the UI composite for * the new Java app configuration. */ private final IChangeListener newJavaAppConfigValidationStatusListener = new IChangeListener() { @Override public void handleChange(ChangeEvent event) { Object observable = event.getObservable(); if (observable instanceof AggregateValidationStatus == false) return; AggregateValidationStatus statusObservable = (AggregateValidationStatus)observable; Object statusObservableValue = statusObservable.getValue(); if (statusObservableValue instanceof IStatus == false) return; IStatus status = (IStatus)statusObservableValue; boolean success = (status.getSeverity() == IStatus.OK); setPageComplete(success); if (success) { setMessage("", IStatus.OK); } else { setMessage(status.getMessage(), IStatus.ERROR); } } }; public AppConfigurationPage(DeployProjectToOpsworksWizardDataModel dataModel) { super("App Configuration"); setTitle("App Configuration"); setDescription(""); this.dataModel = dataModel; } @Override public void createControl(Composite parent) { stackComposite = new Composite(parent, SWT.NONE); stackComposite.setLayout(stackLayout); setControl(stackComposite); } @Override public void onEnterPage() { if (newAppConfigurationComposite != null) { newAppConfigurationComposite.removeValidationStatusChangeListener(); newAppConfigurationComposite.dispose(); } if (existingAppConfigComposite != null) { existingAppConfigComposite.dispose(); } resetErrorMessage(); resetDataModel(); if (dataModel.getIsCreatingNewJavaApp()) { newAppConfigurationComposite = new NewAppConfigurationComposite(stackComposite, dataModel); newAppConfigurationComposite.setValidationStatusChangeListener(newJavaAppConfigValidationStatusListener); stackLayout.topControl = newAppConfigurationComposite; } else { // Show the review page of the selected Java app existingAppConfigComposite = new ExistingAppConfigurationReviewComposite( stackComposite, dataModel.getExistingJavaApp()); if ( existingAppConfigComposite.getParsedS3ApplicationSource() == null ) { // Set the page to incomplete if the application source is not from S3 Source appSource = dataModel.getExistingJavaApp().getAppSource(); setMessage(String.format("Unsupported application source %s:[%s], " + "the OpsWorks Eclipse plugin only supports S3 as the data source. " + "Please use AWS Console to deploy to this app.", appSource.getType(), appSource.getUrl()), IStatus.ERROR); setPageComplete(false); } else { dataModel.setS3ApplicationSource(existingAppConfigComposite .getParsedS3ApplicationSource()); } stackLayout.topControl = existingAppConfigComposite; } stackComposite.layout(true, true); } /* Private interface */ private void resetDataModel() { dataModel.setS3ApplicationSource(new S3ApplicationSource()); dataModel.clearEnvironmentVariable(); dataModel.clearCustomDomains(); dataModel.setEnableSsl(false); dataModel.setSslConfiguration(new SslConfiguration()); } private void resetErrorMessage() { setMessage("", IStatus.OK); setPageComplete(true); } }
8,118
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/page/DeploymentActionConfigurationPage.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newControlDecoration; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.databinding.JsonStringValidator; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel; public class DeploymentActionConfigurationPage extends WizardPageWithOnEnterHook { /* Data model */ private final DeployProjectToOpsworksWizardDataModel dataModel; private final DataBindingContext bindingContext; private final AggregateValidationStatus aggregateValidationStatus; /* UI widgets */ private Text deployCommentText; private Text customChefJsonText; private ControlDecoration customChefJsonTextDecoration; private ISWTObservableValue deployCommentTextObservable; private ISWTObservableValue customChefJsonTextObservable; public DeploymentActionConfigurationPage(DeployProjectToOpsworksWizardDataModel dataModel) { super("Deployment Action Configuration"); setTitle("Deployment Action Configuration"); setDescription(""); this.dataModel = dataModel; this.bindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( bindingContext, AggregateValidationStatus.MAX_SEVERITY); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(3, true)); newFillingLabel(composite, "Command").setFont(JFaceResources.getBannerFont()); newFillingLabel(composite, "Deploy", 2); newFillingLabel(composite, "Comment (optional)").setFont(JFaceResources.getBannerFont()); deployCommentText = newTextArea(composite, 2, 4); newFillingLabel(composite, "Custom Chef JSON (optional)").setFont(JFaceResources.getBannerFont()); customChefJsonText = newTextArea(composite, 2, 4); customChefJsonTextDecoration = newControlDecoration( customChefJsonText, "Enter a valid JSON String."); bindControls(); initializeValidators(); setControl(composite); } private void bindControls() { deployCommentTextObservable = SWTObservables .observeText(deployCommentText, SWT.Modify); bindingContext.bindValue( deployCommentTextObservable, PojoObservables.observeValue( dataModel, DeployProjectToOpsworksWizardDataModel.DEPLOY_COMMENT)); customChefJsonTextObservable = SWTObservables .observeText(customChefJsonText, SWT.Modify); bindingContext.bindValue( customChefJsonTextObservable, PojoObservables.observeValue( dataModel, DeployProjectToOpsworksWizardDataModel.CUSTOM_CHEF_JSON)); } private void initializeValidators() { // Bind the validation status to the wizard page message aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent arg0) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; IStatus status = (IStatus)value; boolean success = (status.getSeverity() == IStatus.OK); setPageComplete(success); if (success) { setMessage("", IStatus.OK); } else { setMessage(status.getMessage(), IStatus.ERROR); } } }); // Validation status providers ChainValidator<String> customChefJsonValidator = new ChainValidator<>( customChefJsonTextObservable, new JsonStringValidator("Please enter a valid JSON String", true)); bindingContext.addValidationStatusProvider(customChefJsonValidator); new DecorationChangeListener(customChefJsonTextDecoration, customChefJsonValidator.getValidationStatus()); } private static Text newTextArea(Composite parent, int colspan, int lines) { Text text = new Text(parent, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL ); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = colspan; gridData.heightHint = lines * text.getLineHeight(); text.setLayoutData(gridData); return text; } @Override protected void onEnterPage() { } }
8,119
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/page/TargetAppSelectionPage.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newControlDecoration; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newRadioButton; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newText; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.core.ui.CancelableThread; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.databinding.BooleanValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.ServiceAPIUtils; import com.amazonaws.eclipse.opsworks.UrlConstants; import com.amazonaws.eclipse.opsworks.deploy.wizard.model.DeployProjectToOpsworksWizardDataModel; import com.amazonaws.services.opsworks.AWSOpsWorks; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.Stack; public class TargetAppSelectionPage extends WizardPageWithOnEnterHook { /* Data model and binding */ private final DeployProjectToOpsworksWizardDataModel dataModel; private final DataBindingContext bindingContext; private final AggregateValidationStatus aggregateValidationStatus; /* UI widgets */ // Select region private Combo regionCombo; // Select stack private IObservableValue existingStackLoaded = new WritableValue(); private Combo stackNameCombo; private Link stackSelectionMessageLabel; // Select Java application private IObservableValue existingJavaAppLoaded = new WritableValue(); private Button useExistingJavaAppRadioButton; private ISWTObservableValue useExistingJavaAppRadioButtonObservable; private Combo existingJavaAppNameCombo; private Button createNewJavaAppRadioButton; private ISWTObservableValue createNewJavaAppRadioButtonObservable; private Text newApplicationNameText; private ControlDecoration newApplicationNameDecoration; private ISWTObservableValue newApplicationNameTextObservable; /* Other */ private AWSOpsWorks opsworksClient; private LoadStacksThread loadStacksThread; private LoadJavaAppsThread loadJavaAppsThread; private final WebLinkListener webLinkListener = new WebLinkListener(); protected final SelectionListener javaAppSectionRadioButtonSelectionListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { radioButtonSelected(e.getSource()); runValidators(); } }; /* Constants */ private static final String LOADING = "Loading..."; private static final String NONE_FOUND = "None found"; public TargetAppSelectionPage(DeployProjectToOpsworksWizardDataModel dataModel) { super("Select Target Stack and App"); setTitle("Select Target Stack and App"); setDescription(""); this.dataModel = dataModel; this.bindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( bindingContext, AggregateValidationStatus.MAX_SEVERITY); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); createRegionSection(composite); createStackSection(composite); createJavaAppSection(composite); bindControls(); initializeValidators(); initializeDefaults(); onRegionSelectionChange(); setControl(composite); setPageComplete(false); } private void createRegionSection(Composite composite) { Group regionGroup = newGroup(composite, "Select AWS Region"); regionGroup.setLayout(new GridLayout(1, false)); regionCombo = newCombo(regionGroup); for (Region region : RegionUtils.getRegionsForService(ServiceAbbreviations.OPSWORKS)) { regionCombo.add(region.getName()); regionCombo.setData(region.getName(), region); } // Find the default region selection Region selectedRegion = dataModel.getRegion(); if (selectedRegion == null) { if ( RegionUtils.isServiceSupportedInCurrentRegion(ServiceAbbreviations.OPSWORKS) ) { selectedRegion = RegionUtils.getCurrentRegion(); } else { selectedRegion = RegionUtils.getRegion(OpsWorksPlugin.DEFAULT_REGION); } } regionCombo.setText(selectedRegion.getName()); regionCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onRegionSelectionChange(); } }); newFillingLabel(regionGroup, "Select the AWS region where your OpsWorks stack and app was created."); } private void createStackSection(Composite composite) { Group stackGroup = newGroup(composite, "Select OpsWorks stack:"); stackGroup.setLayout(new GridLayout(1, false)); stackNameCombo = newCombo(stackGroup); stackNameCombo.setEnabled(false); stackNameCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onStackSelectionChange(); } }); stackSelectionMessageLabel = newLink(stackGroup, webLinkListener, "", 1); } private void createJavaAppSection(Composite composite) { Group javaAppGroupSection = newGroup(composite, "Select or create a Java app:"); javaAppGroupSection.setLayout(new GridLayout(2, false)); useExistingJavaAppRadioButton = newRadioButton(javaAppGroupSection, "Choose an existing Java app:", 1, true, javaAppSectionRadioButtonSelectionListener); existingJavaAppNameCombo = newCombo(javaAppGroupSection); existingJavaAppNameCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onJavaAppSelectionChange(); } }); createNewJavaAppRadioButton = newRadioButton(javaAppGroupSection, "Create a new Java app:", 1, true, javaAppSectionRadioButtonSelectionListener); newApplicationNameText = newText(javaAppGroupSection); newApplicationNameDecoration = newControlDecoration( newApplicationNameText, "Enter a new app name or select an existing app."); } private void onRegionSelectionChange() { Region region = (Region)regionCombo.getData(regionCombo.getText()); String endpoint = region.getServiceEndpoints() .get(ServiceAbbreviations.OPSWORKS); opsworksClient = AwsToolkitCore.getClientFactory() .getOpsWorksClientByEndpoint(endpoint); dataModel.setRegion(region); refreshStacks(); } private void onStackSelectionChange() { if (existingStackLoaded.getValue().equals(Boolean.TRUE)) { Stack stack = (Stack)stackNameCombo.getData(stackNameCombo.getText()); dataModel.setExistingStack(stack); refreshJavaApps(); } } private void onJavaAppSelectionChange() { if (existingJavaAppLoaded.getValue().equals(Boolean.TRUE)) { App selectedApp = (App) existingJavaAppNameCombo .getData(existingJavaAppNameCombo.getText()); dataModel.setExistingJavaApp(selectedApp); } } private void refreshStacks() { existingStackLoaded.setValue(false); if (stackNameCombo != null) { stackNameCombo.setItems(new String[] {LOADING}); stackNameCombo.select(0); } if (stackSelectionMessageLabel != null) { stackSelectionMessageLabel.setText(""); } CancelableThread.cancelThread(loadStacksThread); loadStacksThread = new LoadStacksThread(); loadStacksThread.start(); } private void refreshJavaApps() { existingJavaAppLoaded.setValue(false); // Disable all the UI widgets for app selection until the apps are // loaded setJavaAppSectionEnabled(false); if (existingJavaAppNameCombo != null) { existingJavaAppNameCombo.setItems(new String[] {LOADING}); existingJavaAppNameCombo.select(0); } CancelableThread.cancelThread(loadJavaAppsThread); loadJavaAppsThread = new LoadJavaAppsThread(); loadJavaAppsThread.start(); } private void radioButtonSelected(Object source) { if ( source == useExistingJavaAppRadioButton || source == createNewJavaAppRadioButton) { boolean isCreatingNewApp = (Boolean) createNewJavaAppRadioButtonObservable.getValue(); existingJavaAppNameCombo.setEnabled(!isCreatingNewApp); newApplicationNameText.setEnabled(isCreatingNewApp); } } private void bindControls() { useExistingJavaAppRadioButtonObservable = SWTObservables .observeSelection(useExistingJavaAppRadioButton); createNewJavaAppRadioButtonObservable = SWTObservables .observeSelection(createNewJavaAppRadioButton); bindingContext.bindValue( createNewJavaAppRadioButtonObservable, PojoObservables.observeValue( dataModel, DeployProjectToOpsworksWizardDataModel.IS_CREATING_NEW_JAVA_APP)); newApplicationNameTextObservable = SWTObservables .observeText(newApplicationNameText, SWT.Modify); bindingContext.bindValue( newApplicationNameTextObservable, PojoObservables.observeValue( dataModel, DeployProjectToOpsworksWizardDataModel.NEW_JAVA_APP_NAME)); } private void initializeValidators() { // Bind the validation status to the wizard page message aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent arg0) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; IStatus status = (IStatus)value; boolean success = (status.getSeverity() == IStatus.OK); setPageComplete(success); if (success) { setMessage("", IStatus.OK); } else { setMessage(status.getMessage(), IStatus.ERROR); } } }); // Validation status providers bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( existingStackLoaded, new BooleanValidator("Please select a stack"))); bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( existingJavaAppLoaded, useExistingJavaAppRadioButtonObservable, // enabler new BooleanValidator("Please select a Java app"))); ChainValidator<String> appNameValidator = new ChainValidator<>( newApplicationNameTextObservable, createNewJavaAppRadioButtonObservable, // enabler new NotEmptyValidator("Please provide a valid app name")); bindingContext.addValidationStatusProvider(appNameValidator); new DecorationChangeListener(newApplicationNameDecoration, appNameValidator.getValidationStatus()); } private void runValidators() { Iterator<?> iterator = bindingContext.getBindings().iterator(); while (iterator.hasNext()) { Binding binding = (Binding)iterator.next(); binding.updateTargetToModel(); } } private void initializeDefaults() { existingStackLoaded.setValue(false); existingJavaAppLoaded.setValue(false); useExistingJavaAppRadioButtonObservable.setValue(true); createNewJavaAppRadioButtonObservable.setValue(false); newApplicationNameTextObservable.setValue("My App"); radioButtonSelected(useExistingJavaAppRadioButton); } private final class LoadStacksThread extends CancelableThread { @Override public void run() { final List<String> stackNames = new ArrayList<>(); final Map<String, Stack> stacks = new HashMap<>(); try { for (Stack stack : ServiceAPIUtils.getAllStacks(opsworksClient)) { stackNames.add(stack.getName()); stacks.put(stack.getName(), stack); } // Sort by name Collections.sort(stackNames); } catch (Exception e) { OpsWorksPlugin.getDefault().reportException( "Unable to load existing stacks.", e); setRunning(false); return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { synchronized (LoadStacksThread.this) { if ( !isCanceled() ) { stackNameCombo.removeAll(); for ( String stackName : stackNames ) { stackNameCombo.add(stackName); stackNameCombo.setData(stackName, stacks.get(stackName)); } if ( stackNames.size() > 0 ) { existingStackLoaded.setValue(true); stackNameCombo.setEnabled(true); stackNameCombo.select(0); onStackSelectionChange(); } else { existingStackLoaded.setValue(false); stackNameCombo.setEnabled(false); stackNameCombo.setItems(new String[] { NONE_FOUND}); stackNameCombo.select(0); stackSelectionMessageLabel.setText( "No stack is found in this region. " + "Please create a new OpsWorks stack via " + "<a href=\"" + UrlConstants.OPSWORKS_CONSOLE_URL + "\">AWS Console</a> before making a deployment"); useExistingJavaAppRadioButton.setEnabled(false); existingJavaAppNameCombo.setEnabled(false); existingJavaAppNameCombo.setItems(new String[0]); existingJavaAppLoaded.setValue(false); createNewJavaAppRadioButton.setEnabled(false); } // Re-calculate UI layout ((Composite)getControl()).layout(); } } } finally { setRunning(false); } } }); } } private final class LoadJavaAppsThread extends CancelableThread { @Override public void run() { final List<String> javaAppUINames = new ArrayList<>(); final Map<String, App> javaApps = new HashMap<>(); try { String stackId = dataModel.getExistingStack().getStackId(); for (App javaApp : ServiceAPIUtils .getAllJavaAppsInStack(opsworksClient, stackId)) { // UI names format : "app-name (app-shortname)" String appUIName = String.format("%s (%s)", javaApp.getName(), javaApp.getShortname()); javaAppUINames.add(appUIName); javaApps.put(appUIName, javaApp); } Collections.sort(javaAppUINames); } catch (Exception e) { Status status = new Status(Status.ERROR, OpsWorksPlugin.PLUGIN_ID, "Unable to load existing Java Apps: " + e.getMessage(), e); StatusManager.getManager().handle(status, StatusManager.SHOW); setRunning(false); return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { synchronized (LoadJavaAppsThread.this) { if ( !isCanceled() ) { // Restore the UI enabled status of the app section setJavaAppSectionEnabled(true); radioButtonSelected(useExistingJavaAppRadioButton); existingJavaAppNameCombo.removeAll(); for ( String javaAppUIName : javaAppUINames ) { existingJavaAppNameCombo.add(javaAppUIName); existingJavaAppNameCombo.setData(javaAppUIName, javaApps.get(javaAppUIName)); } if ( javaAppUINames.size() > 0 ) { existingJavaAppNameCombo.select(0); existingJavaAppLoaded.setValue(true); onJavaAppSelectionChange(); } else { useExistingJavaAppRadioButton.setEnabled(false); existingJavaAppNameCombo.setEnabled(false); existingJavaAppNameCombo.setItems(new String[] { NONE_FOUND}); existingJavaAppNameCombo.select(0); existingJavaAppLoaded.setValue(false); useExistingJavaAppRadioButtonObservable.setValue(false); createNewJavaAppRadioButtonObservable.setValue(true); radioButtonSelected(useExistingJavaAppRadioButton); } // Re-calculate UI layout ((Composite)getControl()).layout(); } } } finally { setRunning(false); } } }); } } /** * Enable/disable all the UI widgets in the app selection section. */ private void setJavaAppSectionEnabled(boolean enabled) { if (createNewJavaAppRadioButton != null) createNewJavaAppRadioButton.setEnabled(enabled); if (newApplicationNameText != null) newApplicationNameText.setEnabled(enabled); if (useExistingJavaAppRadioButton != null) useExistingJavaAppRadioButton.setEnabled(enabled); if (existingJavaAppNameCombo != null) existingJavaAppNameCombo.setEnabled(enabled); } @Override protected void onEnterPage() { } }
8,120
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/model/DeployProjectToOpsworksWizardDataModel.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.model; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.eclipse.core.resources.IProject; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.Stack; public class DeployProjectToOpsworksWizardDataModel { public static final String IS_CREATING_NEW_JAVA_APP = "isCreatingNewJavaApp"; public static final String NEW_JAVA_APP_NAME = "newJavaAppName"; public static final String ENABLE_SSL = "enableSsl"; public static final String DEPLOY_COMMENT = "deployComment"; public static final String CUSTOM_CHEF_JSON = "customChefJson"; private final IProject project; /* Page 1*/ private Region region; private Stack existingStack; private boolean isCreatingNewJavaApp; private App existingJavaApp; private String newJavaAppName; /* Page 2*/ private S3ApplicationSource s3ApplicationSource = new S3ApplicationSource(); private List<EnvironmentVariable> environmentVariables = new LinkedList<>(); private List<String> customDomains = new LinkedList<>(); private boolean enableSsl; private SslConfiguration sslConfiguration = new SslConfiguration(); /* Page 3*/ private String deployComment; private String customChefJson; /** * @param project * The Eclipse local project that is to be deployed. */ public DeployProjectToOpsworksWizardDataModel(IProject project) { this.project = project; } public IProject getProject() { return project; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public Stack getExistingStack() { return existingStack; } public void setExistingStack(Stack existingStack) { this.existingStack = existingStack; } public boolean getIsCreatingNewJavaApp() { return isCreatingNewJavaApp; } public void setIsCreatingNewJavaApp(boolean isCreatingNewJavaApp) { this.isCreatingNewJavaApp = isCreatingNewJavaApp; } public App getExistingJavaApp() { return existingJavaApp; } public void setExistingJavaApp(App existingJavaApp) { this.existingJavaApp = existingJavaApp; } public String getNewJavaAppName() { return newJavaAppName; } public void setNewJavaAppName(String newJavaAppName) { this.newJavaAppName = newJavaAppName; } public S3ApplicationSource getS3ApplicationSource() { return s3ApplicationSource; } public void setS3ApplicationSource(S3ApplicationSource s3ApplicationSource) { this.s3ApplicationSource = s3ApplicationSource; } public List<EnvironmentVariable> getEnvironmentVariables() { return Collections.unmodifiableList(environmentVariables); } public void addEnvironmentVariable(EnvironmentVariable var) { environmentVariables.add(var); } public void clearEnvironmentVariable() { environmentVariables.clear(); } public List<String> getCustomDomains() { return Collections.unmodifiableList(customDomains); } public void addCustomDomain(String domain) { customDomains.add(domain); } public void clearCustomDomains() { customDomains.clear(); } public boolean isEnableSsl() { return enableSsl; } public void setEnableSsl(boolean enableSsl) { this.enableSsl = enableSsl; } public SslConfiguration getSslConfiguration() { return sslConfiguration; } public void setSslConfiguration(SslConfiguration sslConfiguration) { this.sslConfiguration = sslConfiguration; } public String getDeployComment() { return deployComment; } public void setDeployComment(String deployComment) { this.deployComment = deployComment; } public String getCustomChefJson() { return customChefJson; } public void setCustomChefJson(String customChefJson) { this.customChefJson = customChefJson; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{") .append("eclipse-project=" + project.getName()) .append(", region=" + region) .append(", stack=" + existingStack.getName()) .append(", isCreatingNewJavaApp=" + isCreatingNewJavaApp) .append(", existingJavaApp=" + (existingJavaApp == null ? null : existingJavaApp.getName())) .append(", newJavaAppName=" + newJavaAppName) .append(", s3ApplicationSource=" + s3ApplicationSource) .append(", environmentVariables=" + environmentVariables) .append(", customDomains=" + customDomains) .append(", enableSsl=" + enableSsl) .append(", sslConfiguration=" + sslConfiguration) .append(", deployComment=" + deployComment) .append(", customChefJson=" + customChefJson) .append("}") ; return sb.toString(); } public static class EnvironmentVariable { public static final String KEY = "key"; public static final String VALUE = "value"; public static final String SECURE = "secure"; private String key; private String value; private boolean secure; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isSecure() { return secure; } public void setSecure(boolean secure) { this.secure = secure; } public com.amazonaws.services.opsworks.model.EnvironmentVariable toSdkModel() { return new com.amazonaws.services.opsworks.model.EnvironmentVariable() .withKey(key) .withValue(value) .withSecure(secure); } @Override public String toString() { return String.format("{ key=%s, value=%s, secure=%s }", key, value, secure); } } public static class SslConfiguration { public static final String CERTIFICATE = "certificate"; public static final String CHAIN = "chain"; public static final String PRIVATE_KEY = "privateKey"; private String certificate; private String chain; private String privateKey; public String getCertificate() { return certificate; } public void setCertificate(String certificate) { this.certificate = certificate; } public String getChain() { return chain; } public void setChain(String chain) { this.chain = chain; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public com.amazonaws.services.opsworks.model.SslConfiguration toSdkModel() { return new com.amazonaws.services.opsworks.model.SslConfiguration() .withCertificate(certificate) .withChain(chain) .withPrivateKey(privateKey); } @Override public String toString() { return String.format("{ certificate=%s, chain=%s, privateKey=%s }", certificate, chain, privateKey); } } }
8,121
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/deploy/wizard/model/S3ApplicationSource.java
package com.amazonaws.eclipse.opsworks.deploy.wizard.model; import com.amazonaws.regions.Region; import com.amazonaws.regions.RegionUtils; import com.amazonaws.services.opsworks.model.Source; import com.amazonaws.services.opsworks.model.SourceType; import com.amazonaws.services.s3.AmazonS3URI; import com.amazonaws.util.SdkHttpUtils; public class S3ApplicationSource { public static String BUCKET_NAME = "bucketName"; public static String KEY_NAME = "keyName"; public static String REGION = "region"; public static String AS_PUBLIC_HTTP_ARCHIVE = "asPublicHttpArchive"; private String bucketName; private String keyName; private Region region; private boolean asPublicHttpArchive = true; // always true when creating new apps /** * @return null if the specified application source is not supported. */ public static S3ApplicationSource parse(Source source) { S3ApplicationSource s3Source = new S3ApplicationSource(); if ("archive".equals(source.getType())) { s3Source.setAsPublicHttpArchive(true); } else if ("s3".equals(source.getType())) { s3Source.setAsPublicHttpArchive(false); } else { return null; } // parse the s3 URL AmazonS3URI s3Uri = null; try { s3Uri = new AmazonS3URI(source.getUrl()); } catch (Exception e) { return null; } if (s3Uri.getBucket() == null || s3Uri.getBucket().isEmpty()) { return null; } if (s3Uri.getKey() == null || s3Uri.getKey().isEmpty()) { return null; } if (s3Uri.getRegion() != null && RegionUtils.getRegion(s3Uri.getRegion()) == null) { return null; } s3Source.setBucketName(s3Uri.getBucket()); s3Source.setKeyName(s3Uri.getKey()); if (s3Uri.getRegion() != null) { s3Source.setRegion(RegionUtils.getRegion(s3Uri.getRegion())); } return s3Source; } /** * @return the Source object that can be used in a CreateApp request */ public Source toGenericSource() { Source source = new Source(); source.setType(asPublicHttpArchive ? SourceType.Archive : SourceType.S3); source.setUrl(String.format( "http://%s.s3.amazonaws.com/%s", SdkHttpUtils.urlEncode(bucketName, false), SdkHttpUtils.urlEncode(keyName, true))); return source; } public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getKeyName() { return keyName; } public void setKeyName(String keyName) { this.keyName = keyName; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public boolean isAsPublicHttpArchive() { return asPublicHttpArchive; } public void setAsPublicHttpArchive(boolean asPublicHttpArchive) { this.asPublicHttpArchive = asPublicHttpArchive; } @Override public String toString() { return String.format( "{ region=%s, bucket=%s, key=%s, isPublic=%s, url=%s }", region == null ? null : region.getName(), bucketName, keyName, asPublicHttpArchive, toGenericSource().getUrl()); } }
8,122
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/ExplorerNodeDecorator.java
/* * Copyright 2011-2012 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.opsworks.explorer; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import com.amazonaws.eclipse.opsworks.explorer.node.LayerElementNode; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.Instance; public class ExplorerNodeDecorator implements ILightweightLabelDecorator { private static final Map<String, String> APP_TYPES_MAPPING = new HashMap<>(); static { APP_TYPES_MAPPING.put("java", "Java"); APP_TYPES_MAPPING.put("rails", "Ruby on Rails"); APP_TYPES_MAPPING.put("php", "PHP"); APP_TYPES_MAPPING.put("nodejs", "Node.js"); APP_TYPES_MAPPING.put("static", "Static"); } @Override public void addListener(ILabelProviderListener listener) {} @Override public void removeListener(ILabelProviderListener listener) {} @Override public void dispose() {} @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void decorate(Object element, IDecoration decoration) { if (element instanceof LayerElementNode) { List<Instance> instances = ((LayerElementNode)element).getInstancesInLayer(); int count = instances == null ? 0 : instances.size(); if (count > 1) { decoration.addSuffix(" (" + count + " instances)"); } else { decoration.addSuffix(" (" + count + " instance)"); } } if (element instanceof Instance) { Instance node = (Instance)element; decoration.addSuffix(String.format(" %s (%s)", node.getPublicIp(), node.getStatus())); } if (element instanceof App) { App node = (App)element; String appTypeName = APP_TYPES_MAPPING.get(node.getType()); if (appTypeName != null) { decoration.addSuffix(" (" + appTypeName + ")"); } } } }
8,123
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/OpsWorksActionProvider.java
package com.amazonaws.eclipse.opsworks.explorer; import org.eclipse.jface.action.IMenuManager; import org.eclipse.ui.navigator.CommonActionProvider; public class OpsWorksActionProvider extends CommonActionProvider { @Override public void fillContextMenu(IMenuManager menu) { } }
8,124
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/OpsWorksContentProvider.java
package com.amazonaws.eclipse.opsworks.explorer; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; import com.amazonaws.eclipse.explorer.Loading; import com.amazonaws.eclipse.opsworks.ServiceAPIUtils; import com.amazonaws.eclipse.opsworks.explorer.node.AppsRootNode; import com.amazonaws.eclipse.opsworks.explorer.node.LayerElementNode; import com.amazonaws.eclipse.opsworks.explorer.node.LayersRootNode; import com.amazonaws.eclipse.opsworks.explorer.node.OpsWorksRootNode; import com.amazonaws.services.opsworks.AWSOpsWorks; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.Instance; import com.amazonaws.services.opsworks.model.Layer; import com.amazonaws.services.opsworks.model.Stack; public class OpsWorksContentProvider extends AbstractContentProvider { private static OpsWorksContentProvider instance; public OpsWorksContentProvider() { instance = this; } /* * Abstract methods of AbstractContentProvider */ @Override public boolean hasChildren(Object element) { if (element instanceof AWSResourcesRootElement || element instanceof OpsWorksRootNode || element instanceof Stack) { return true; } if (element instanceof LayersRootNode) { LayersRootNode node = (LayersRootNode)element; return node.getLayerNodes() != null && !node.getLayerNodes().isEmpty(); } if (element instanceof LayerElementNode) { LayerElementNode node = (LayerElementNode)element; return node.getInstancesInLayer() != null && !node.getInstancesInLayer().isEmpty(); } if (element instanceof AppsRootNode) { AppsRootNode node = (AppsRootNode)element; return node.getApps() != null && !node.getApps().isEmpty(); } return false; } @Override public Object[] loadChildren(Object parentElement) { if (parentElement instanceof AWSResourcesRootElement) { return new Object[] { OpsWorksRootNode.ROOT_ELEMENT }; } if (parentElement instanceof OpsWorksRootNode) { new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AWSOpsWorks client = AwsToolkitCore.getClientFactory() .getOpsWorksClient(); return ServiceAPIUtils.getAllStacks(client).toArray(); } }.start(); } if (parentElement instanceof Stack) { final String stackId = ((Stack) parentElement).getStackId(); new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AWSOpsWorks client = AwsToolkitCore.getClientFactory() .getOpsWorksClient(); List<Layer> layers = ServiceAPIUtils .getAllLayersInStack(client, stackId); List<LayerElementNode> layerNodes = new LinkedList<>(); for (Layer layer : layers) { layerNodes.add(new LayerElementNode(layer)); } LayersRootNode layersRoot = new LayersRootNode(layerNodes); List<App> apps = ServiceAPIUtils .getAllAppsInStack(client, stackId); AppsRootNode appsRoot = new AppsRootNode(apps); return new Object[] {appsRoot, layersRoot}; } }.start(); } if (parentElement instanceof LayersRootNode) { AWSOpsWorks client = AwsToolkitCore.getClientFactory() .getOpsWorksClient(); List<LayerElementNode> layerNodes = ((LayersRootNode)parentElement).getLayerNodes(); for (LayerElementNode layerNode : layerNodes) { List<Instance> instances = ServiceAPIUtils .getAllInstancesInLayer(client, layerNode.getLayer().getLayerId()); layerNode.setInstancesInLayer(instances); } return layerNodes.toArray(); } if (parentElement instanceof LayerElementNode) { return ((LayerElementNode)parentElement).getInstancesInLayer().toArray(); } if (parentElement instanceof AppsRootNode) { return ((AppsRootNode)parentElement).getApps().toArray(); } return Loading.LOADING; } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.OPSWORKS; } @Override public void dispose() { viewer.removeOpenListener(listener); super.dispose(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { super.inputChanged(viewer, oldInput, newInput); this.viewer.addOpenListener(listener); } public static OpsWorksContentProvider getInstance() { return instance; } private final IOpenListener listener = new IOpenListener() { @Override public void open(OpenEvent event) { StructuredSelection selection = (StructuredSelection)event.getSelection(); Iterator<?> i = selection.iterator(); while ( i.hasNext() ) { Object obj = i.next(); // Node double-click actions } } }; }
8,125
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/ExplorerSorter.java
package com.amazonaws.eclipse.opsworks.explorer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import com.amazonaws.eclipse.explorer.ExplorerNode; public class ExplorerSorter extends ViewerSorter { @Override public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof ExplorerNode && e2 instanceof ExplorerNode) { ExplorerNode nn1 = (ExplorerNode)e1; ExplorerNode nn2 = (ExplorerNode)e2; Integer sortPriority1 = nn1.getSortPriority(); Integer sortPriority2 = nn2.getSortPriority(); return sortPriority1.compareTo(sortPriority2); } else return super.compare(viewer, e1, e2); } }
8,126
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/OpsWorksLabelProvider.java
package com.amazonaws.eclipse.opsworks.explorer; import java.util.List; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.explorer.image.OpsWorksExplorerImages; import com.amazonaws.eclipse.opsworks.explorer.node.AppsRootNode; import com.amazonaws.eclipse.opsworks.explorer.node.LayerElementNode; import com.amazonaws.eclipse.opsworks.explorer.node.LayersRootNode; import com.amazonaws.eclipse.opsworks.explorer.node.OpsWorksRootNode; import com.amazonaws.services.opsworks.model.App; import com.amazonaws.services.opsworks.model.Instance; import com.amazonaws.services.opsworks.model.Stack; public class OpsWorksLabelProvider extends ExplorerNodeLabelProvider { @Override public Image getDefaultImage(Object element) { ImageRegistry imageRegistry = OpsWorksPlugin.getDefault().getImageRegistry(); if ( element instanceof OpsWorksRootNode ) { return imageRegistry.get(OpsWorksExplorerImages.IMG_SERVICE); } if ( element instanceof Stack ) { return imageRegistry.get(OpsWorksExplorerImages.IMG_STACK); } if ( element instanceof LayerElementNode || element instanceof LayersRootNode ) { return imageRegistry.get(OpsWorksExplorerImages.IMG_LAYER); } if ( element instanceof Instance ) { return imageRegistry.get(OpsWorksExplorerImages.IMG_INSTANCE); } if ( element instanceof App || element instanceof AppsRootNode ) { return imageRegistry.get(OpsWorksExplorerImages.IMG_APP); } return null; } @Override public String getText(Object element) { if ( element instanceof OpsWorksRootNode ) { return "AWS OpsWorks"; } if ( element instanceof Stack ) { Stack stack = (Stack)element; return stack.getName(); } if ( element instanceof LayersRootNode ) { LayersRootNode layerRoot = (LayersRootNode)element; List<LayerElementNode> layers = layerRoot.getLayerNodes(); int count = layers == null ? 0 : layers.size(); if (count > 1) { return count + " Layers"; } else { return count + " Layer"; } } if ( element instanceof LayerElementNode ) { LayerElementNode layerNode = (LayerElementNode)element; return layerNode.getLayer().getName(); } if ( element instanceof Instance ) { Instance instance = (Instance)element; return instance.getHostname(); } if ( element instanceof AppsRootNode ) { AppsRootNode appRoot = (AppsRootNode)element; List<App> apps = appRoot.getApps(); int count = apps == null ? 0 : apps.size(); if (count > 1) { return count + " Apps"; } else { return count + " App"; } } if ( element instanceof App ) { App app = (App)element; return app.getName(); } return getExplorerNodeText(element); } }
8,127
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/image/OpsWorksExplorerImages.java
package com.amazonaws.eclipse.opsworks.explorer.image; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; public class OpsWorksExplorerImages { public static final String IMG_AWS_BOX = "aws-box"; public static final String IMG_SERVICE = "opsworks-service"; public static final String IMG_STACK = "stack"; public static final String IMG_LAYER = "layer"; public static final String IMG_INSTANCE = "instance"; public static final String IMG_APP = "app"; public static final String IMG_ADD = "add"; public static ImageRegistry createImageRegistry() { ImageRegistry imageRegistry = new ImageRegistry(Display.getCurrent()); imageRegistry.put(IMG_AWS_BOX, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/aws-box.gif")); imageRegistry.put(IMG_SERVICE, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/opsworks-service.png")); imageRegistry.put(IMG_STACK, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/stack.png")); imageRegistry.put(IMG_LAYER, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/layer.png")); imageRegistry.put(IMG_INSTANCE, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/instance.png")); imageRegistry.put(IMG_APP, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/app.png")); imageRegistry.put(IMG_ADD, ImageDescriptor.createFromFile(OpsWorksPlugin.class, "/icons/add.png")); return imageRegistry; } }
8,128
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/node/LayersRootNode.java
package com.amazonaws.eclipse.opsworks.explorer.node; import java.util.Collections; import java.util.List; import com.amazonaws.eclipse.explorer.ExplorerNode; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.explorer.image.OpsWorksExplorerImages; public class LayersRootNode extends ExplorerNode { private final List<LayerElementNode> layerNodes; public LayersRootNode(List<LayerElementNode> layerNodes) { super("Layers", 1, OpsWorksPlugin.getDefault().getImageRegistry() .get(OpsWorksExplorerImages.IMG_LAYER), null); this.layerNodes = Collections.unmodifiableList(layerNodes); } public List<LayerElementNode> getLayerNodes() { return layerNodes; } }
8,129
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/node/AppsRootNode.java
package com.amazonaws.eclipse.opsworks.explorer.node; import java.util.Collections; import java.util.List; import com.amazonaws.eclipse.explorer.ExplorerNode; import com.amazonaws.eclipse.opsworks.OpsWorksPlugin; import com.amazonaws.eclipse.opsworks.explorer.image.OpsWorksExplorerImages; import com.amazonaws.services.opsworks.model.App; public class AppsRootNode extends ExplorerNode { private final List<App> apps; public AppsRootNode(List<App> apps) { super("Apps", 2, OpsWorksPlugin.getDefault().getImageRegistry() .get(OpsWorksExplorerImages.IMG_APP), null); this.apps = apps; } public List<App> getApps() { return Collections.unmodifiableList(apps); } }
8,130
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/node/OpsWorksRootNode.java
package com.amazonaws.eclipse.opsworks.explorer.node; /** * Root element for OpsWorks resources in the resource navigator. */ public class OpsWorksRootNode { public static final OpsWorksRootNode ROOT_ELEMENT = new OpsWorksRootNode(); private OpsWorksRootNode() {} }
8,131
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.opsworks/src/com/amazonaws/eclipse/opsworks/explorer/node/LayerElementNode.java
package com.amazonaws.eclipse.opsworks.explorer.node; import java.util.Collections; import java.util.List; import com.amazonaws.services.opsworks.model.Instance; import com.amazonaws.services.opsworks.model.Layer; public class LayerElementNode { private final Layer layer; private List<Instance> instancesInLayer; public LayerElementNode(Layer layer) { this.layer = layer; } public Layer getLayer() { return layer; } public void setInstancesInLayer(List<Instance> instancesInLayer) { this.instancesInLayer = instancesInLayer; } public List<Instance> getInstancesInLayer() { return Collections.unmodifiableList(instancesInLayer); } }
8,132
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/LambdaHandlerInitedWithRandomValueTest.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import static edu.umd.cs.findbugs.test.CountMatcher.containsExactly; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.lambda.snapstart.matcher.ContainsMatcher.containsAll; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.test.matcher.BugInstanceMatcher; import edu.umd.cs.findbugs.test.matcher.BugInstanceMatcherBuilder; import java.util.Arrays; import java.util.List; import org.hamcrest.Matcher; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; public class LambdaHandlerInitedWithRandomValueTest extends AbstractSnapStartTest { @Test public void testGoodCase() { BugCollection bugCollection = findBugsInLambda("GoodLambda"); assertThat(bugCollection, containsExactly(0, snapStartBugMatcher().build())); } @Test public void testNonLambdaCase() { BugCollection bugCollection = findBugsInLambda("NonLambda"); assertThat(bugCollection, containsExactly(0, snapStartBugMatcher().build())); } @Test public void testBadCase() { SystemProperties.setProperty("findbugs.execplan.debug", "true"); BugCollection bugCollection = findBugsInLambda("BadLambda"); BugInstanceMatcherBuilder bugMatcherBuilder = snapStartBugMatcher().inClass("BadLambda"); List<Matcher<BugInstance>> expectedBugs = Arrays.asList( bugMatcherBuilder.atField("RNG").atLine(19).build(), bugMatcherBuilder.atField("STATIC_USER_ID_DOUBLE").atLine(24).build(), bugMatcherBuilder.atField("STATIC_USER_ID_INT").atLine(25).build(), bugMatcherBuilder.atField("STATIC_USER_ID_INT_SEC").atLine(26).build(), bugMatcherBuilder.atField("STATIC_USER_ID_UUID").atLine(23).build(), bugMatcherBuilder.atField("userIdDouble").atLine(31).build(), bugMatcherBuilder.atField("userIdUuid").atLine(27).build() ); assertThat(bugCollection, containsAll(expectedBugs)); } @Test public void rngMemberFieldBreaksSnapStart() { BugCollection bugCollection = findBugsInClasses("LambdaUsingRandom"); BugInstanceMatcherBuilder bugMatcherBuilder = snapStartBugMatcher().inClass("LambdaUsingRandom"); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("staticRng").atLine(14).build())); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("rng").atLine(22).build())); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("injectedRng").atLine(24).build())); assertThat(bugCollection, containsExactly(3, snapStartBugMatcher().build())); } @Test public void transitiveRngInstancesBreaksSnapStart() { BugCollection bugCollection = findBugsInClasses("LambdaUsingTransitiveRng"); BugInstanceMatcher bugMatcher = snapStartBugMatcher().build(); toBeFixed(() -> assertThat(bugCollection, not(containsExactly(0, bugMatcher)))); } @Test public void customRngMemberFieldBreaksSnapStart() { BugCollection bugCollection = findBugsInClasses("LambdaUsingRngLib", "RngLib", "DeepRngLib"); BugInstanceMatcherBuilder bugMatcherBuilder = snapStartBugMatcher().inClass("LambdaUsingRngLib"); List<Matcher<BugInstance>> expectedUncaughtBugs = Arrays.asList( bugMatcherBuilder.atField("staticRngLib").atLine(12).build(), bugMatcherBuilder.atField("rngLib").atLine(16).build() ); toBeFixed(() -> assertThat(bugCollection, containsAll(expectedUncaughtBugs))); List<Matcher<BugInstance>> expectedCaughtBugs = Arrays.asList( bugMatcherBuilder.atField("randomLogId").atLine(21).build(), bugMatcherBuilder.atField("randomUserId").atLine(20).build() ); assertThat(bugCollection, containsAll(expectedCaughtBugs)); } @Test public void uuidMemberFieldBreaksSnapStart() { BugCollection bugCollection = findBugsInClasses("LambdaUsingUuid"); BugInstanceMatcherBuilder bugMatcherBuilder = snapStartBugMatcher().inClass("LambdaUsingUuid"); List<Matcher<BugInstance>> expectedBugs = Arrays.asList( bugMatcherBuilder.atField("ID1").atLine(13).build(), bugMatcherBuilder.atField("ID2").atLine(14).build(), bugMatcherBuilder.atField("id3").atLine(22).build(), bugMatcherBuilder.atField("id4").atLine(16).build(), bugMatcherBuilder.atField("id5").atLine(22).build() ); toBeFixed(() -> assertThat(bugCollection, containsAll(expectedBugs))); } @Test public void timestampMemberFieldBreaksSnapStart() { BugCollection bugCollection = findBugsInClasses("LambdaUsingTs"); BugInstanceMatcherBuilder bugMatcherBuilder = snapStartBugMatcher().inClass("LambdaUsingTs"); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("tsFromSystemTimeMillis").atLine(24).build())); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("tsFromSystemTimeNano").atLine(25).build())); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("tsFromInstantNow").atLine(26).build())); assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("tsFromClock").atLine(27).build())); toBeFixed(() -> assertThat(bugCollection, containsExactly(1, bugMatcherBuilder.atField("logName").atLine(29).build()))); assertThat(bugCollection, containsExactly(4, snapStartBugMatcher().build())); toBeFixed(() -> assertThat(bugCollection, containsExactly(5, snapStartBugMatcher().build()))); } @Test public void findsBugsInClassesThatLookLikeLambda() { BugCollection bugCollection = findBugsInClasses("LooksLikeLambda", "LooksLikeStreamLambda"); List<Matcher<BugInstance>> expectedBugs = Arrays.asList( snapStartBugMatcher().inClass("LooksLikeLambda").atField("LOG_ID").atLine(11).build(), snapStartBugMatcher().inClass("LooksLikeStreamLambda").atField("LOG_ID").atLine(13).build() ); assertThat(bugCollection, containsAll(expectedBugs)); } @Test public void findsBugsInClassesThatImplementCracResource() { String className = "LambdaWithCracUsingRng"; BugCollection bugCollection = findBugsInClasses(className); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass(className).atField("constructorNewRng_bad").atLine(31).build())); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass(className).atField("constructorDirectRefRng_bad").atLine(32).build())); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass(className).atField("constructorMethodRefRng_bad").atLine(33).build())); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass(className).atField("checkpointNewRng_bad").atLine(43).build())); assertThat(bugCollection, containsExactly(4, snapStartBugMatcher().inClass(className).build())); } @Test public void testLambdaWithToString() { BugCollection bugCollection = findBugsInClasses("LambdaWithToString"); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("LambdaWithToString").atField("random").atLine(11).build())); } @Test public void testLambdaWithParentClass() { BugCollection bugCollection = findBugsInClasses("LambdaWithParentClass", "ParentHandler", "SuperParentHandler"); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("ParentHandler").atField("parentId").atLine(6).build())); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("SuperParentHandler").atField("superParentId").atLine(6).build())); } @Test public void testClassImplementingFunctionalInterface() { BugCollection bugCollection = findBugsInClasses("ImplementsFunctionalInterface"); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("ImplementsFunctionalInterface").atField("random").atLine(8).build())); } @Test public void testLambdaWithNoInterface() { BugCollection bugCollection = findBugsInClasses("LambdaHandlerWithNoInterface"); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("LambdaHandlerWithNoInterface").atField("random").atLine(7).build())); } @Test public void testLambdaWithDependencyInjection() { BugCollection bugCollection = findBugsInClasses("DependencyInjection", "MyDependency"); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("MyDependency").atField("random").atLine(6).build())); } // Test a Lambda function using Dependency Injection while implementing a Functional Interface @Test public void testLambdaWithDependencyInjectionAndFunctionalInterface() { BugCollection bugCollection = findBugsInClasses("DependencyInjectionFunctionalInterface", "MyDependency"); assertThat(bugCollection, containsExactly(1, snapStartBugMatcher().inClass("MyDependency").atField("random").atLine(6).build())); } // TODO fix all tests using this and remove this method eventually! private static void toBeFixed(Executable e) { assertThrows(AssertionError.class, e); } }
8,133
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/AbstractSnapStartTest.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.test.AnalysisRunner; import edu.umd.cs.findbugs.test.matcher.BugInstanceMatcherBuilder; import java.io.File; import java.lang.management.ManagementFactory; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; public abstract class AbstractSnapStartTest { /** * All example classes that are subject to our tests should be under this package. */ private static final String EXAMPLE_PKG = "software.amazon.lambda.snapstart.lambdaexamples".replace('.', '/'); private AnalysisRunner runner; @BeforeEach public void init() { runner = new AnalysisRunner(); // Our test fixture classes under lambdaexamples package use the test classpath and we // want analyzer to have access the bytecode of everything that fixture classes can use. // Therefore, the whole test classpath is added as auxiliary classpath entry here. String cPath = ManagementFactory.getRuntimeMXBean().getClassPath(); for (String p : cPath.split(File.pathSeparator)) { runner.addAuxClasspathEntry(Paths.get(p)); } } @AfterEach public void clean() { runner = null; } protected BugCollection findBugsInClasses(String ... classNames) { Path [] paths = new Path[classNames.length]; for (int i = 0; i < classNames.length; i++) { String className = classNames[i]; paths[i] = Paths.get("target/test-classes", EXAMPLE_PKG, className + ".class"); } return runner.run(paths).getBugCollection(); } protected BugCollection findBugsInLambda(String className) { return findBugsInClasses(className); } protected BugInstanceMatcherBuilder snapStartBugMatcher() { return new BugInstanceMatcherBuilder() .bugType("AWS_LAMBDA_SNAP_START_BUG"); } }
8,134
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/BadLambda.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.security.SecureRandom; import java.util.Map; import java.util.Random; import java.util.UUID; /** All class members (static-non static) are tainted and will be caught by * our rudimentary SnapStart bug detector. */ class BadLambda implements RequestHandler<Map<String,String>, String> { private static final Random RNG = new Random(); private static final SecureRandom SEC_RNG = new SecureRandom(); // These are buggy fields private static final UUID STATIC_USER_ID_UUID = UUID.randomUUID(); private static final Double STATIC_USER_ID_DOUBLE = Math.random(); private static final Integer STATIC_USER_ID_INT = RNG.nextInt(); private static final Integer STATIC_USER_ID_INT_SEC = SEC_RNG.nextInt(); private final UUID userIdUuid = UUID.randomUUID(); private final Double userIdDouble; public BadLambda() { userIdDouble = Math.random(); } @Override public String handleRequest(Map<String,String> event, Context context) { LambdaLogger logger = context.getLogger(); logger.log("Creating a new user IDs"); logger.log(Double.toString(userIdDouble)); logger.log(Double.toString(STATIC_USER_ID_DOUBLE)); logger.log(Double.toString(STATIC_USER_ID_INT)); logger.log(Double.toString(STATIC_USER_ID_INT_SEC)); logger.log(userIdUuid.toString()); return STATIC_USER_ID_UUID.toString(); } }
8,135
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LooksLikeLambda.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import java.util.Map; import java.util.UUID; public class LooksLikeLambda { private static final UUID LOG_ID = UUID.randomUUID(); // This is a bug public String handlesTheEvent(Map<String,String> event, Context context) { return LOG_ID.toString(); } }
8,136
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LooksLikeStreamLambda.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.UUID; public class LooksLikeStreamLambda { private static final UUID LOG_ID = UUID.randomUUID(); // This is a bug public void handlesTheEvent(InputStream input, OutputStream output, Context context) { PrintWriter pw = new PrintWriter(output); pw.println(LOG_ID); pw.flush(); } }
8,137
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/GoodLambda.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; class GoodLambda implements RequestHandler<Map<String,String>, String> { private final Double userIdDouble; public GoodLambda() { userIdDouble = 5d; } @Override public String handleRequest(Map<String,String> event, Context context) { LambdaLogger logger = context.getLogger(); logger.log("Creating a new user IDs"); logger.log(Double.toString(userIdDouble)); return userIdDouble.toString(); } }
8,138
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaHandlerWithNoInterface.java
package software.amazon.lambda.snapstart.lambdaexamples; import java.util.UUID; public class LambdaHandlerWithNoInterface { private final UUID random = UUID.randomUUID(); public String handleRequest(){ return random.toString(); } }
8,139
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/SuperParentHandler.java
package software.amazon.lambda.snapstart.lambdaexamples; import java.util.UUID; public class SuperParentHandler { protected final UUID superParentId = UUID.randomUUID(); protected SuperParentHandler() {} }
8,140
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaUsingRandom.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.security.SecureRandom; import java.util.Map; import java.util.Random; public class LambdaUsingRandom implements RequestHandler<Map<String,String>, String> { private static final Random staticRng = new Random(); // This is a bug private static final Random staticSecureRng = new SecureRandom(); // This is NOT a bug private final Random rng; private final Random secureRng; private final Random injectedRng; private final Random injectedSecureRng; public LambdaUsingRandom(Random injectedRng, SecureRandom injectedSecureRng) { this.rng = new Random(0); // This is a bug this.secureRng = new SecureRandom(); // This is NOT a bug this.injectedRng = injectedRng; // This is a bug this.injectedSecureRng = injectedSecureRng; // This is NOT a bug } @Override public String handleRequest(Map<String,String> event, Context context) { int randomSum = 0; randomSum += staticRng.nextInt(); randomSum += staticSecureRng.nextInt(); randomSum += rng.nextInt(); randomSum += secureRng.nextInt(); randomSum += injectedRng.nextInt(); randomSum += injectedSecureRng.nextInt(); return Integer.toString(randomSum); } }
8,141
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/ParentHandler.java
package software.amazon.lambda.snapstart.lambdaexamples; import java.util.UUID; public abstract class ParentHandler extends SuperParentHandler { protected final UUID parentId = UUID.randomUUID(); protected ParentHandler() {} }
8,142
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaUsingRngLib.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; public class LambdaUsingRngLib implements RequestHandler<Map<String,String>, String> { private static final RngLib staticRngLib = new RngLib(); // This is a bug (but currently we don't catch this) private final RngLib rngLib; private final int randomUserId; private final int randomLogId; public LambdaUsingRngLib() { rngLib = new RngLib(); // This is a bug (but currently we don't catch this) DeepRngLib deepRngLib = new DeepRngLib(); randomUserId = deepRngLib.randomInt(); // This is a bug randomLogId = rngLib.randomInt(); // This is a bug } @Override public String handleRequest(Map<String,String> event, Context context) { // use fields return Integer.toString(rngLib.randomInt()) + Integer.toString(staticRngLib.randomInt()) + Integer.toString(randomUserId) + Integer.toString(randomLogId); } }
8,143
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/DependencyInjectionFunctionalInterface.java
package software.amazon.lambda.snapstart.lambdaexamples; import java.util.function.Function; public class DependencyInjectionFunctionalInterface implements Function<String, String> { private final MyDependency myDependency; public DependencyInjectionFunctionalInterface(MyDependency myDependency) { this.myDependency = myDependency; } @Override public String apply(String s) { return myDependency.toString(); } }
8,144
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaWithCracUsingRng.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import static java.lang.System.out; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.security.SecureRandom; import java.util.Random; import org.crac.Resource; public class LambdaWithCracUsingRng implements RequestHandler<String, String>, Resource { private final Random constructorNewRng_bad; private final Random constructorDirectRefRng_bad; private final Random constructorMethodRefRng_bad; private final SecureRandom constructorNewSecureRng_ok; private final SecureRandom constructorDirectRefSecureRng_ok; private final SecureRandom constructorMethodRefSecureRng_ok; private final Random constructorRngPolymorphedFromSecureRng_ok; private final Random constructorRngUpCastedFromSecureRng_ok; private Random checkpointNewRng_bad; private Random checkpointNewSecureRng_ok; private Random restoreNewRng_ok; private Random invokeNewRng_ok; public LambdaWithCracUsingRng(final Random rng, final SecureRandom secureRng) { this.constructorNewRng_bad = new Random(); // This is a bug this.constructorDirectRefRng_bad = rng; // This is a bug this.constructorMethodRefRng_bad = Random.class.cast(secureRng); // This is a bug as we assume any method returning `Random` type is potentially unsecure this.constructorNewSecureRng_ok = new SecureRandom(); this.constructorDirectRefSecureRng_ok = secureRng; this.constructorMethodRefSecureRng_ok = SecureRandom.class.cast(secureRng); this.constructorRngPolymorphedFromSecureRng_ok = secureRng; this.constructorRngUpCastedFromSecureRng_ok = (Random) secureRng; } @Override public void beforeCheckpoint(org.crac.Context<? extends Resource> context) throws Exception { this.checkpointNewRng_bad = new Random(); // This is a bug this.checkpointNewSecureRng_ok = new SecureRandom(); } @Override public void afterRestore(org.crac.Context<? extends Resource> context) throws Exception { this.restoreNewRng_ok = new Random(); } @Override public String handleRequest(String event, Context context) { this.invokeNewRng_ok = new Random(); out.println(constructorNewRng_bad.nextInt()); out.println(constructorDirectRefRng_bad.nextInt()); out.println(constructorMethodRefRng_bad.nextInt()); out.println(constructorNewSecureRng_ok.nextInt()); out.println(constructorDirectRefSecureRng_ok.nextInt()); out.println(constructorMethodRefSecureRng_ok.nextInt()); out.println(constructorRngPolymorphedFromSecureRng_ok.nextInt()); out.println(constructorRngUpCastedFromSecureRng_ok.nextInt()); out.println(checkpointNewRng_bad.nextInt()); out.println(checkpointNewSecureRng_ok.nextInt()); out.println(restoreNewRng_ok.nextInt()); out.println(invokeNewRng_ok.nextInt()); return "200"; } }
8,145
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaUsingTransitiveRng.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.security.SecureRandom; import java.util.Map; import java.util.Random; import org.crac.Resource; public class LambdaUsingTransitiveRng implements RequestHandler<Map<String,String>, String>, Resource { /** * Library class that does not implement {@link RequestHandler} or {@link Resource}, * but is used by {@link LambdaUsingTransitiveRng} which is a Lambda handler. * * Note: For the purpose of the detector, it should not matter whether this is an inner class * or a separate class, so as long as this class is provided in the classpath of SpotBugs execution. */ public static class LogicLib { final static Random staticRng = new Random(); final static SecureRandom staticSecureRng = new SecureRandom(); final Random rng; final SecureRandom secureRng; // RNGs set in class outside of Lambda handler public LogicLib(Random rng, SecureRandom secureRng) { this.rng = rng; this.secureRng = secureRng; } public int getRngValue() { return rng.nextInt(); } } private static final LogicLib staticLogicLib = new LogicLib(new Random(), new SecureRandom()); private final LogicLib constructorLogicLib; private LogicLib checkpointLogicLib; private LogicLib restoreLogicLib; public LambdaUsingTransitiveRng(Random rng, SecureRandom secureRng) { this.constructorLogicLib = new LogicLib(rng, secureRng); } @Override // for org.crac.Resource public void beforeCheckpoint(org.crac.Context<? extends Resource> context) throws Exception { this.checkpointLogicLib = new LogicLib(new Random(), new SecureRandom()); } @Override // for org.crac.Resource public void afterRestore(org.crac.Context<? extends Resource> context) throws Exception { this.restoreLogicLib = new LogicLib(new Random(), new SecureRandom()); } @Override // for RequestHandler public String handleRequest(Map<String,String> event, Context context) { int sum = 0; sum += LogicLib.staticRng.nextInt(); // This should be a bug sum += LogicLib.staticSecureRng.nextInt(); sum += getBadRngValue(); sum += getOkayRngValue(); sum += staticLogicLib.getRngValue(); // This should be a bug sum += constructorLogicLib.getRngValue(); // This should be a bug sum += checkpointLogicLib.getRngValue(); // This should be a bug sum += restoreLogicLib.getRngValue(); return Integer.toString(sum); } private int getBadRngValue() { int sum = 0; sum += staticLogicLib.rng.nextInt(); // This should be a bug sum += constructorLogicLib.rng.nextInt(); // This should be a bug sum += checkpointLogicLib.rng.nextInt(); // This should be a bug return sum; } private int getOkayRngValue() { int sum = 0; sum += staticLogicLib.secureRng.nextInt(); sum += constructorLogicLib.secureRng.nextInt(); sum += checkpointLogicLib.secureRng.nextInt(); sum += restoreLogicLib.rng.nextInt(); sum += restoreLogicLib.secureRng.nextInt(); return sum; } }
8,146
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaUsingUuid.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; import java.util.UUID; public class LambdaUsingUuid implements RequestHandler<Map<String,String>, String> { private static final String ID1 = "a" + UUID.randomUUID(); // This is a bug private static final String ID2 = UUID.randomUUID() + "a"; // This is a bug private final String id3; private final String id4 = newString(); // This is a bug private final UUID id5; private final String name = "example"; // This is NOT a bug public LambdaUsingUuid() { id3 = UUID.randomUUID().toString(); // This is a bug id5 = UUID.randomUUID(); // This is a bug } @Override public String handleRequest(Map<String, String> event, Context context) { return ID1 + ID2 + id3 + id4 + name; } public String newString() { return UUID.randomUUID() + "c"; } }
8,147
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/ImplementsFunctionalInterface.java
package software.amazon.lambda.snapstart.lambdaexamples; import java.util.UUID; import java.util.function.Function; public class ImplementsFunctionalInterface implements Function<String, String> { private final UUID random = UUID.randomUUID(); @Override public String apply(String s) { return random.toString(); } }
8,148
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/MyDependency.java
package software.amazon.lambda.snapstart.lambdaexamples; import java.util.UUID; public class MyDependency { private final UUID random = UUID.randomUUID(); public UUID getUUID() { return random; } }
8,149
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaUsingTs.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import static java.lang.System.out; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.time.Clock; import java.time.Instant; import java.util.Map; public class LambdaUsingTs implements RequestHandler<Map<String,String>, String> { private static String logName; private long tsFromSystemTimeMillis; private long tsFromSystemTimeNano; private Instant tsFromInstantNow; private Instant tsFromClock; public LambdaUsingTs(Clock clock) { tsFromSystemTimeMillis = System.currentTimeMillis(); // This is a bug tsFromSystemTimeNano = System.nanoTime(); // This is a bug tsFromInstantNow = Instant.now(); // This is a bug tsFromClock = clock.instant(); // This is a bug logName = getLogName(); // This is a bug } private String getLogName() { return "my-app.log." + System.currentTimeMillis(); } @Override public String handleRequest(Map<String, String> event, Context context) { out.println(logName); out.println(tsFromSystemTimeMillis); out.println(tsFromSystemTimeNano); out.println(tsFromInstantNow); out.println(tsFromClock); return "200"; } }
8,150
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaWithToString.java
package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; import java.util.UUID; public class LambdaWithToString implements RequestHandler<Map<String,String>, String> { private final String random = UUID.randomUUID().toString(); @Override public String handleRequest(Map<String, String> stringStringMap, Context context) { return random; } }
8,151
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/DependencyInjection.java
package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class DependencyInjection implements RequestHandler<String, String> { private final MyDependency myDependency; public DependencyInjection(MyDependency myDependency) { this.myDependency = myDependency; } @Override public String handleRequest(String s, Context context) { return myDependency.getUUID().toString(); } }
8,152
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/DeepRngLib.java
package software.amazon.lambda.snapstart.lambdaexamples; public class DeepRngLib { private final RngLib random; public DeepRngLib() { this.random = new RngLib(); } public int randomInt() { return random.randomInt(); } }
8,153
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/NonLambda.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import java.util.Map; import java.util.UUID; /** * This isn't a Lambda function even though it looks like one. */ public class NonLambda { private static final UUID STATIC_USER_ID_UUID = UUID.randomUUID(); private final Double userIdDouble; public NonLambda() { userIdDouble = Math.random(); } public String handleRequest() { return STATIC_USER_ID_UUID.toString(); } }
8,154
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/RngLib.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.lambdaexamples; import java.util.Random; public class RngLib { private final Random random; public RngLib() { this.random = new Random(0); } public int randomInt() { return random.nextInt(); } }
8,155
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/lambdaexamples/LambdaWithParentClass.java
package software.amazon.lambda.snapstart.lambdaexamples; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.logging.Level; import java.util.logging.Logger; public class LambdaWithParentClass extends ParentHandler implements RequestHandler<String, String> { @Override public String handleRequest(String s, Context context) { Logger logger = Logger.getLogger("LambdaWithParentClass"); logger.log(Level.INFO, superParentId.toString()); return parentId.toString(); } }
8,156
0
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart
Create_ds/aws-lambda-snapstart-java-rules/src/test/java/software/amazon/lambda/snapstart/matcher/ContainsMatcher.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart.matcher; import java.util.Arrays; import java.util.Iterator; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.hamcrest.TypeSafeMatcher; public final class ContainsMatcher<T> extends TypeSafeMatcher<Iterable<T>> { private final Iterable<Matcher<T>> matchers; private final Description description; public ContainsMatcher(Iterable<Matcher<T>> matchers) { this.matchers = matchers; this.description = new StringDescription(); } public static <T> Matcher<Iterable<T>> containsAll(final Iterable<Matcher<T>> matchers) { return new ContainsMatcher<>(matchers); } public static <T> Matcher<Iterable<T>> containsAll(final Matcher<T> ... matchers) { return containsAll(Arrays.asList(matchers)); } @Override protected boolean matchesSafely(Iterable<T> items) { Iterator<T> itemsIterator = items.iterator(); Iterator<Matcher<T>> matcherIterator = matchers.iterator(); boolean allItemsMatched = true; while (matcherIterator.hasNext()) { Matcher<T> matcher = matcherIterator.next(); T item = null; if (itemsIterator.hasNext()) { item = itemsIterator.next(); } if (!matcher.matches(item)) { matcher.describeTo(description); description.appendText("\n"); allItemsMatched = false; } } return allItemsMatched; } @Override public void describeTo(final Description desc) { desc.appendText(description.toString()); } }
8,157
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/LambdaHandlerFieldsDatabase.java
package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.ba.interproc.FieldPropertyDatabase; import edu.umd.cs.findbugs.ba.interproc.PropertyDatabaseFormatException; public class LambdaHandlerFieldsDatabase extends FieldPropertyDatabase<Boolean> { public LambdaHandlerFieldsDatabase() { super(); } @Override protected Boolean decodeProperty(String s) throws PropertyDatabaseFormatException { return null; } @Override protected String encodeProperty(Boolean aBoolean) { return null; } }
8,158
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/LambdaHandlerParentsDatabase.java
package software.amazon.lambda.snapstart; import java.util.ArrayList; import java.util.List; public class LambdaHandlerParentsDatabase { private final List<String> parentClasses = new ArrayList<>(); public List<String> getParentClasses() { return this.parentClasses; } public void addLambdaParentClass(String parentClass) { this.parentClasses.add(parentClass); } }
8,159
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/CallGraph.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.ba.interproc.MethodPropertyDatabase; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; public class CallGraph { private Map<MethodDescriptor, Set<MethodDescriptor>> callGraph; public CallGraph() { callGraph = new HashMap<>(); } public boolean isInCallGraph(MethodDescriptor method) { return callGraph.containsKey(method); } public void record(MethodDescriptor caller, MethodDescriptor called) { Set<MethodDescriptor> calledBy = callGraph.computeIfAbsent(called, k -> new HashSet<>()); calledBy.add(caller); } public void flushCallersToDatabase(MethodDescriptor called, MethodPropertyDatabase<Boolean> database, Boolean value) { LinkedList<MethodDescriptor> queue = new LinkedList<>(); queue.push(called); while (!queue.isEmpty()) { MethodDescriptor m = queue.remove(); database.setProperty(m, value); queueCallers(m, queue); } } private void queueCallers(MethodDescriptor called, LinkedList<MethodDescriptor> queue) { Set<MethodDescriptor> callers = callGraph.remove(called); if (callers != null) { for (MethodDescriptor caller : callers) { queue.push(caller); } } } }
8,160
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/CacheLambdaHandlerParentClasses.java
package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.XClass; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.classfile.Global; import java.util.Objects; public class CacheLambdaHandlerParentClasses implements Detector { private final ByteCodeIntrospector introspector; private ClassContext classContext; private XClass xClass; private final LambdaHandlerParentsDatabase database; public CacheLambdaHandlerParentClasses(BugReporter bugReporter) { this.introspector = new ByteCodeIntrospector(); database = new LambdaHandlerParentsDatabase(); Global.getAnalysisCache().eagerlyPutDatabase(LambdaHandlerParentsDatabase.class, database); } @Override public void visitClassContext(ClassContext classContext) { this.classContext = classContext; this.xClass = classContext.getXClass(); if (introspector.isLambdaHandler(xClass)) { JavaClass[] parentClasses = null; try { parentClasses = classContext.getJavaClass().getSuperClasses(); } catch (ClassNotFoundException e) { // Do nothing } if (Objects.nonNull(parentClasses)) { for (JavaClass parentClass : parentClasses) { if (!parentClass.getClassName().equals("java.lang.Object")) { database.addLambdaParentClass(parentClass.getClassName().replace(".", "/")); } } } } } @Override public void report() { // this is a non-reporting detector } }
8,161
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/LambdaHandlerInitedWithRandomValue.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.Const; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; /** * This detector implements a heuristic to detect AWS Lambda functions using the */ public class LambdaHandlerInitedWithRandomValue extends OpcodeStackDetector { private static final String SNAP_START_BUG = "AWS_LAMBDA_SNAP_START_BUG"; private final BugReporter bugReporter; private boolean isLambdaHandlerClass; private boolean isLambdaHandlerParentClass; private boolean implementsFunctionalInterface; private boolean isLambdaHandlerField; private boolean isCracResource; private boolean inInitializer; private boolean inStaticInitializer; private boolean inCracBeforeCheckpoint; private ByteCodeIntrospector introspector; private ReturnValueRandomnessPropertyDatabase database; public LambdaHandlerInitedWithRandomValue(BugReporter bugReporter) { this.bugReporter = bugReporter; this.isLambdaHandlerClass = false; this.isLambdaHandlerParentClass = false; this.implementsFunctionalInterface = false; this.isLambdaHandlerField = false; this.isCracResource = false; this.inInitializer = false; this.inStaticInitializer = false; this.inCracBeforeCheckpoint = false; this.introspector = new ByteCodeIntrospector(); } @Override public void visit(JavaClass obj) { inInitializer = false; inStaticInitializer = false; inCracBeforeCheckpoint = false; XClass xClass = getXClass(); isLambdaHandlerClass = introspector.isLambdaHandler(xClass); isLambdaHandlerParentClass = introspector.isLambdaHandlerParentClass(xClass); implementsFunctionalInterface = introspector.implementsFunctionalInterface(xClass); isLambdaHandlerField = introspector.isLambdaHandlerField(xClass); isCracResource = introspector.isCracResource(xClass); } @Override public boolean shouldVisitCode(Code code) { boolean shouldVisit = false; if (isLambdaHandlerClass || isLambdaHandlerField || isLambdaHandlerParentClass) { inStaticInitializer = getMethodName().equals(Const.STATIC_INITIALIZER_NAME); inInitializer = getMethodName().equals(Const.CONSTRUCTOR_NAME); database = Global.getAnalysisCache().getDatabase(ReturnValueRandomnessPropertyDatabase.class); if (inInitializer || inStaticInitializer) { shouldVisit = true; } } else { inStaticInitializer = false; inInitializer = false; } if (isCracResource) { inCracBeforeCheckpoint = getMethodName().equals("beforeCheckpoint"); if (inCracBeforeCheckpoint) { shouldVisit = true; } } else { inCracBeforeCheckpoint = false; } return shouldVisit; } @Override public void sawOpcode(int seen) { switch (seen) { case Const.PUTSTATIC: case Const.PUTFIELD: { XField xField = getXFieldOperand(); if (getXClass().getXFields().contains(xField)) { if (isOperandStackTopBadRng() || isRandomValue() || isOperandStackTopTimestamp()) { reportBug(xField); } } break; } } } private boolean isOperandStackTopBadRng() { return introspector.isRandomType(getStack()); } private boolean isRandomValue() { XMethod returningMethod = getReturningMethodOrNull(); if (returningMethod == null) { return false; } Boolean returnsRandom = database.getProperty(returningMethod.getMethodDescriptor()); return returnsRandom != null && returnsRandom; } private boolean isOperandStackTopTimestamp() { return introspector.isTimestamp(getStack()); } private void reportBug(XField xField) { BugInstance bug = new BugInstance(this, SNAP_START_BUG, HIGH_PRIORITY) .addClassAndMethod(this.getXMethod()) .addField(xField) .addSourceLine(this); bugReporter.reportBug(bug); } private XMethod getReturningMethodOrNull() { OpcodeStack.Item retValItem = getStack().getStackItem(0); return retValItem.getReturnValueOf(); } }
8,162
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/CacheLambdaHandlerFields.java
package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.FieldDescriptor; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.classfile.Field; /** * This detector stores fields with the Lambda Handler and Crac resources to be used later * for visiting the classes passed in through dependency injection */ public class CacheLambdaHandlerFields implements Detector { private final ByteCodeIntrospector introspector; private ClassContext classContext; private XClass xClass; private final LambdaHandlerFieldsDatabase database; public CacheLambdaHandlerFields(BugReporter reporter) { introspector = new ByteCodeIntrospector(); database = new LambdaHandlerFieldsDatabase(); Global.getAnalysisCache().eagerlyPutDatabase(LambdaHandlerFieldsDatabase.class, database); } @Override public void visitClassContext(ClassContext classContext) { this.classContext = classContext; this.xClass = classContext.getXClass(); if (introspector.isLambdaHandler(xClass)) { Field[] fields = classContext.getJavaClass().getFields(); for (Field field : fields) { FieldDescriptor fieldDescriptor = DescriptorFactory.instance().getFieldDescriptor(xClass.toString().replace(".", "/"), field); database.setProperty(fieldDescriptor, true); } } } @Override public void report() { // this is a non-reporting detector } }
8,163
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/ByteCodeIntrospector.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.FieldDescriptor; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.Type; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; public class ByteCodeIntrospector { private static final String LAMBDA_HANDLER_SIGNATURE = "(Ljava/util/Map;Lcom/amazonaws/services/lambda/runtime/Context;)"; private static final String LAMBDA_STREAMING_HANDLER_SIGNATURE = "(Ljava/io/InputStream;Ljava/io/OutputStream;Lcom/amazonaws/services/lambda/runtime/Context;)"; private static final Set<String> LAMBDA_HANDLER_INTERFACES = new HashSet<String>() {{ add("com.amazonaws.services.lambda.runtime.RequestHandler"); add("com.amazonaws.services.lambda.runtime.RequestStreamHandler"); }}; private static final String FUNCTIONAL_INTERFACE = "java.util.function.Function"; private static final String CRAC_RESOURCE_INTERFACE = "org.crac.Resource"; private static final String RANDOM_SIGNATURE = "Ljava/util/Random;"; private static final String INSTANT_SIGNATURE = "Ljava/time/Instant;"; private static final Map<String, Set<String>> TIMESTAMP_METHODS = new HashMap<String, Set<String>>() {{ put("java.lang.System", setOf("currentTimeMillis", "nanoTime")); }}; private LambdaHandlerParentsDatabase lambdaHandlerParentsDatabase; private LambdaHandlerFieldsDatabase database; private static Set<String> setOf(String ... strings) { Set<String> set = new HashSet<>(); Collections.addAll(set, strings); return set; }; boolean isLambdaHandler(XClass xClass) { return implementsLambdaInterface(xClass) || implementsFunctionalInterface(xClass) || hasLambdaHandlerMethod(xClass) || (hasHandlerInClassName(xClass) && hasHandleRequestMethod(xClass)); } /** * Returns true if the class has the word "Handler" in the name. */ private boolean hasHandlerInClassName(XClass xClass) { return xClass.toString().contains("Handler"); } /** * Returns true if the class has a method called "handleRequest" */ private boolean hasHandleRequestMethod(XClass xClass) { List<? extends XMethod> methods = xClass.getXMethods(); for (XMethod method : methods) { if (method.getName().equals("handleRequest")) { return true; } } return false; } boolean hasLambdaHandlerMethod(XClass xClass) { List<? extends XMethod> methods = xClass.getXMethods(); for (XMethod method : methods) { if (method.getSignature() == null) { continue; } if (method.getSignature().startsWith(LAMBDA_HANDLER_SIGNATURE)) { return true; } if (method.getSignature().startsWith(LAMBDA_STREAMING_HANDLER_SIGNATURE)) { return true; } } return false; } /** * This returns true only when the class directly implements * <a href="https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html">AWS Lambda handler interfaces</a>. */ boolean implementsLambdaInterface(XClass xClass) { for (ClassDescriptor classDescriptor : xClass.getInterfaceDescriptorList()) { try { if (classDescriptor.getXClass().isInterface() && LAMBDA_HANDLER_INTERFACES.contains(classDescriptor.getDottedClassName())) { return true; } } catch (CheckedAnalysisException e) { // ignore } } return false; } boolean isLambdaHandlerParentClass(XClass xClass) { lambdaHandlerParentsDatabase = Global.getAnalysisCache().getDatabase(LambdaHandlerParentsDatabase.class); return lambdaHandlerParentsDatabase.getParentClasses().contains(xClass.toString()); } /** * This returns true only when the class directly implements * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html">Java Functional Interface</a>. */ boolean implementsFunctionalInterface(XClass xClass) { for (ClassDescriptor classDescriptor : xClass.getInterfaceDescriptorList()) { try { if (classDescriptor.getXClass().isInterface() && FUNCTIONAL_INTERFACE.equals(classDescriptor.getDottedClassName())) { return true; } } catch (CheckedAnalysisException e) { // ignore } } return false; } /** * This returns true only if this class is used as a field in a Lambda handler class */ boolean isLambdaHandlerField(XClass xClass) { database = Global.getAnalysisCache().getDatabase(LambdaHandlerFieldsDatabase.class); for (FieldDescriptor fieldDescriptor : database.getKeys()) { String fieldType = Type.getReturnType(fieldDescriptor.getSignature()).toString().replace(".", "/"); if (fieldType.equals(xClass.toString())) { return true; } } return false; } /** * This returns true only when the class directly implements the CRaC (Coordinated Restore at Checkpoint) * <a href="https://javadoc.io/doc/io.github.crac/org-crac/latest/org/crac/Resource.html">Resource interface</a>. */ boolean isCracResource(XClass xClass) { for (ClassDescriptor classDescriptor : xClass.getInterfaceDescriptorList()) { try { if (classDescriptor.getXClass().isInterface()) { if (CRAC_RESOURCE_INTERFACE.equals(classDescriptor.getDottedClassName())) { return true; } } } catch (CheckedAnalysisException e) { // ignore } } return false; } /** * Return true if is {@link Random} type. * Otherwise, return false. */ boolean isRandomType(OpcodeStack stack) { return RANDOM_SIGNATURE.equals(stack.getStackItem(0).getSignature()); } /** * Return true if: * - is Instant type * - is a known method that returns a timestamp-like value, such as {@link System#currentTimeMillis()} * Otherwise, return false. */ boolean isTimestamp(OpcodeStack stack) { if (INSTANT_SIGNATURE.equals(stack.getStackItem(0).getSignature())) { return true; } XMethod xMethod = stack.getStackItem(0).getReturnValueOf(); if (xMethod != null) { Set<String> methodNames = TIMESTAMP_METHODS.get(xMethod.getClassName()); if (methodNames != null) { return methodNames.contains(xMethod.getName()); } } return false; } }
8,164
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/BuildRandomReturningMethodsDatabase.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.MissingClassException; import edu.umd.cs.findbugs.ba.SignatureConverter; import edu.umd.cs.findbugs.ba.ca.Call; import edu.umd.cs.findbugs.ba.ca.CallList; import edu.umd.cs.findbugs.ba.ca.CallListDataflow; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.log.Profiler; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.bcel.Const; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.ReturnInstruction; /** * This class is a detector implementation which runs in the first pass of analysis. With a very simplistic assumption * this identifies whether a method might return a pseudo-random value purely based on the fact that it calls a method * that's already known to return a pseudo-random value. A better approach is doing proper dataflow analysis to * understand whether the pseudo-random value makes it to the return instruction. */ public class BuildRandomReturningMethodsDatabase implements Detector { private final BugReporter bugReporter; private final BugAccumulator bugAccumulator; private final ReturnValueRandomnessPropertyDatabase database; private final ByteCodeIntrospector introspector; // Transient state private ClassContext classContext; private Method method; private MethodDescriptor methodDescriptor; private CallListDataflow callListDataflow; private Map<Call, MethodDescriptor> callMethodDescriptorMap; private CallGraph callGraph; public BuildRandomReturningMethodsDatabase(BugReporter reporter) { this.bugReporter = reporter; this.bugAccumulator = new BugAccumulator(reporter); database = new ReturnValueRandomnessPropertyDatabase(); Global.getAnalysisCache().eagerlyPutDatabase(ReturnValueRandomnessPropertyDatabase.class, database); callGraph = new CallGraph(); callMethodDescriptorMap = new HashMap<>(); introspector = new ByteCodeIntrospector(); } @Override public void visitClassContext(ClassContext classContext) { this.classContext = classContext; String currentMethod = null; List<Method> methodsInCallOrder = classContext.getMethodsInCallOrder(); for (Method method : methodsInCallOrder) { try { if (method.isAbstract() || method.isNative() || method.getCode() == null) { continue; } currentMethod = SignatureConverter.convertMethodSignature(classContext.getJavaClass(), method); analyzeMethod(method); } catch (MissingClassException e) { bugReporter.reportMissingClass(e.getClassNotFoundException()); } catch (DataflowAnalysisException | CFGBuilderException e) { bugReporter.logError("While analyzing " + currentMethod + ": BuildRandomReturningMethodsDatabase caught an exception", e); } bugAccumulator.reportAccumulatedBugs(); } } private void analyzeMethod(Method method) throws DataflowAnalysisException, CFGBuilderException { if ((method.getAccessFlags() & Const.ACC_BRIDGE) != 0) { return; } this.method = method; this.methodDescriptor = DescriptorFactory.instance().getMethodDescriptor(classContext.getJavaClass(), method); callListDataflow = classContext.getCallListDataflow(method); checkInvokeAndReturnInstructions(); } private void checkInvokeAndReturnInstructions() { Profiler profiler = Global.getAnalysisCache().getProfiler(); profiler.start(BuildRandomReturningMethodsDatabase.class); try { for (Iterator<Location> i = classContext.getCFG(method).locationIterator(); i.hasNext();) { Location location = i.next(); Instruction ins = location.getHandle().getInstruction(); if (ins instanceof ReturnInstruction) { examineReturnInstruction(location); } else if (ins instanceof InvokeInstruction) { examineInvokeInstruction((InvokeInstruction) ins); } } } catch (CheckedAnalysisException e) { AnalysisContext.logError("error:", e); } finally { profiler.end(BuildRandomReturningMethodsDatabase.class); } } private void examineInvokeInstruction(InvokeInstruction inv) { ConstantPoolGen cpg = classContext.getConstantPoolGen(); MethodDescriptor md = new MethodDescriptor(inv, classContext.getConstantPoolGen()); Call call = new Call(inv.getClassName(cpg), inv.getName(cpg), inv.getSignature(cpg)); callMethodDescriptorMap.put(call, md); } private void examineReturnInstruction(Location location) throws DataflowAnalysisException { // We have a crude assumption here that is any method call effects the return value of the caller method. CallList callList = callListDataflow.getFactAtLocation(location); if (!callList.isValid()) { return; } Iterator<Call> callIterator = callList.callIterator(); while (callIterator.hasNext()) { Call call = callIterator.next(); MethodDescriptor caller = methodDescriptor; MethodDescriptor called = callMethodDescriptorMap.get(call); if (called != null) { recordCalledMethod(caller, called); } } } private void recordCalledMethod(MethodDescriptor caller, MethodDescriptor called) { Boolean returnsRandom = database.getProperty(called); if (returnsRandom != null && returnsRandom) { callGraph.flushCallersToDatabase(caller, database, true); } else { if (callGraph.isInCallGraph(caller) || isLambdaHandlerInitMethod()) { // Call chain from Lambda event handler checks out callGraph.record(caller, called); } } } private boolean isLambdaHandlerInitMethod() { if (introspector.isLambdaHandler(classContext.getXClass())) { return Const.STATIC_INITIALIZER_NAME.equals(method.getName()) || Const.CONSTRUCTOR_NAME.equals(method.getName()); } return false; } @Override public void report() { // this is a non-reporting detector } }
8,165
0
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda
Create_ds/aws-lambda-snapstart-java-rules/src/main/java/software/amazon/lambda/snapstart/ReturnValueRandomnessPropertyDatabase.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.lambda.snapstart; import edu.umd.cs.findbugs.ba.interproc.MethodPropertyDatabase; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ReturnValueRandomnessPropertyDatabase extends MethodPropertyDatabase<Boolean> { private static final Set<MethodDescriptor> ALREADY_KNOWN_PSEUDO_RANDOM_GEN_METHODS = new HashSet<>(Arrays.asList( new MethodDescriptor("java/lang/Math", "random", "()D", true), new MethodDescriptor("java/util/UUID", "randomUUID", "()Ljava/util/UUID;", true), new MethodDescriptor("java/util/UUID", "toString", "()Ljava/lang/String;"), new MethodDescriptor("java/util/Random", "nextInt", "()I"), new MethodDescriptor("java/lang/StrictMath", "random", "()D", true) )); public ReturnValueRandomnessPropertyDatabase() { super(); for (MethodDescriptor d : ALREADY_KNOWN_PSEUDO_RANDOM_GEN_METHODS) { setProperty(d, true); } } @Override protected Boolean decodeProperty(String propStr) { return Boolean.parseBoolean(propStr); } @Override protected String encodeProperty(Boolean property) { return property.toString(); } }
8,166
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/util/CollectionUnwrapperTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.util; import com.netflix.zeno.util.CollectionUnwrapper; import com.netflix.zeno.util.collections.MinimizedUnmodifiableCollections; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.junit.Assert; import org.junit.Test; public class CollectionUnwrapperTest { @Test public void unwrapsLists() { List<Integer> list = Arrays.asList(1, 2, 3); List<Integer> wrapped = Collections.unmodifiableList(list); Assert.assertSame(list, CollectionUnwrapper.unwrap(wrapped)); } @Test public void unwrapsSets() { Set<Integer> set = new HashSet<Integer>(); set.add(1); Set<Integer> wrapped = Collections.unmodifiableSet(set); Assert.assertSame(set, CollectionUnwrapper.unwrap(wrapped)); } @Test public void unwrapsMaps() { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 2); Map<Integer, Integer> wrapped = Collections.unmodifiableMap(map); Assert.assertSame(map, CollectionUnwrapper.unwrap(wrapped)); } @Test public void returnsNonCollectionsUnchanged() { Object o = new Object(); Assert.assertSame(o, CollectionUnwrapper.unwrap(o)); } @Test public void unwrapsMultiplyWrappedCollections() { List<Integer> list = Arrays.asList(1, 2, 3); List<Integer> wrapped = Collections.unmodifiableList(list); List<Integer> doubleWrapped = Collections.unmodifiableList(wrapped); Assert.assertSame(list, CollectionUnwrapper.unwrap(doubleWrapped)); } @Test public void returnsCanonicalVersionsOfEmptyCollections() { Assert.assertSame(Collections.EMPTY_LIST, CollectionUnwrapper.unwrap(new ArrayList<Object>())); Assert.assertSame(Collections.EMPTY_SET, CollectionUnwrapper.unwrap(new HashSet<Object>())); Assert.assertSame(MinimizedUnmodifiableCollections.EMPTY_SORTED_MAP, CollectionUnwrapper.unwrap(new TreeMap<Object, Object>())); Assert.assertSame(Collections.EMPTY_MAP, CollectionUnwrapper.unwrap(new HashMap<Object, Object>())); } }
8,167
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/impl/OpenAddressArraySetTest.java
package com.netflix.zeno.util.collections.impl; import com.netflix.zeno.util.collections.builder.SetBuilder; import java.util.Iterator; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class OpenAddressArraySetTest { @Test public void populateAndRetrieve() { SetBuilder<Integer> setBuilder = new OpenAddressingArraySet<Integer>(); setBuilder.builderInit(15); setBuilder.builderSet(0, 0); setBuilder.builderSet(1, 1); setBuilder.builderSet(2, null); setBuilder.builderSet(3, 2); setBuilder.builderSet(4, 3); Set<Integer> set = setBuilder.builderFinish(); Assert.assertEquals(5, set.size()); Assert.assertTrue(set.contains(0)); Assert.assertTrue(set.contains(3)); Assert.assertTrue(set.contains(null)); Assert.assertFalse(set.contains(4)); Iterator<Integer> iter = set.iterator(); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(Integer.valueOf(0), iter.next()); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(Integer.valueOf(1), iter.next()); Assert.assertTrue(iter.hasNext()); Assert.assertNull(iter.next()); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(Integer.valueOf(2), iter.next()); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(Integer.valueOf(3), iter.next()); Assert.assertFalse(iter.hasNext()); } }
8,168
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/impl/OpenAddressHashMapTest.java
package com.netflix.zeno.util.collections.impl; import com.netflix.zeno.util.collections.builder.MapBuilder; import java.util.Iterator; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class OpenAddressHashMapTest { @Test public void putAndRetrieve() { MapBuilder<Integer, Integer> builder = new OpenAddressingHashMap<Integer, Integer>(); builder.builderInit(5); builder.builderPut(0, 1, 2); builder.builderPut(1, 3, 4); builder.builderPut(2, 5, 6); builder.builderPut(3, 7, 8); builder.builderPut(4, 9, 0); Map<Integer, Integer> map = builder.builderFinish(); Assert.assertEquals(Integer.valueOf(2), map.get(1)); Assert.assertEquals(Integer.valueOf(4), map.get(3)); Assert.assertEquals(Integer.valueOf(6), map.get(5)); Assert.assertEquals(Integer.valueOf(8), map.get(7)); Assert.assertEquals(Integer.valueOf(0), map.get(9)); Assert.assertEquals(5, map.size()); } @Test public void putAndRetrieveWithNullValues() { MapBuilder<Integer, Integer> builder = new OpenAddressingHashMap<Integer, Integer>(); builder.builderInit(5); builder.builderPut(0, 1, 2); builder.builderPut(1, 3, 4); builder.builderPut(2, 5, null); builder.builderPut(3, 7, 8); builder.builderPut(4, 9, 0); Map<Integer, Integer> map = builder.builderFinish(); Assert.assertEquals(Integer.valueOf(2), map.get(1)); Assert.assertEquals(Integer.valueOf(4), map.get(3)); Assert.assertEquals(null, map.get(5)); Assert.assertEquals(Integer.valueOf(8), map.get(7)); Assert.assertEquals(Integer.valueOf(0), map.get(9)); Assert.assertEquals(5, map.size()); } @Test public void putAndRetrieveWithNullKeys() { MapBuilder<Integer, Integer> builder = new OpenAddressingHashMap<Integer, Integer>(); builder.builderInit(5); builder.builderPut(0, 1, 2); builder.builderPut(1, 3, 4); builder.builderPut(2, null, 6); builder.builderPut(3, 7, 8); builder.builderPut(4, 9, 0); Map<Integer, Integer> map = builder.builderFinish(); Assert.assertEquals(Integer.valueOf(2), map.get(1)); Assert.assertEquals(Integer.valueOf(4), map.get(3)); Assert.assertEquals(Integer.valueOf(6), map.get(null)); Assert.assertEquals(Integer.valueOf(8), map.get(7)); Assert.assertEquals(Integer.valueOf(0), map.get(9)); Assert.assertEquals(5, map.size()); } @Test public void sizeIsCorrectBasedOnNumberOfItemsAdded() { MapBuilder<Integer, Integer> builder = new OpenAddressingHashMap<Integer, Integer>(); builder.builderInit(10); builder.builderPut(0, 1, 2); builder.builderPut(1, 3, 4); builder.builderPut(2, null, 6); builder.builderPut(3, 7, 8); builder.builderPut(4, 9, 0); Map<Integer, Integer> map = builder.builderFinish(); Assert.assertEquals(Integer.valueOf(2), map.get(1)); Assert.assertEquals(Integer.valueOf(4), map.get(3)); Assert.assertEquals(Integer.valueOf(6), map.get(null)); Assert.assertEquals(Integer.valueOf(8), map.get(7)); Assert.assertEquals(Integer.valueOf(0), map.get(9)); Assert.assertEquals(5, map.size()); } @Test public void sortedHashMapIteratesSortedEntries() { MapBuilder<Integer, Integer> builder = new OpenAddressingSortedHashMap<Integer, Integer>(); builder.builderInit(10); builder.builderPut(0, 7, 8); builder.builderPut(1, 9, 0); builder.builderPut(2, 3, 4); builder.builderPut(3, 1, 2); builder.builderPut(4, null, 6); Map<Integer, Integer> map = builder.builderFinish(); Assert.assertEquals(Integer.valueOf(2), map.get(1)); Assert.assertEquals(Integer.valueOf(4), map.get(3)); Assert.assertEquals(Integer.valueOf(6), map.get(null)); Assert.assertEquals(Integer.valueOf(8), map.get(7)); Assert.assertEquals(Integer.valueOf(0), map.get(9)); Assert.assertEquals(5, map.size()); Iterator<Map.Entry<Integer, Integer>> entryIter = map.entrySet().iterator(); Assert.assertTrue(entryIter.hasNext()); Map.Entry<Integer, Integer> curEntry = entryIter.next(); Assert.assertEquals(null, curEntry.getKey()); Assert.assertEquals(Integer.valueOf(6), curEntry.getValue()); Assert.assertTrue(entryIter.hasNext()); curEntry = entryIter.next(); Assert.assertEquals(Integer.valueOf(1), curEntry.getKey()); Assert.assertEquals(Integer.valueOf(2), curEntry.getValue()); Assert.assertTrue(entryIter.hasNext()); curEntry = entryIter.next(); Assert.assertEquals(Integer.valueOf(3), curEntry.getKey()); Assert.assertEquals(Integer.valueOf(4), curEntry.getValue()); Assert.assertTrue(entryIter.hasNext()); curEntry = entryIter.next(); Assert.assertEquals(Integer.valueOf(7), curEntry.getKey()); Assert.assertEquals(Integer.valueOf(8), curEntry.getValue()); Assert.assertTrue(entryIter.hasNext()); curEntry = entryIter.next(); Assert.assertEquals(Integer.valueOf(9), curEntry.getKey()); Assert.assertEquals(Integer.valueOf(0), curEntry.getValue()); Assert.assertFalse(entryIter.hasNext()); } }
8,169
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/heapfriendly/PhasedHeapFriendlyHashMapTest.java
/* * * Copyright 2015 Netflix, 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.netflix.zeno.util.collections.heapfriendly; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** * JUnit tests for {@link PhasedHeapFriendlyHashMap} * * @author drbathgate * */ public class PhasedHeapFriendlyHashMapTest { @Test public void setAndGet() { Map<String, Integer> map = getMap(30000); for(int i=0;i<30000;i++) { Assert.assertTrue(map.containsKey(String.valueOf(i))); Integer val = map.get(String.valueOf(i)); Assert.assertEquals(i, val.intValue()); } for(int i=30000;i<60000;i++) { Assert.assertFalse(map.containsKey(String.valueOf(i))); Assert.assertNull(map.get(String.valueOf(i))); } } @Test public void putWithSameDerivableKeyReplacesExistingEntry() { PhasedHeapFriendlyHashMap<String, Integer> map = new PhasedHeapFriendlyHashMap<String, Integer>(); Integer one1 = new Integer(1); Integer one2 = new Integer(1); map.beginDataSwapPhase(1); map.put("1", one1); map.endDataSwapPhase(); Assert.assertSame(one1, map.get("1")); map.beginDataSwapPhase(1); map.put("1", one1); map.put("1", one2); map.endDataSwapPhase(); Assert.assertNotSame(one1, map.get("1")); Assert.assertSame(one2, map.get("1")); } @Test public void testEntrySet() { PhasedHeapFriendlyHashMap<String, Integer> map = getMap(2500); Set<Integer> allValues = new HashSet<Integer>(); for(Map.Entry<String, Integer> entry : map.entrySet()) { Assert.assertEquals(String.valueOf(entry.getValue()), entry.getKey()); allValues.add(entry.getValue()); } for(int i=0;i<2500;i++) { Assert.assertTrue(allValues.contains(Integer.valueOf(i))); } } @Test public void testKeySet() { PhasedHeapFriendlyHashMap<String, Integer> map = getMap(2500); Set<String> allKeys = new HashSet<String>(); Set<String> keySet = map.keySet(); for(String key : keySet) { Assert.assertTrue(keySet.contains(key)); allKeys.add(key); } for(int i=0;i<2500;i++) { Assert.assertTrue(keySet.contains(String.valueOf(i))); Assert.assertTrue(allKeys.contains(String.valueOf(i))); } } @Test public void testValueSet() { PhasedHeapFriendlyHashMap<String, Integer> map = getMap(2500); Set<Integer> allKeys = new HashSet<Integer>(); Collection<Integer> values = map.values(); for(Integer value : values) { Assert.assertTrue(values.contains(value)); allKeys.add(value); } for(int i=0;i<2500;i++) { Assert.assertTrue(values.contains(Integer.valueOf(i))); Assert.assertTrue(allKeys.contains(Integer.valueOf(i))); } } @Test public void testImproperPut() { boolean exceptionThrown = false; PhasedHeapFriendlyHashMap<String, Integer> map = new PhasedHeapFriendlyHashMap<String, Integer>(); try { map.put("1", 1); } catch (IllegalStateException e) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); } @Test public void testImproperGet() { PhasedHeapFriendlyHashMap<String, Integer> map = new PhasedHeapFriendlyHashMap<String, Integer>(); map.beginDataSwapPhase(1); map.put("1", 1); Assert.assertNull(map.get("1")); map.endDataSwapPhase(); Assert.assertNotNull(map.get("1")); } @Test public void testImproperBeginSwapPhase() { boolean exceptionThrown = false; PhasedHeapFriendlyHashMap<String, Integer> map = new PhasedHeapFriendlyHashMap<String, Integer>(); map.beginDataSwapPhase(1); try { map.beginDataSwapPhase(1); } catch (IllegalStateException e) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); } @Test public void testImproperEndSwapPhase() { boolean exceptionThrown = false; PhasedHeapFriendlyHashMap<String, Integer> map = new PhasedHeapFriendlyHashMap<String, Integer>(); try { map.endDataSwapPhase(); } catch (IllegalStateException e) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); } private PhasedHeapFriendlyHashMap<String, Integer> getMap(int numOfEntries){ PhasedHeapFriendlyHashMap<String, Integer> map = new PhasedHeapFriendlyHashMap<String, Integer>(); map.beginDataSwapPhase(numOfEntries); for (int i = 0; i < numOfEntries; i++) { map.put(String.valueOf(i), i); } map.endDataSwapPhase(); return map; } }
8,170
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/heapfriendly/OpenAddressingHashMapTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.util.collections.heapfriendly; import com.netflix.zeno.util.collections.builder.MapBuilder; import com.netflix.zeno.util.collections.impl.OpenAddressingHashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class OpenAddressingHashMapTest { @Test public void mustHandleNullElements() { MapBuilder<Integer, String> builder = new OpenAddressingHashMap<Integer, String>(); builder.builderInit(3); builder.builderPut(0, 1, "1"); builder.builderPut(1, null, "2"); builder.builderPut(2, 3, "3"); Map<Integer, String> map = builder.builderFinish(); Assert.assertEquals(3, map.size()); Assert.assertEquals("1", map.get(1)); Assert.assertEquals("2", map.get(null)); Assert.assertEquals("3", map.get(3)); } @Test public void mustNotBreakWhenInitIsHintedWithTooManyElements() { MapBuilder<Integer, String> builder = new OpenAddressingHashMap<Integer, String>(); builder.builderInit(4); builder.builderPut(0, 1, "1"); builder.builderPut(1, 2, "2"); Map<Integer, String> map = builder.builderFinish(); Assert.assertEquals("1", map.get(1)); Assert.assertEquals("2", map.get(2)); Assert.assertEquals(null, map.get(null)); //TODO: Fix the map.size(); //Assert.assertEquals(2, map.size()); } }
8,171
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/heapfriendly/HeapFriendlyHashMapTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.util.collections.heapfriendly; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HeapFriendlyHashMapTest { private HeapFriendlyMapArrayRecycler recycler; @Before public void setUp() { recycler = HeapFriendlyMapArrayRecycler.get(); recycler.clear(); } @After public void tearDown() { recycler.clear(); } @Test public void setAndGet() { Map<String, Integer> map = getMap(30000); for(int i=0;i<30000;i++) { Assert.assertTrue(map.containsKey(String.valueOf(i))); Integer val = map.get(String.valueOf(i)); Assert.assertEquals(i, val.intValue()); } for(int i=30000;i<60000;i++) { Assert.assertFalse(map.containsKey(String.valueOf(i))); Assert.assertNull(map.get(String.valueOf(i))); } } @Test public void putWithSameDerivableKeyReplacesExistingEntry() { HeapFriendlyHashMap<String, Integer> map = new HeapFriendlyHashMap<String, Integer>(1); Integer one1 = new Integer(1); Integer one2 = new Integer(1); map.put("1", one1); Assert.assertSame(one1, map.get("1")); map.put("1", one2); Assert.assertNotSame(one1, map.get("1")); Assert.assertSame(one2, map.get("1")); } @Test public void testEntrySet() { HeapFriendlyHashMap<String, Integer> map = getMap(2500); Set<Integer> allValues = new HashSet<Integer>(); for(Map.Entry<String, Integer> entry : map.entrySet()) { Assert.assertEquals(String.valueOf(entry.getValue()), entry.getKey()); allValues.add(entry.getValue()); } for(int i=0;i<2500;i++) { Assert.assertTrue(allValues.contains(Integer.valueOf(i))); } } @Test public void testKeySet() { HeapFriendlyHashMap<String, Integer> map = getMap(2500); Set<String> allKeys = new HashSet<String>(); Set<String> keySet = map.keySet(); for(String key : keySet) { Assert.assertTrue(keySet.contains(key)); allKeys.add(key); } for(int i=0;i<2500;i++) { Assert.assertTrue(keySet.contains(String.valueOf(i))); Assert.assertTrue(allKeys.contains(String.valueOf(i))); } } @Test public void testValueSet() { HeapFriendlyHashMap<String, Integer> map = getMap(2500); Set<Integer> allKeys = new HashSet<Integer>(); Collection<Integer> values = map.values(); for(Integer value : values) { Assert.assertTrue(values.contains(value)); allKeys.add(value); } for(int i=0;i<2500;i++) { Assert.assertTrue(values.contains(Integer.valueOf(i))); Assert.assertTrue(allKeys.contains(Integer.valueOf(i))); } } @Test public void recyclesObjectArraysFromAlternatingCycles() throws Exception { HeapFriendlyMapArrayRecycler recycler = HeapFriendlyMapArrayRecycler.get(); HeapFriendlyHashMap<String, Integer> map = getMap(100); Object[] firstKeySegment = getFirstSegment(map, "keys"); Object[] firstValueSegment = getFirstSegment(map, "values"); recycler.swapCycleObjectArrays(); map.releaseObjectArrays(); map = getMap(100); Object[] differentFirstKeySegment = getFirstSegment(map, "keys"); Object[] differentFirstValueSegment = getFirstSegment(map, "values"); /// neither arrays are recycled from the first cycle. Assert.assertNotSame(firstKeySegment, differentFirstKeySegment); Assert.assertNotSame(firstValueSegment, differentFirstValueSegment); Assert.assertNotSame(firstKeySegment, differentFirstValueSegment); Assert.assertNotSame(firstValueSegment, differentFirstKeySegment); recycler.swapCycleObjectArrays(); map.releaseObjectArrays(); map = getMap(100); Object[] firstKeySegmentAgain = getFirstSegment(map, "keys"); Object[] firstValueSegmentAgain = getFirstSegment(map, "values"); /// both arrays are recycled, but it doesn't matter whether which was initially for the keys and which was initially for the values. Assert.assertTrue(firstKeySegmentAgain == firstKeySegment || firstKeySegmentAgain == firstValueSegment); Assert.assertTrue(firstValueSegmentAgain == firstKeySegment || firstValueSegmentAgain == firstValueSegment); } @Test public void sizeIsCorrectAfterReplacement() { HeapFriendlyHashMap<String, String> map = new HeapFriendlyHashMap<String, String>(2); map.put("a", "b"); map.put("b", "d"); map.put("a", "c"); Assert.assertEquals(2, map.size()); } private Object[] getFirstSegment(HeapFriendlyHashMap<String, Integer> map, String fieldName) throws Exception { Field f = HeapFriendlyHashMap.class.getDeclaredField(fieldName); f.setAccessible(true); return ((Object[][])f.get(map))[0]; } private HeapFriendlyHashMap<String, Integer> getMap(int numEntries) { HeapFriendlyHashMap<String, Integer> map = new HeapFriendlyHashMap<String, Integer>(numEntries); for(int i=0;i<numEntries;i++) { map.put(String.valueOf(i), Integer.valueOf(i)); } return map; } }
8,172
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/heapfriendly/HeapFriendlyDerivableKeyHashMapTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.util.collections.heapfriendly; import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyDerivableKeyHashMap; import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyMapArrayRecycler; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HeapFriendlyDerivableKeyHashMapTest { private HeapFriendlyMapArrayRecycler recycler; @Before public void setUp() { recycler = HeapFriendlyMapArrayRecycler.get(); recycler.clear(); } @After public void tearDown() { recycler.clear(); } @Test public void setAndGet() { Map<String, Integer> map = getMap(30000); for(int i=0;i<30000;i++) { Assert.assertTrue(map.containsKey(String.valueOf(i))); Integer val = map.get(String.valueOf(i)); Assert.assertEquals(i, val.intValue()); } for(int i=30000;i<60000;i++) { Assert.assertFalse(map.containsKey(String.valueOf(i))); Assert.assertNull(map.get(String.valueOf(i))); } } @Test public void putWithSameDerivableKeyReplacesExistingEntry() { HeapFriendlyDerivableKeyHashMap<String, Integer> map = new HeapFriendlyDerivableKeyHashMap<String, Integer>(1) { protected String deriveKey(Integer value) { return String.valueOf(value); } }; Integer one1 = new Integer(1); Integer one2 = new Integer(1); map.put(one1); Assert.assertSame(one1, map.get("1")); map.put(one2); Assert.assertNotSame(one1, map.get("1")); Assert.assertSame(one2, map.get("1")); } @Test public void testEntrySet() { HeapFriendlyDerivableKeyHashMap<String, Integer> map = getMap(2500); Set<Integer> allValues = new HashSet<Integer>(); for(Map.Entry<String, Integer> entry : map.entrySet()) { Assert.assertEquals(String.valueOf(entry.getValue()), entry.getKey()); allValues.add(entry.getValue()); } for(int i=0;i<2500;i++) { Assert.assertTrue(allValues.contains(Integer.valueOf(i))); } } @Test public void testKeySet() { HeapFriendlyDerivableKeyHashMap<String, Integer> map = getMap(2500); Set<String> allKeys = new HashSet<String>(); Set<String> keySet = map.keySet(); for(String key : keySet) { Assert.assertTrue(keySet.contains(key)); allKeys.add(key); } for(int i=0;i<2500;i++) { Assert.assertTrue(keySet.contains(String.valueOf(i))); Assert.assertTrue(allKeys.contains(String.valueOf(i))); } } @Test public void testValueSet() { HeapFriendlyDerivableKeyHashMap<String, Integer> map = getMap(2500); Set<Integer> allKeys = new HashSet<Integer>(); Collection<Integer> values = map.values(); for(Integer value : values) { Assert.assertTrue(values.contains(value)); allKeys.add(value); } for(int i=0;i<2500;i++) { Assert.assertTrue(values.contains(Integer.valueOf(i))); Assert.assertTrue(allKeys.contains(Integer.valueOf(i))); } } @Test public void recyclesObjectArraysFromAlternatingCycles() throws Exception { HeapFriendlyMapArrayRecycler recycler = HeapFriendlyMapArrayRecycler.get(); HeapFriendlyDerivableKeyHashMap<String, Integer> map = getMap(100); Object[] firstSegment = getFirstSegment(map); recycler.swapCycleObjectArrays(); map.releaseObjectArrays(); recycler.clearNextCycleObjectArrays(); map = getMap(100); Object[] differentFirstSegment = getFirstSegment(map); Assert.assertNotSame(firstSegment, differentFirstSegment); recycler.swapCycleObjectArrays(); map.releaseObjectArrays(); recycler.clearNextCycleObjectArrays(); map = getMap(100); Object[] firstSegmentAgain = getFirstSegment(map); Assert.assertSame(firstSegment, firstSegmentAgain); } @Test public void sizeIsCorrectAfterReplacement() { HeapFriendlyDerivableKeyHashMap<String, String> map = new HeapFriendlyDerivableKeyHashMap<String, String>(2) { protected String deriveKey(String value) { return value; } }; map.put("a"); map.put("b"); map.put("a"); Assert.assertEquals(2, map.size()); } private Object[] getFirstSegment(HeapFriendlyDerivableKeyHashMap<String, Integer> map) throws Exception { Field f = HeapFriendlyDerivableKeyHashMap.class.getDeclaredField("values"); f.setAccessible(true); return ((Object[][])f.get(map))[0]; } private HeapFriendlyDerivableKeyHashMap<String, Integer> getMap(int numEntries) { HeapFriendlyDerivableKeyHashMap<String, Integer> map = new HeapFriendlyDerivableKeyHashMap<String, Integer>(numEntries) { protected String deriveKey(Integer value) { return String.valueOf(value); } }; for(int i=0;i<numEntries;i++) { Integer value = Integer.valueOf(i); map.put(value); } return map; } }
8,173
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/heapfriendly/HeapFriendlyMapRandomizedTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.util.collections.heapfriendly; import com.netflix.zeno.util.collections.heapfriendly.AbstractHeapFriendlyMap; import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyDerivableKeyHashMap; import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyHashMap; import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyMapArrayRecycler; import java.util.Map; import java.util.Random; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HeapFriendlyMapRandomizedTest { private final Random rand = new Random(); @Before public void setUp() { HeapFriendlyMapArrayRecycler.get().clearNextCycleObjectArrays(); } @Test public void randomlyTestHeapFriendlyMap() { /// 4 cycles for(int i=0;i<4;i++) { ///prepare by swapping the cycle Object arrays HeapFriendlyMapArrayRecycler.get().swapCycleObjectArrays(); AbstractHeapFriendlyMap<Integer, String> map = createRandomMap(10000); /// arrays may be "released" as long as the clearNextCycleObjectArrays is not called before calls are completed. map.releaseObjectArrays(); int counter = 0; for(Map.Entry<Integer, String> entry : map.entrySet()) { int key = entry.getKey().intValue(); String value = entry.getValue(); /// the key should be mapped to the expected value Assert.assertEquals(key, Integer.parseInt(value)); /// and we should be able to look up that value Assert.assertEquals(value, map.get(entry.getKey())); counter++; } /// make sure map.size() is correct Assert.assertEquals(counter, map.size()); /// must clear all arrays in the recycler before they are reused in the next cycle. HeapFriendlyMapArrayRecycler.get().clearNextCycleObjectArrays(); } } private AbstractHeapFriendlyMap<Integer, String> createRandomMap(int numElements) { if(rand.nextBoolean()) { HeapFriendlyHashMap<Integer, String> map = new HeapFriendlyHashMap<Integer, String>(numElements); for(int i=0;i<numElements;i++) { int value = rand.nextInt(); map.put(Integer.valueOf(value), String.valueOf(value)); } return map; } else { HeapFriendlyDerivableKeyHashMap<Integer, String> map = new HeapFriendlyDerivableKeyHashMap<Integer, String>(numElements) { protected Integer deriveKey(String value) { return Integer.valueOf(value); } }; for(int i=0;i<numElements;i++) { int value = rand.nextInt(); map.put(String.valueOf(value)); } return map; } } }
8,174
0
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections
Create_ds/zeno/src/test/java/com/netflix/zeno/util/collections/algorithms/ArrayQuickSortTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.util.collections.algorithms; import com.netflix.zeno.util.collections.Comparators; import java.util.ArrayList; import java.util.Comparator; import java.util.Random; import org.junit.Assert; import org.junit.Test; public class ArrayQuickSortTest { private static final int NUM_ITERATIONS = 1000; private static final int LIST_SIZE = 1000; private static final Random rand = new Random(); @Test public void testRandomData() { for(int i=0;i<NUM_ITERATIONS;i++) { IntegerArray arr = createShuffledArray(LIST_SIZE); Comparator<Integer> comparator = Comparators.comparableComparator(); ArrayQuickSort.sort(arr, comparator); assertSorted(arr); } } private IntegerArray createShuffledArray(int size) { IntegerArray arr = new IntegerArray(size); for(int i=0;i<LIST_SIZE;i++) { arr.add(Integer.valueOf(rand.nextInt())); } return arr; } private void assertSorted(IntegerArray arr) { Integer currentValue = arr.get(0); for(int i=1;i<arr.size();i++) { Assert.assertTrue(currentValue.intValue() <= arr.get(i).intValue()); currentValue = arr.get(i); } } @SuppressWarnings("serial") public class IntegerArray extends ArrayList<Integer> implements Sortable<Integer> { public IntegerArray(int size) { super(size); } @Override public Integer at(int index) { return get(index); } @Override public void swap(int i1, int i2) { Integer temp = get(i1); set(i1, get(i2)); set(i2, temp); } } }
8,175
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/UndefinedNullCollectionElementSerializerTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; import com.netflix.zeno.fastblob.io.FastBlobReader; import com.netflix.zeno.fastblob.io.FastBlobWriter; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType; import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState; import com.netflix.zeno.serializer.NFDeserializationRecord; import com.netflix.zeno.serializer.NFSerializationRecord; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.serializer.common.ListSerializer; import com.netflix.zeno.serializer.common.MapSerializer; import com.netflix.zeno.serializer.common.SetSerializer; public class UndefinedNullCollectionElementSerializerTest { @Test public void includesLegitimatelyNullElementsButNotUndefinedElementsInList() throws IOException { final ListSerializer<Integer> listSerializer = new ListSerializer<Integer>(new FakeIntSerializer()); FastBlobStateEngine stateEngine = new FastBlobStateEngine(new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { listSerializer }; } }); List<Integer> inList = Arrays.asList(1, 2, 3, null, 4); stateEngine.add(listSerializer.getName(), inList, FastBlobImageUtils.ONE_TRUE); serializeAndDeserialize(stateEngine); FastBlobTypeDeserializationState<List<Integer>> typeDeserializationState = stateEngine.getTypeDeserializationState(listSerializer.getName()); List<Integer> outList = typeDeserializationState.get(0); Assert.assertEquals(4, outList.size()); Assert.assertEquals(1, outList.get(0).intValue()); Assert.assertEquals(3, outList.get(1).intValue()); Assert.assertEquals(null, outList.get(2)); Assert.assertEquals(4, outList.get(3).intValue()); } @Test public void includesLegitimatelyNullElementsButNotUndefinedElementsInSet() throws IOException { final SetSerializer<Integer> setSerializer = new SetSerializer<Integer>(new FakeIntSerializer()); FastBlobStateEngine stateEngine = new FastBlobStateEngine(new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { setSerializer }; } }); Set<Integer> inSet = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4)); Set<Integer> inSet2 = new HashSet<Integer>(Arrays.asList(1, 3, null, 4)); Set<Integer> inSet3 = new HashSet<Integer>(Arrays.asList(1, 2, 3, null, 4)); stateEngine.add(setSerializer.getName(), inSet, FastBlobImageUtils.ONE_TRUE); stateEngine.add(setSerializer.getName(), inSet2, FastBlobImageUtils.ONE_TRUE); stateEngine.add(setSerializer.getName(), inSet3, FastBlobImageUtils.ONE_TRUE); serializeAndDeserialize(stateEngine); FastBlobTypeDeserializationState<Set<Integer>> typeDeserializationState = stateEngine.getTypeDeserializationState(setSerializer.getName()); Set<Integer> outSet = typeDeserializationState.get(0); Assert.assertEquals(3, outSet.size()); Assert.assertTrue(outSet.contains(1)); Assert.assertTrue(outSet.contains(3)); Assert.assertTrue(outSet.contains(4)); Set<Integer> outSet2 = typeDeserializationState.get(1); Assert.assertEquals(4, outSet2.size()); Assert.assertTrue(outSet2.contains(1)); Assert.assertTrue(outSet2.contains(3)); Assert.assertTrue(outSet2.contains(null)); Assert.assertTrue(outSet2.contains(4)); Set<Integer> outSet3 = typeDeserializationState.get(2); Assert.assertEquals(4, outSet3.size()); Assert.assertTrue(outSet3.contains(1)); Assert.assertTrue(outSet3.contains(3)); Assert.assertTrue(outSet3.contains(null)); Assert.assertTrue(outSet3.contains(4)); } @Test public void doesNotIncludeEntriesWithUndefinedKeysOrValuesInMap() throws IOException { final MapSerializer<Integer, Integer> mapSerializer = new MapSerializer<Integer, Integer>(new FakeIntSerializer(), new FakeIntSerializer()); FastBlobStateEngine stateEngine = new FastBlobStateEngine(new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { mapSerializer }; } }); Map<Integer, Integer> inMap = new HashMap<Integer, Integer>(); inMap.put(0, 1); inMap.put(1, 2); inMap.put(2, 3); inMap.put(3, 4); stateEngine.add(mapSerializer.getName(), inMap, FastBlobImageUtils.ONE_TRUE); serializeAndDeserialize(stateEngine); FastBlobTypeDeserializationState<Map<Integer, Integer>> typeDeserializationState = stateEngine.getTypeDeserializationState(mapSerializer.getName()); Map<Integer, Integer> outMap = typeDeserializationState.get(0); Assert.assertEquals(2, outMap.size()); Assert.assertEquals(Integer.valueOf(1), outMap.get(0)); Assert.assertEquals(Integer.valueOf(4), outMap.get(3)); } private void serializeAndDeserialize(FastBlobStateEngine stateEngine) throws IOException { stateEngine.prepareForWrite(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FastBlobWriter writer = new FastBlobWriter(stateEngine, 0); writer.writeSnapshot(new DataOutputStream(baos)); FastBlobReader reader = new FastBlobReader(stateEngine); reader.readSnapshot(new ByteArrayInputStream(baos.toByteArray())); } /** * This Integer serializer is deliberately unable to deserialize the value "2". * */ private class FakeIntSerializer extends NFTypeSerializer<Integer> { public FakeIntSerializer() { super("FakeInt"); } @Override public void doSerialize(Integer value, NFSerializationRecord rec) { serializePrimitive(rec, "value", value); } @Override protected Integer doDeserialize(NFDeserializationRecord rec) { Integer value = deserializeInteger(rec, "value"); /// unable to deserialize "2" if(value != null && value == 2) return null; return value; } @Override protected FastBlobSchema createSchema() { return schema( field("value", FieldType.INT) ); } @Override public Collection<NFTypeSerializer<?>> requiredSubSerializers() { return serializers(); } } }
8,176
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/OrdinalRemapperTest.java
package com.netflix.zeno.fastblob; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord; import com.netflix.zeno.fastblob.record.FastBlobSerializationRecord; import com.netflix.zeno.fastblob.record.VarInt; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType; import com.netflix.zeno.fastblob.record.schema.FieldDefinition; import com.netflix.zeno.fastblob.record.schema.MapFieldDefinition; import com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition; import com.netflix.zeno.fastblob.state.OrdinalRemapper; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.serializer.common.ListSerializer; import com.netflix.zeno.serializer.common.MapSerializer; import com.netflix.zeno.serializer.common.SetSerializer; import com.netflix.zeno.testpojos.TypeA; import com.netflix.zeno.testpojos.TypeASerializer; import com.netflix.zeno.testpojos.TypeD; import com.netflix.zeno.testpojos.TypeDSerializer; /* * This test validates only the ordinal remapping functionality. * * Essentially, we set up a fake mapping for TypeA POJO instances for the LazyBlobSerializer: * * 0->4 (TypeA(0, 0) -> TypeA(4, 4)) * 1->3 (TypeA(1, 1) -> TypeA(3, 3)) * 2->2 (TypeA(2, 2) -> TypeA(2, 2)) * 3->1 (TypeA(3, 3) -> TypeA(1, 1)) * 4->0 (TypeA(4, 4) -> TypeA(0, 0)) * * Then we serialize each of the field types which requires remapping. When we remap the ordinals, then * deserialize the transformed data, we expect that the resultant objects will be transformed accordingly, e.g.: * * List (TypeA(0, 0)) becomes List(TypeA(4, 4)) * Set (TypeA(3, 3), TypeA(0, 0)) -> Set(TypeA(1, 1), TypeA(4, 4)) * * In actual use, the context for this mapping would be based on reassignment * in the lazy blob, instead of the arbitrary values assigned here for testing. * */ public class OrdinalRemapperTest { private static final MapSerializer<TypeA, TypeA> MAP_SERIALIZER = new MapSerializer<TypeA, TypeA>(new TypeASerializer(), new TypeASerializer()); private static final SetSerializer<TypeA> SET_SERIALIZER = new SetSerializer<TypeA>(new TypeASerializer()); private static final ListSerializer<TypeA> LIST_SERIALIZER = new ListSerializer<TypeA>(new TypeASerializer()); private FastBlobStateEngine stateEngine; private OrdinalRemapper ordinalRemapper; @Before public void setUp() { stateEngine = new FastBlobStateEngine(new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?> [] { new MapSerializer<TypeA, TypeA>(new TypeASerializer(), new TypeASerializer()), new SetSerializer<TypeA>(new TypeASerializer()), new ListSerializer<TypeA>(new TypeASerializer()), new TypeDSerializer() }; } }); stateEngine.add("TypeA", new TypeA(0, 0)); // ordinal 0 stateEngine.add("TypeA", new TypeA(1, 1)); // ordinal 1 stateEngine.add("TypeA", new TypeA(2, 2)); // ordinal 2 stateEngine.add("TypeA", new TypeA(3, 3)); // ordinal 3 stateEngine.add("TypeA", new TypeA(4, 4)); // ordinal 4 stateEngine.add("TypeA", new TypeA(5, 5)); // ordinal 5 stateEngine.add("TypeA", new TypeA(6, 6)); // ordinal 6 /// fill deserialization state from serialization state stateEngine.getTypeSerializationState("TypeA").fillDeserializationState(stateEngine.getTypeDeserializationState("TypeA")); OrdinalMapping ordinalMapping = new OrdinalMapping(); StateOrdinalMapping stateOrdinalMapping = ordinalMapping.createStateOrdinalMapping("TypeA", 6); stateOrdinalMapping.setMappedOrdinal(0, 4); stateOrdinalMapping.setMappedOrdinal(1, 3); stateOrdinalMapping.setMappedOrdinal(2, 2); stateOrdinalMapping.setMappedOrdinal(3, 1); stateOrdinalMapping.setMappedOrdinal(4, 0); stateOrdinalMapping.setMappedOrdinal(5, 6); stateOrdinalMapping.setMappedOrdinal(6, 5); ordinalRemapper = new OrdinalRemapper(ordinalMapping); } @Test public void remapsListOrdinals() { NFTypeSerializer<List<TypeA>> listSerializer = stateEngine.getSerializer(LIST_SERIALIZER.getName()); FastBlobSchema listSchema = listSerializer.getFastBlobSchema(); FastBlobSerializationRecord rec = new FastBlobSerializationRecord(listSchema); rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE); List<TypeA> list = new ArrayList<TypeA>(); list.add(new TypeA(3, 3)); list.add(new TypeA(0, 0)); list.add(null); list.add(new TypeA(2, 2)); list.add(new TypeA(6, 6)); list.add(new TypeA(5, 5)); listSerializer.serialize(list, rec); FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(listSchema, rec); FastBlobDeserializationRecord remappedRec = remapOrdinals(listSchema, deserializationRec); List<TypeA> typeAs = listSerializer.deserialize(remappedRec); Assert.assertEquals(6, typeAs.size()); Assert.assertEquals(new TypeA(1, 1), typeAs.get(0)); Assert.assertEquals(new TypeA(4, 4), typeAs.get(1)); Assert.assertNull(typeAs.get(2)); Assert.assertEquals(new TypeA(2, 2), typeAs.get(3)); } @Test public void remapsListFieldOrdinals() { FastBlobSchema schema = new FastBlobSchema("Test", 2); schema.addField("intField", new FieldDefinition(FieldType.INT)); schema.addField("listField", new TypedFieldDefinition(FieldType.LIST, "ElementType")); Random rand = new Random(); for(int i=0;i<1000;i++) { int numElements = rand.nextInt(1000); ByteDataBuffer buf = new ByteDataBuffer(); OrdinalMapping ordinalMapping = new OrdinalMapping(); StateOrdinalMapping stateOrdinalMap = ordinalMapping.createStateOrdinalMapping("ElementType", numElements); for(int j=0;j<numElements;j++) { stateOrdinalMap.setMappedOrdinal(j, rand.nextInt(10000)); VarInt.writeVInt(buf, j); } ByteDataBuffer toDataBuffer = copyToBufferAndRemapOrdinals(schema, buf, ordinalMapping); Assert.assertEquals(100, VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 0)); int listDataSize = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 1); long position = VarInt.sizeOfVInt(listDataSize) + 1; long endPosition = position + listDataSize; int counter = 0; while(position < endPosition) { int encoded = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position); position += VarInt.sizeOfVInt(encoded); Assert.assertEquals(encoded, stateOrdinalMap.getMappedOrdinal(counter)); counter++; } } } @Test public void remapsMapFieldOrdinals() { FastBlobSchema schema = new FastBlobSchema("Test", 2); schema.addField("intField", new FieldDefinition(FieldType.INT)); schema.addField("mapField", new MapFieldDefinition("ElementType", "ElementType")); Random rand = new Random(); for(int i=0;i<1000;i++) { int numElements = rand.nextInt(1000); ByteDataBuffer buf = new ByteDataBuffer(); BitSet usedMappings = new BitSet(); Map<Integer, Integer> expectedMap = new HashMap<Integer, Integer>(); OrdinalMapping ordinalMapping = new OrdinalMapping(); StateOrdinalMapping stateOrdinalMap = ordinalMapping.createStateOrdinalMapping("ElementType", numElements); for(int j=0;j<numElements;j++) { int mapping = getRandomMapping(rand, usedMappings); stateOrdinalMap.setMappedOrdinal(j, mapping); VarInt.writeVInt(buf, j); VarInt.writeVInt(buf, j == 0 ? 0 : 1); expectedMap.put(mapping, mapping); } ByteDataBuffer toDataBuffer = copyToBufferAndRemapOrdinals(schema, buf, ordinalMapping); Assert.assertEquals(100, VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 0)); Map<Integer, Integer> actualMap = new HashMap<Integer, Integer>(); int listDataSize = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 1); long position = VarInt.sizeOfVInt(listDataSize) + 1; long endPosition = position + listDataSize; int prevValue = 0; while(position < endPosition) { int key = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position); position += VarInt.sizeOfVInt(key); int delta = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position); int value = prevValue + delta; prevValue = value; position += VarInt.sizeOfVInt(delta); actualMap.put(key, value); } Assert.assertEquals(expectedMap, actualMap); } } @Test public void remapsSetFieldOrdinals() { FastBlobSchema schema = new FastBlobSchema("Test", 2); schema.addField("intField", new FieldDefinition(FieldType.INT)); schema.addField("setField", new TypedFieldDefinition(FieldType.SET, "ElementType")); Random rand = new Random(); for(int i=0;i<1000;i++) { int numElements = rand.nextInt(1000); ByteDataBuffer buf = new ByteDataBuffer(); Set<Integer> expectedSet = new HashSet<Integer>(); BitSet usedMappings = new BitSet(); OrdinalMapping ordinalMapping = new OrdinalMapping(); StateOrdinalMapping stateOrdinalMap = ordinalMapping.createStateOrdinalMapping("ElementType", numElements); for(int j=0;j<numElements;j++) { int mapping = getRandomMapping(rand, usedMappings); stateOrdinalMap.setMappedOrdinal(j, mapping); VarInt.writeVInt(buf, j == 0 ? 0 : 1); expectedSet.add(mapping); } ByteDataBuffer toDataBuffer = copyToBufferAndRemapOrdinals(schema, buf, ordinalMapping); Assert.assertEquals(100, VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 0)); int listDataSize = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 1); long position = VarInt.sizeOfVInt(listDataSize) + 1; long endPosition = position + listDataSize; Set<Integer> actualSet = new HashSet<Integer>(); int prevOrdinal = 0; while(position < endPosition) { int deltaOrdinal = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position); position += VarInt.sizeOfVInt(deltaOrdinal); int currentOrdinal = prevOrdinal + deltaOrdinal; prevOrdinal = currentOrdinal; actualSet.add(currentOrdinal); } Assert.assertEquals(expectedSet, actualSet); } } private ByteDataBuffer copyToBufferAndRemapOrdinals(FastBlobSchema schema, ByteDataBuffer buf, OrdinalMapping ordinalMapping) { ByteDataBuffer fromDataBuffer = new ByteDataBuffer(); VarInt.writeVInt(fromDataBuffer, 100); VarInt.writeVInt(fromDataBuffer, (int)buf.length()); fromDataBuffer.copyFrom(buf); FastBlobDeserializationRecord rec = new FastBlobDeserializationRecord(schema, fromDataBuffer.getUnderlyingArray()); rec.position(0); ByteDataBuffer toDataBuffer = new ByteDataBuffer(); new OrdinalRemapper(ordinalMapping).remapOrdinals(rec, toDataBuffer); return toDataBuffer; } private int getRandomMapping(Random rand, BitSet usedMappings) { int mapping = rand.nextInt(10000); while(usedMappings.get(mapping)) mapping = rand.nextInt(10000); usedMappings.set(mapping); return mapping; } @Test public void remapsSetOrdinals() { NFTypeSerializer<Set<TypeA>> setSerializer = stateEngine.getSerializer(SET_SERIALIZER.getName()); FastBlobSchema setSchema = setSerializer.getFastBlobSchema(); FastBlobSerializationRecord rec = new FastBlobSerializationRecord(setSchema); rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE); Set<TypeA> set = new HashSet<TypeA>(); set.add(new TypeA(1, 1)); set.add(new TypeA(4, 4)); set.add(null); setSerializer.serialize(set, rec); FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(setSchema, rec); FastBlobDeserializationRecord remappedRec = remapOrdinals(setSchema, deserializationRec); Set<TypeA> typeAs = setSerializer.deserialize(remappedRec); Assert.assertEquals(3, typeAs.size()); Assert.assertTrue(typeAs.contains(new TypeA(3, 3))); Assert.assertTrue(typeAs.contains(new TypeA(0, 0))); Assert.assertTrue(typeAs.contains(null)); } @Test public void remapsMapOrdinals() { NFTypeSerializer<Map<TypeA, TypeA>> mapSerializer = stateEngine.getSerializer(MAP_SERIALIZER.getName()); FastBlobSchema mapSchema = mapSerializer.getFastBlobSchema(); FastBlobSerializationRecord rec = new FastBlobSerializationRecord(mapSchema); rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE); Map<TypeA, TypeA> map = new HashMap<TypeA, TypeA>(); map.put(new TypeA(1, 1), new TypeA(4, 4)); map.put(new TypeA(3, 3), new TypeA(1, 1)); map.put(null, new TypeA(1, 1)); map.put(new TypeA(4, 4), null); mapSerializer.serialize(map, rec); FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(mapSchema, rec); FastBlobDeserializationRecord remappedRec = remapOrdinals(mapSchema, deserializationRec); Map<TypeA, TypeA> typeAs = mapSerializer.deserialize(remappedRec); Assert.assertEquals(4, typeAs.size()); Assert.assertEquals(new TypeA(0, 0), typeAs.get(new TypeA(3, 3))); Assert.assertEquals(new TypeA(3, 3), typeAs.get(new TypeA(1, 1))); Assert.assertEquals(new TypeA(3, 3), typeAs.get(null)); Assert.assertEquals(null, typeAs.get(new TypeA(0, 0))); } @Test public void remapsObjectOrdinals() { NFTypeSerializer<TypeD> serializer = stateEngine.getSerializer("TypeD"); FastBlobSchema typeDSchema = serializer.getFastBlobSchema(); FastBlobSerializationRecord rec = new FastBlobSerializationRecord(typeDSchema); rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE); TypeD typeD = new TypeD(100, new TypeA(3, 3)); serializer.serialize(typeD, rec); FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(typeDSchema, rec); FastBlobDeserializationRecord remappedRec = remapOrdinals(typeDSchema, deserializationRec); TypeD deserializedTypeD = serializer.deserialize(remappedRec); Assert.assertEquals(Integer.valueOf(100), deserializedTypeD.getVal()); Assert.assertEquals(new TypeA(1, 1), deserializedTypeD.getTypeA()); } private FastBlobDeserializationRecord createDeserializationRecord(FastBlobSchema schema, FastBlobSerializationRecord rec) { ByteDataBuffer originalRecord = new ByteDataBuffer(); rec.writeDataTo(originalRecord); FastBlobDeserializationRecord deserializationRec = new FastBlobDeserializationRecord(schema, originalRecord.getUnderlyingArray()); deserializationRec.position(0); return deserializationRec; } private FastBlobDeserializationRecord remapOrdinals(FastBlobSchema schema, FastBlobDeserializationRecord deserializationRec) { ByteDataBuffer remappedRecordSpace = new ByteDataBuffer(); ordinalRemapper.remapOrdinals(deserializationRec, remappedRecordSpace); FastBlobDeserializationRecord remappedRec = new FastBlobDeserializationRecord(schema, remappedRecordSpace.getUnderlyingArray()); remappedRec.position(0); return remappedRec; } }
8,177
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/NFTypeSerializerTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType; import com.netflix.zeno.fastblob.record.FastBlobSerializationRecord; import com.netflix.zeno.serializer.NFDeserializationRecord; import com.netflix.zeno.serializer.NFSerializationRecord; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import java.util.Collection; import java.util.Collections; import org.junit.Assert; import org.junit.Test; public class NFTypeSerializerTest { SerializerFactory serializerFactory = new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[]{ new TestSerializer(), new TestSerializerBytes() }; } }; FastBlobStateEngine framework = new FastBlobStateEngine(serializerFactory); @Test public void booleanUsesDefaultWhenActualValueIsNull() { TestSerializer testSerializer = new TestSerializer(); testSerializer.setSerializationFramework(new FastBlobStateEngine(serializerFactory)); FastBlobSerializationRecord rec = new FastBlobSerializationRecord(testSerializer.getFastBlobSchema()); testSerializer.serialize(null, rec); ByteDataBuffer buf = new ByteDataBuffer(); rec.writeDataTo(buf); FastBlobDeserializationRecord deserializeRec = new FastBlobDeserializationRecord(testSerializer.getFastBlobSchema(), buf.getUnderlyingArray()); deserializeRec.position(0); Boolean deserialized = testSerializer.deserialize(deserializeRec); Assert.assertEquals(Boolean.TRUE, deserialized); } public class TestSerializer extends NFTypeSerializer<Boolean> { private static final String NAME = "TEST_BOOLEAN"; public TestSerializer() { super(NAME); } @Override public void doSerialize(Boolean value, NFSerializationRecord rec) { serializePrimitive(rec, "bool", value); } @Override protected Boolean doDeserialize(NFDeserializationRecord rec) { return deserializeBoolean(rec, "bool", true); } @Override protected FastBlobSchema createSchema() { return schema( field("bool", FieldType.BOOLEAN) ); } @Override public Collection<NFTypeSerializer<?>> requiredSubSerializers() { return Collections.emptySet(); } } byte[] bytes = new byte[]{1,55}; byte[] bytes2 = new byte[]{2,56}; @Test public void testBytes() throws Exception { NFTypeSerializer<Object[]> testSerializer = framework.getSerializer(TestSerializerBytes.NAME); FastBlobSerializationRecord rec = new FastBlobSerializationRecord(testSerializer.getFastBlobSchema()); testSerializer.serialize(new Object[]{bytes, bytes2}, rec); ByteDataBuffer buf = new ByteDataBuffer(); rec.writeDataTo(buf); FastBlobDeserializationRecord deserializeRec = new FastBlobDeserializationRecord(testSerializer.getFastBlobSchema(), buf.getUnderlyingArray()); deserializeRec.position(0); Object[] deserialized = testSerializer.deserialize(deserializeRec); Assert.assertArrayEquals(bytes, (byte[])deserialized[0]); Assert.assertArrayEquals(bytes2, (byte[])deserialized[1]); } public class TestSerializerBytes extends NFTypeSerializer<Object[]> { public static final String NAME = "TEST_BYTES"; public TestSerializerBytes() { super(NAME); } @Override public void doSerialize(Object[] objs, NFSerializationRecord rec) { serializeBytes(rec, "bytes", (byte[])objs[0]); serializeBytes(rec, "bytes2", (byte[])objs[1]); } @Override protected Object[] doDeserialize(NFDeserializationRecord rec) { return new Object[]{ deserializeBytes(rec, "bytes"), deserializeBytes(rec, "bytes2") }; } @Override protected FastBlobSchema createSchema() { return schema( field("bytes", FieldType.BYTES), field("bytes2", FieldType.BYTES) ); } @Override public Collection<NFTypeSerializer<?>> requiredSubSerializers() { return Collections.emptySet(); } } }
8,178
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/SerializerDeltaTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import com.netflix.zeno.fastblob.FastBlobStateEngine; import com.netflix.zeno.testpojos.TypeA; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SerializerDeltaTest extends BlobSerializationGenericFrameworkAbstract { @Override @Before public void setUp() throws Exception { super.setUp(); } @Test public void serializesAndDeserializesDeltas() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeA", new TypeA(1, 2)); cache("TypeA", new TypeA(3, 4)); serializeAndDeserializeSnapshot(); cache("TypeA", new TypeA(1, 2)); cache("TypeA", new TypeA(5, 6)); serializeAndDeserializeDelta(); final List<TypeA>allAs = getAll("TypeA"); Assert.assertEquals(2, allAs.size()); Assert.assertTrue(allAs.contains(new TypeA(1, 2))); Assert.assertTrue(allAs.contains(new TypeA(5, 6))); Assert.assertFalse(allAs.contains(new TypeA(3, 4))); } }
8,179
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/FastBlobEngineTest.java
package com.netflix.zeno.fastblob; import com.netflix.zeno.fastblob.io.FastBlobReader; import com.netflix.zeno.fastblob.io.FastBlobWriter; import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.serializer.common.IntegerSerializer; import com.netflix.zeno.serializer.common.StringSerializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Arrays; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FastBlobEngineTest { SerializerFactory factory = new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { new IntegerSerializer(), new StringSerializer() }; } }; FastBlobStateEngine srcEngine1; FastBlobStateEngine srcEngine2; FastBlobStateEngine destEngine; @Before public void setUp() { srcEngine1 = new FastBlobStateEngine(factory, 2); srcEngine2 = new FastBlobStateEngine(factory, 2); destEngine = new FastBlobStateEngine(factory, 2); } @Test public void copiesDataFromOneStateEngineToAnother() throws Exception { /// initialize data in "from" state addData(srcEngine1, 1, true, true); addData(srcEngine1, 2, true, false); addData(srcEngine1, 3, false, true); copyEngine(srcEngine1, destEngine); /// assert data was copied assertData(destEngine, 1, true, true); assertData(destEngine, 2, true, false); assertData(destEngine, 3, false, true); } @Test public void copiesDataFromOneStateEngineToAnotherWithIgnoreList() throws Exception { /// initialize data in "from" state addData(srcEngine1, 1, true, true); addStringData(srcEngine1, "Two", true, false); addData(srcEngine1, 3, false, true); srcEngine1.copySerializationStatesTo(destEngine, Arrays.asList("Strings")); /// assert data was copied assertData(destEngine, 1, true, true); assertNoStringData(destEngine, "Two", true, true); assertData(destEngine, 3, false, true); } @Test public void copiesPartialDataFromOneStateEngineToAnotherInMultiplePhases() throws Exception { /// initialize data in "from" state addData(srcEngine1, 1, true, true); addStringData(srcEngine1, "Two", true, false); addData(srcEngine1, 3, false, true); OrdinalMapping mapping = srcEngine1.copySerializationStatesTo(destEngine, Arrays.asList("Strings")); srcEngine1.copySpecificSerializationStatesTo(destEngine, Arrays.asList("Strings"), mapping); /// assert data was copied assertData(destEngine, 1, true, true); assertStringData(destEngine, "Two", true, false); assertData(destEngine, 3, false, true); } @Test public void copiesDataFromOneStateEngineToAnotherWithIgnoreListContainingUnknownSerializer() throws Exception { /// initialize data in "from" state addData(srcEngine1, 1, true, true); addStringData(srcEngine1, "Two", true, false); addData(srcEngine1, 3, false, true); srcEngine1.copySerializationStatesTo(destEngine, Arrays.asList("Strings", "Foo")); /// assert data was copied assertData(destEngine, 1, true, true); assertNoStringData(destEngine, "Two", true, true); assertData(destEngine, 3, false, true); } @Test public void copiesDataFromMultipleStateEnginesToAnother() throws Exception { /// initialize data in "from" state addData(srcEngine1, 1, false, true); // Repetitive addition with different image flags addData(srcEngine1, 1, true, true); addData(srcEngine1, 2, true, false); addData(srcEngine1, 3, false, true); copyEngine(srcEngine1, destEngine); addData(srcEngine2, 1, true, true); addData(srcEngine2, 4, true, false); addData(srcEngine2, 5, false, true); copyEngine(srcEngine2, destEngine); /// assert data was copied assertData(destEngine, 1, true, true); assertData(destEngine, 2, true, false); assertData(destEngine, 3, false, true); assertData(destEngine, 4, true, false); assertData(destEngine, 5, false, true); } @Test public void serializeAndDeserialize() throws Exception{ addData(srcEngine1, 1, true, true); addData(srcEngine1, 2, true, false); addData(srcEngine1, 3, false, true); addData(srcEngine1, 1, true, true); addData(srcEngine1, 2, true, false); addData(srcEngine1, 4, false, true); final File f = File.createTempFile("pre", "suf"); DataOutputStream dos = new DataOutputStream(new FileOutputStream(f)); DataInputStream dis = new DataInputStream(new FileInputStream(f)); try { srcEngine1.setLatestVersion("foo"); srcEngine1.serializeTo(dos); destEngine.deserializeFrom(dis); }finally { dos.close(); dis.close(); f.delete(); } /// assert data was deserialized assertData(destEngine, 1, true, true); assertData(destEngine, 2, true, false); assertData(destEngine, 3, false, true); assertData(destEngine, 4, false, true); } private void copyEngine(FastBlobStateEngine srcStateEngine, FastBlobStateEngine destStateEngine) { srcStateEngine.copySerializationStatesTo(destStateEngine, Collections.<String> emptyList()); } private void addData(FastBlobStateEngine stateEngine, Integer data, boolean... images) { stateEngine.add("Integer", data, FastBlobImageUtils.toLong(images)); } private void addStringData(FastBlobStateEngine stateEngine, String data, boolean... images) { stateEngine.add("Strings", data, FastBlobImageUtils.toLong(images)); } private void assertData(FastBlobStateEngine stateEngine, Integer data, boolean... images) throws Exception { stateEngine.prepareForWrite(); for(int i=0;i<images.length;i++) { if(images[i]) { FastBlobStateEngine testStateEngine = new FastBlobStateEngine(factory); fillDeserializationWithImage(stateEngine, testStateEngine, i); Assert.assertTrue(containsData(testStateEngine, data, "Integer")); } } } private void assertNoStringData(FastBlobStateEngine stateEngine, String data, boolean... images) throws Exception { stateEngine.prepareForWrite(); for(int i=0;i<images.length;i++) { if(images[i]) { FastBlobStateEngine testStateEngine = new FastBlobStateEngine(factory); fillDeserializationWithImage(stateEngine, testStateEngine, i); Assert.assertFalse(containsData(testStateEngine, data, "Strings")); } } } private void assertStringData(FastBlobStateEngine stateEngine, String data, boolean... images) throws Exception { stateEngine.prepareForWrite(); for(int i=0;i<images.length;i++) { if(images[i]) { FastBlobStateEngine testStateEngine = new FastBlobStateEngine(factory); fillDeserializationWithImage(stateEngine, testStateEngine, i); Assert.assertTrue(containsData(testStateEngine, data, "Strings")); } } } private <T> boolean containsData(FastBlobStateEngine stateEngine, T value, String serializerName) { FastBlobTypeDeserializationState<T> typeState = stateEngine.getTypeDeserializationState(serializerName); for(T i : typeState) { if(i.equals(value)) return true; } return false; } private void fillDeserializationWithImage(FastBlobStateEngine serverStateEngine, FastBlobStateEngine clientStateEngine, int imageIndex) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); FastBlobWriter writer = new FastBlobWriter(serverStateEngine, imageIndex); writer.writeSnapshot(baos); FastBlobReader reader = new FastBlobReader(clientStateEngine); reader.readSnapshot(new ByteArrayInputStream(baos.toByteArray())); } }
8,180
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/CompatibilitySerializerTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType; import com.netflix.zeno.fastblob.record.FastBlobSerializationRecord; import com.netflix.zeno.serializer.NFDeserializationRecord; import com.netflix.zeno.serializer.NFSerializationRecord; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import java.io.IOException; import java.util.Collection; import java.util.Collections; import org.junit.Assert; import org.junit.Test; public class CompatibilitySerializerTest { SerializerFactory serializerFactory = new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[]{ new TestSerializer1(), new TestSerializer2() }; } }; FastBlobStateEngine framework = new FastBlobStateEngine(serializerFactory); NFTypeSerializer<String[]> testSerializer1 = framework.getSerializer(TestSerializer1.NAME); NFTypeSerializer<String[]> testSerializer2 = framework.getSerializer(TestSerializer2.NAME); String text1 = "String1"; String text2 = "String2"; @Test public void testRemove() throws Exception { FastBlobSerializationRecord rec = new FastBlobSerializationRecord(testSerializer2.getFastBlobSchema()); testSerializer2.serialize(new String[]{text1, text2}, rec); FastBlobDeserializationRecord result = serializeDeserialize(testSerializer2, rec); String[] deserialized = testSerializer1.deserialize(result); Assert.assertEquals(text1, deserialized[0]); } @Test public void testAdd() throws Exception { FastBlobSerializationRecord rec = new FastBlobSerializationRecord(testSerializer1.getFastBlobSchema()); testSerializer1.serialize(new String[]{text1}, rec); FastBlobDeserializationRecord result = serializeDeserialize(testSerializer1, rec); String[] deserialized = testSerializer2.deserialize(result); Assert.assertEquals(text1, deserialized[0]); Assert.assertEquals(null, deserialized[1]); } private FastBlobDeserializationRecord serializeDeserialize(NFTypeSerializer<String[]> testSerializer, FastBlobSerializationRecord rec) throws IOException { ByteDataBuffer buf = new ByteDataBuffer(); rec.writeDataTo(buf); FastBlobDeserializationRecord deserializeRec = new FastBlobDeserializationRecord(testSerializer.getFastBlobSchema(), buf.getUnderlyingArray()); deserializeRec.position(0); return deserializeRec; } public class TestSerializer1 extends NFTypeSerializer<String[]> { public static final String NAME = "TEST1"; public TestSerializer1() { super(NAME); } @Override public void doSerialize(String[] objs, NFSerializationRecord rec) { serializePrimitive(rec, "string1", (String)objs[0]); } @Override protected String[] doDeserialize(NFDeserializationRecord rec) { return new String[]{ deserializePrimitiveString(rec, "string1") }; } @Override protected FastBlobSchema createSchema() { return schema( field("string1", FieldType.STRING) ); } @Override public Collection<NFTypeSerializer<?>> requiredSubSerializers() { return Collections.emptySet(); } } public class TestSerializer2 extends NFTypeSerializer<String[]> { public static final String NAME = "TEST2"; public TestSerializer2() { super(NAME); } @Override public void doSerialize(String[] objs, NFSerializationRecord rec) { serializePrimitive(rec, "string1", (String)objs[0]); serializePrimitive(rec, "string2", (String)objs[1]); } @Override protected String[] doDeserialize(NFDeserializationRecord rec) { return new String[]{ deserializePrimitiveString(rec, "string1"), deserializePrimitiveString(rec, "string2") }; } @Override protected FastBlobSchema createSchema() { return schema( field("string1", FieldType.STRING), field("string2", FieldType.STRING) ); } @Override public Collection<NFTypeSerializer<?>> requiredSubSerializers() { return Collections.emptySet(); } } }
8,181
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/BlobSerializationGenericFrameworkAbstract.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.testpojos.TypeASerializer; import com.netflix.zeno.testpojos.TypeBSerializer; import com.netflix.zeno.testpojos.TypeCSerializer; import com.netflix.zeno.testpojos.TypeDSerializer; import com.netflix.zeno.testpojos.TypeESerializer; public abstract class BlobSerializationGenericFrameworkAbstract extends BlobSerializationAbstract { protected SerializerFactory serializersFactory = new SerializerFactory(){ @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { new TypeASerializer(), new TypeBSerializer(), new TypeCSerializer(), new TypeDSerializer(), new TypeESerializer() }; } }; protected TypeASerializer typeASerializer = new TypeASerializer(); protected TypeBSerializer TypeBSerializer = new TypeBSerializer(); protected TypeCSerializer typeCSerializer = new TypeCSerializer(); protected TypeDSerializer TypeDSerializer = new TypeDSerializer(); protected TypeESerializer TypeESerializer = new TypeESerializer(); @Override public void setUp() throws Exception { super.setUp(); } }
8,182
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/BlobSerializationAbstract.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import com.netflix.zeno.fastblob.io.FastBlobReader; import com.netflix.zeno.fastblob.io.FastBlobWriter; import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public abstract class BlobSerializationAbstract { protected FastBlobStateEngine serializationState; protected ByteArrayOutputStream baos; public void setUp() throws Exception { this.baos = new ByteArrayOutputStream(); } protected void serializeAndDeserializeDelta() throws IOException, Exception { serializationState.prepareForWrite(); new FastBlobWriter(serializationState, 0).writeDelta(new DataOutputStream(baos)); serializationState.prepareForNextCycle(); new FastBlobReader(serializationState).readDelta(new ByteArrayInputStream(baos.toByteArray())); baos.reset(); } protected void serializeAndDeserializeSnapshot() throws Exception { final byte[] data = serializeSnapshot(); deserializeSnapshot(data); } protected void deserializeSnapshot(final byte[] data) throws IOException { final InputStream is = new ByteArrayInputStream(data); new FastBlobReader(serializationState).readSnapshot(is); } protected byte[] serializeSnapshot() throws IOException { serializationState.prepareForWrite(); new FastBlobWriter(serializationState, 0).writeSnapshot(new DataOutputStream(baos)); serializationState.prepareForNextCycle(); baos.close(); final byte data[] = baos.toByteArray(); baos.reset(); return data; } protected void cache(final String cacheName, Object obj) { serializationState.add(cacheName, obj, FastBlobImageUtils.ONE_TRUE); } protected <T> List<T> getAll(final String cacheName) { List<T> list = new ArrayList<T>(); FastBlobTypeDeserializationState<T> state = serializationState.getTypeDeserializationState(cacheName); for(T t : state) list.add(t); return list; } }
8,183
0
Create_ds/zeno/src/test/java/com/netflix/zeno
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/SerializerSnapshotTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.netflix.zeno.testpojos.TypeA; import com.netflix.zeno.testpojos.TypeB; import com.netflix.zeno.testpojos.TypeC; import com.netflix.zeno.testpojos.TypeCSerializer; import com.netflix.zeno.testpojos.TypeD; public class SerializerSnapshotTest extends BlobSerializationGenericFrameworkAbstract { @Override @Before public void setUp() throws Exception { super.setUp(); } @Test public void serializeObjects() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeA", new TypeA(23523452, 2)); cache("TypeB", new TypeB(3, "four")); serializeAndDeserializeSnapshot(); final List<TypeA> typeAList = getAll("TypeA"); final List<TypeB> typeBList = getAll("TypeB"); Assert.assertEquals(1, typeAList.size()); Assert.assertEquals(1, typeBList.size()); Assert.assertEquals(23523452, typeAList.get(0).getVal1()); Assert.assertEquals(2, typeAList.get(0).getVal2()); Assert.assertEquals(3, typeBList.get(0).getVal1()); Assert.assertEquals("four", typeBList.get(0).getVal2()); } @Test public void deserializeWithoutKnowingAboutSomeObjectTypes() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeA", new TypeA(23523452, 2)); cache("TypeB", new TypeB(3, "four")); final byte data[] = serializeSnapshot(); serializationState = new FastBlobStateEngine(serializersFactory); deserializeSnapshot(data); final List<TypeB> typeBList = getAll("TypeB"); Assert.assertEquals(1, typeBList.size()); Assert.assertEquals(3, typeBList.get(0).getVal1()); Assert.assertEquals("four", typeBList.get(0).getVal2()); } @Test public void serializeObjectsWithNullPrimitives() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeD", new TypeD(null, null)); serializeAndDeserializeSnapshot(); final TypeD deserialized = (TypeD) getAll("TypeD").get(0); Assert.assertNull(deserialized.getVal()); } @Test public void serializeObjectsWithNullReferences() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeC", new TypeC(null, null)); serializeAndDeserializeSnapshot(); final TypeC deserialized = (TypeC) getAll("TypeC").get(0); Assert.assertNull(deserialized.getTypeAMap()); Assert.assertNull(deserialized.getTypeBs()); } @Test public void serializeMultipleObjects() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeB", new TypeB(1, "two")); cache("TypeB", new TypeB(3, "four")); serializeAndDeserializeSnapshot(); Assert.assertEquals(2, getAll("TypeB").size()); } @Test public void deserializedObjectsShareReferences() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); final TypeA theTypeA = new TypeA(1, 2); cache("TypeA", theTypeA); cache("TypeD", new TypeD(1, theTypeA)); cache("TypeD", new TypeD(2, theTypeA)); serializeAndDeserializeSnapshot(); final List<TypeD> deserializedDs = getAll("TypeD"); Assert.assertEquals(1, getAll("TypeA").size()); Assert.assertEquals(2, deserializedDs.size()); Assert.assertSame(deserializedDs.get(0).getTypeA(), deserializedDs.get(1).getTypeA()); } @Test public void serializeNestedObjects() throws Exception { serializationState = new FastBlobStateEngine(serializersFactory); cache("TypeC", new TypeC( typeAMap(), Arrays.asList( new TypeB(3, "four"), new TypeB(5, "six") ) )); serializeAndDeserializeSnapshot(); final TypeC deserializedC = (TypeC) getAll("TypeC").get(0); Assert.assertEquals(2, deserializedC.getTypeAMap().size()); Assert.assertEquals(12, deserializedC.getTypeAMap().get("ED").getVal1()); Assert.assertEquals(34, deserializedC.getTypeAMap().get("ED").getVal2()); Assert.assertEquals(56, deserializedC.getTypeAMap().get("BR").getVal1()); Assert.assertEquals(78, deserializedC.getTypeAMap().get("BR").getVal2()); Assert.assertEquals(2, deserializedC.getTypeBs().size()); Assert.assertEquals(3, deserializedC.getTypeBs().get(0).getVal1()); Assert.assertEquals("four", deserializedC.getTypeBs().get(0).getVal2()); Assert.assertEquals(5, deserializedC.getTypeBs().get(1).getVal1()); Assert.assertEquals("six", deserializedC.getTypeBs().get(1).getVal2()); Assert.assertSame(deserializedC.getTypeAMap(), getAll(TypeCSerializer.MAP_SERIALIZER.getName()).get(0)); Assert.assertSame(deserializedC.getTypeBs(), getAll(TypeCSerializer.LIST_SERIALIZER.getName()).get(0)); Assert.assertTrue(getAll("TypeB").contains(deserializedC.getTypeBs().get(0))); Assert.assertTrue(getAll("TypeB").contains(deserializedC.getTypeBs().get(1))); } private Map<String, TypeA> typeAMap() { final Map<String, TypeA> map = new HashMap<String, TypeA>(); map.put("ED", new TypeA(12, 34)); map.put("BR", new TypeA(56, 78)); return map; } }
8,184
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/io/FastBlobWriterTest.java
package com.netflix.zeno.fastblob.io; import static org.junit.Assert.assertTrue; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.junit.Before; import org.junit.Test; import com.netflix.zeno.fastblob.FastBlobStateEngine; import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.serializer.common.IntegerSerializer; import com.netflix.zeno.serializer.common.StringSerializer; public class FastBlobWriterTest { private final SerializerFactory factory = new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { new IntegerSerializer(), new StringSerializer() }; } }; private FastBlobStateEngine srcEngine; private FastBlobStateEngine destEngine; private FastBlobWriter fastBlobWriter; private FastBlobReader fastBlobReader; @Before public void setUp() { srcEngine = new FastBlobStateEngine(factory, 2); destEngine = new FastBlobStateEngine(factory, 2); } @Test public void writeSnapshotFromStatesAndRead() throws Exception { addData(srcEngine, 1, true, true); addStringData(srcEngine, "Two", true, false); addData(srcEngine, 3, false, true); addStringData(srcEngine, "Four", false, false); addData(srcEngine, 5, false, true); srcEngine.fillDeserializationStatesFromSerializedData(); srcEngine.prepareForWrite(); fastBlobWriter = new FastBlobWriter(srcEngine); final File f = File.createTempFile("pre", "suf"); DataOutputStream dos = new DataOutputStream(new FileOutputStream(f)); fastBlobWriter.writeNonImageSpecificSnapshot(dos); dos.close(); fastBlobReader = new FastBlobReader(destEngine); DataInputStream dis = new DataInputStream(new FileInputStream(f)); fastBlobReader.readSnapshot(dis); dis.close(); assertTrue(containsData(destEngine, 1, "Integer")); assertTrue(containsData(destEngine, "Two", "Strings")); assertTrue(containsData(destEngine, 3, "Integer")); assertTrue(containsData(destEngine, "Four", "Strings")); assertTrue(containsData(destEngine, 5, "Integer")); } private void addData(FastBlobStateEngine stateEngine, Integer data, boolean... images) { stateEngine.add("Integer", data, images); } private void addStringData(FastBlobStateEngine stateEngine, String data, boolean... images) { stateEngine.add("Strings", data, images); } private <T> boolean containsData(FastBlobStateEngine stateEngine, T value, String serializerName) { FastBlobTypeDeserializationState<T> typeState = stateEngine.getTypeDeserializationState(serializerName); for(T obj : typeState) { if(obj.equals(value)) return true; } return false; } }
8,185
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/WeakObjectOrdinalMapTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import org.apache.commons.lang.math.RandomUtils; import org.junit.Assert; import org.junit.Test; public class WeakObjectOrdinalMapTest { private static class MyClass { int i = RandomUtils.nextInt(); } @Test public void map() throws Exception { WeakObjectOrdinalMap map = new WeakObjectOrdinalMap(8); // // { // List<MyClass> sample = new ArrayList<MyClass>(); // int number = 100000; // for (int i = 0; i < number; i++) { // MyClass i1 = new MyClass(); // map.put(i1, number + i, 2 * number + i); // sample.add(i1); // } // Assert.assertEquals(number, map.size()); // sample.clear(); // sample = null; // } // // Thread.sleep(5000); // System.gc(); // // Assert.assertEquals(0, map.size()); MyClass i1 = new MyClass(); MyClass i2 = new MyClass(); MyClass i3 = new MyClass(); map.put(i1, 1, 4); map.put(i2, 2, 5); map.put(i3, 3, 6); Assert.assertEquals(3, map.size()); map.clear(); Assert.assertEquals(0, map.size()); map.put(i1, 1, 4); map.put(i2, 2, 5); map.put(i3, 3, 6); WeakObjectOrdinalMap.Entry entry1 = map.getEntry(i1); Assert.assertEquals(1, entry1.getOrdinal()); Assert.assertEquals(4, entry1.getImageMembershipsFlags()); WeakObjectOrdinalMap.Entry entry2 = map.getEntry(i2); Assert.assertEquals(2, entry2.getOrdinal()); Assert.assertEquals(5, entry2.getImageMembershipsFlags()); WeakObjectOrdinalMap.Entry entry3 = map.getEntry(i3); Assert.assertEquals(3, entry3.getOrdinal()); Assert.assertEquals(6, entry3.getImageMembershipsFlags()); Assert.assertEquals(3, map.size()); i2 = null; i3 = null; doGC(); Assert.assertEquals(1, map.size()); entry1 = map.getEntry(i1); Assert.assertEquals(1, entry1.getOrdinal()); Assert.assertEquals(4, entry1.getImageMembershipsFlags()); i1 = null; doGC(); Assert.assertEquals(0, map.size()); } private void doGC() throws InterruptedException { System.gc(); Thread.sleep(1000); } }
8,186
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/FreeOrdinalTrackerTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.state.FreeOrdinalTracker; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class FreeOrdinalTrackerTest { @Test public void returnsIncreasingOrdinals() { FreeOrdinalTracker tracker = new FreeOrdinalTracker(); for(int i=0;i<100;i++) { Assert.assertEquals(i, tracker.getFreeOrdinal()); } } @Test public void returnsOrdinalsPreviouslyReturnedToPool() { FreeOrdinalTracker tracker = new FreeOrdinalTracker(); for(int i=0;i<100;i++) { tracker.getFreeOrdinal(); } tracker.returnOrdinalToPool(20); tracker.returnOrdinalToPool(30); tracker.returnOrdinalToPool(40); Assert.assertEquals(40, tracker.getFreeOrdinal()); Assert.assertEquals(30, tracker.getFreeOrdinal()); Assert.assertEquals(20, tracker.getFreeOrdinal()); Assert.assertEquals(100, tracker.getFreeOrdinal()); Assert.assertEquals(101, tracker.getFreeOrdinal()); } @Test public void serializesAndDeserializes() throws IOException { FreeOrdinalTracker tracker = new FreeOrdinalTracker(); for(int i=0;i<100;i++) { tracker.getFreeOrdinal(); } tracker.returnOrdinalToPool(20); tracker.returnOrdinalToPool(30); tracker.returnOrdinalToPool(40); ByteArrayOutputStream baos = new ByteArrayOutputStream(); tracker.serializeTo(baos); FreeOrdinalTracker deserializedTracker = FreeOrdinalTracker.deserializeFrom(new ByteArrayInputStream(baos.toByteArray())); Assert.assertEquals(40, deserializedTracker.getFreeOrdinal()); Assert.assertEquals(30, deserializedTracker.getFreeOrdinal()); Assert.assertEquals(20, deserializedTracker.getFreeOrdinal()); Assert.assertEquals(100, deserializedTracker.getFreeOrdinal()); Assert.assertEquals(101, deserializedTracker.getFreeOrdinal()); } }
8,187
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/SegmentedByteArrayTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.record.SegmentedByteArray; import org.junit.Assert; import org.junit.Test; public class SegmentedByteArrayTest { @Test public void noSuchThingAsOutOfBoundsExceptionWhenWriting() { SegmentedByteArray arr = new SegmentedByteArray(3); // each segment is size 8 for(int i=0;i<1000;i++) { arr.set(i, (byte)i); } for(int i=0;i<1000;i++) { Assert.assertEquals((byte)i, arr.get(i)); } } @Test public void copyToAnotherSegmentedByteArray() { SegmentedByteArray src = new SegmentedByteArray(3); for(int i=0;i<128;i++) { src.set(i, (byte)i); } SegmentedByteArray dest = new SegmentedByteArray(3); for(int i=0;i<(128-32);i++) { for(int j=0;j<(128-32);j++) { dest.copy(src, i, j, 32); for(int k=0;k<32;k++) { Assert.assertEquals((byte)src.get(i+k), (byte)dest.get(j+k)); } } } } @Test public void canReferenceLongSpace() { SegmentedByteArray arr = new SegmentedByteArray(25); arr.set(0x1FFFFFFFFL, (byte)100); Assert.assertEquals((byte)100, arr.get(0x1FFFFFFFFL)); } }
8,188
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/ByteArrayOrdinalMapTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import com.netflix.zeno.fastblob.record.VarInt; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; public class ByteArrayOrdinalMapTest { @Test public void compacts() { ByteArrayOrdinalMap map = new ByteArrayOrdinalMap(); ByteDataBuffer buf = new ByteDataBuffer(); /// add 1000 entries for(int i=0;i<1000;i++) { VarInt.writeVInt(buf, 10000 + i); map.getOrAssignOrdinal(buf); buf.reset(); } /// mark half of the entries used ThreadSafeBitSet bitSet = new ThreadSafeBitSet(10); for(int i=0;i<1000;i+=2) { bitSet.set(i); } /// compact away the unused entries map.compact(bitSet); /// ensure that the used entries are still available for(int i=0;i<1000;i+=2) { VarInt.writeVInt(buf, 10000 + i); Assert.assertEquals(i, map.getOrAssignOrdinal(buf)); buf.reset(); } /// track the ordinals which are assigned to new values Set<Integer> newlyAssignedOrdinals = new HashSet<Integer>(); for(int i=1;i<1000;i+=2) { VarInt.writeVInt(buf, 50230532 + i); int newOrdinal = map.getOrAssignOrdinal(buf); newlyAssignedOrdinals.add(newOrdinal); buf.reset(); } /// those ordinals should be the recycled ones after the compact. for(int i=1;i<1000;i+=2) { Assert.assertTrue(newlyAssignedOrdinals.contains(i)); } } @Test public void clientSideHeapSafeUsageTest() { ByteArrayOrdinalMap map = new ByteArrayOrdinalMap(); ByteDataBuffer buf = new ByteDataBuffer(); for(int i=0;i<1000;i++) { VarInt.writeVInt(buf, 10000 + i); map.put(buf, i + 50); buf.reset(); } for(int i=0;i<1000;i++) { VarInt.writeVInt(buf, 10000 + i); Assert.assertEquals(i + 50, map.get(buf)); buf.reset(); } for(int i=0;i<1000;i++) { VarInt.writeVInt(buf, 20000 + i); Assert.assertEquals(-1, map.get(buf)); buf.reset(); } map.clear(); Assert.assertEquals(0, map.getDataSize()); for(int i=0;i<5000;i++) { VarInt.writeVInt(buf, 20000 + i); Assert.assertEquals(-1, map.get(buf)); buf.reset(); } for(int i=0;i<5000;i++) { VarInt.writeVInt(buf, 20000 + i); map.put(buf, i + 50); buf.reset(); } } @Test public void testThreadSafety() throws IOException { int numThreads = 100; final int numUniqueValues = 1000000; final int numIterationsPerThread = 200000; ThreadPoolExecutor executor = new ThreadPoolExecutor(numThreads, numThreads, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); final ConcurrentHashMap<Integer, Integer> controlMap = new ConcurrentHashMap<Integer, Integer>(); final ByteArrayOrdinalMap map = new ByteArrayOrdinalMap(); for(int i=0;i<numThreads;i++) { executor.execute(new Runnable() { @Override public void run() { Random rand = new Random(); ByteDataBuffer buf = new ByteDataBuffer(); for(int i=0;i<numIterationsPerThread;i++) { int value = rand.nextInt(numUniqueValues); VarInt.writeVInt(buf, value); Integer ordinal = Integer.valueOf(map.getOrAssignOrdinal(buf)); Integer beatMe = controlMap.putIfAbsent(value, ordinal); if(beatMe != null) { Assert.assertEquals(ordinal, beatMe); } buf.reset(); } } }); } shutdown(executor); /// serialize then deserialize the map /*ByteArrayOutputStream os = new ByteArrayOutputStream(); map.serializeTo(os); ByteArrayOrdinalMap deserializedMap = ByteArrayOrdinalMap.deserializeFrom(new ByteArrayInputStream(os.toByteArray()));*/ ByteDataBuffer buf = new ByteDataBuffer(); for(Map.Entry<Integer, Integer> entry : controlMap.entrySet()) { Integer value = entry.getKey(); Integer expected = entry.getValue(); buf.reset(); VarInt.writeVLong(buf, value.longValue()); int actual = map.getOrAssignOrdinal(buf); Assert.assertEquals(actual, expected.intValue()); } } private void shutdown(ThreadPoolExecutor executor) { executor.shutdown(); while(!executor.isTerminated()) { try { executor.awaitTermination(1, TimeUnit.DAYS); } catch (final InterruptedException e) { } } } }
8,189
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/FastBlobStateEngineReserializationTest.java
package com.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.FastBlobStateEngine; import com.netflix.zeno.fastblob.io.FastBlobReader; import com.netflix.zeno.fastblob.io.FastBlobWriter; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.testpojos.TypeA; import com.netflix.zeno.testpojos.TypeASerializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class FastBlobStateEngineReserializationTest { @Test public void canReserializeDeserializedData() throws Exception { FastBlobStateEngine stateEngine = typeAStateEngine(); stateEngine.add("TypeA", new TypeA(1, 2)); stateEngine.add("TypeA", new TypeA(3, 4)); stateEngine.prepareForWrite(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FastBlobWriter writer = new FastBlobWriter(stateEngine); writer.writeSnapshot(baos); FastBlobStateEngine deserializeEngine = typeAStateEngine(); FastBlobReader reader = new FastBlobReader(deserializeEngine); reader.readSnapshot(new ByteArrayInputStream(baos.toByteArray())); deserializeEngine.fillSerializationStatesFromDeserializedData(); deserializeEngine.prepareForWrite(); ByteArrayOutputStream reserializedStream = new ByteArrayOutputStream(); FastBlobWriter rewriter = new FastBlobWriter(deserializeEngine); rewriter.writeSnapshot(reserializedStream); Assert.assertArrayEquals(baos.toByteArray(), reserializedStream.toByteArray()); System.out.println(Arrays.toString(baos.toByteArray())); System.out.println(Arrays.toString(reserializedStream.toByteArray())); } private FastBlobStateEngine typeAStateEngine() { return new FastBlobStateEngine(new SerializerFactory() { @Override public NFTypeSerializer<?>[] createSerializers() { // TODO Auto-generated method stub return new NFTypeSerializer<?>[] { new TypeASerializer() }; } }); } }
8,190
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/TypeDeserializationStateListenerTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.FastBlobStateEngine; import com.netflix.zeno.fastblob.io.FastBlobReader; import com.netflix.zeno.fastblob.io.FastBlobWriter; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.testpojos.TypeF; import com.netflix.zeno.testpojos.TypeFSerializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TypeDeserializationStateListenerTest { FastBlobStateEngine stateEngine; byte snapshot1[]; byte delta[]; byte snapshot2[]; byte brokenDeltaChainSnapshot2[]; @Before public void createStates() throws Exception { stateEngine = newStateEngine(); /// first state has 1 - 10 addFs(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); stateEngine.prepareForWrite(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FastBlobWriter writer = new FastBlobWriter(stateEngine); writer.writeSnapshot(baos); snapshot1 = baos.toByteArray(); baos.reset(); stateEngine.prepareForNextCycle(); /// second state removes 3, 7, 10 and adds 11, 12 addFs(1, 2, 4, 5, 6, 8, 9, 11, 12); stateEngine.prepareForWrite(); writer.writeDelta(baos); delta = baos.toByteArray(); baos.reset(); writer.writeSnapshot(baos); snapshot2 = baos.toByteArray(); baos.reset(); /// we also create a broken delta chain to cause ordinal reassignments. stateEngine = newStateEngine(); addFs(1, 2, 4, 5, 6, 8, 9, 11, 12); stateEngine.prepareForWrite(); writer = new FastBlobWriter(stateEngine); writer.writeSnapshot(baos); brokenDeltaChainSnapshot2 = baos.toByteArray(); } private FastBlobStateEngine newStateEngine() { return new FastBlobStateEngine(new SerializerFactory() { public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { new TypeFSerializer() }; } }); } private void addFs(int... values) { for(int value : values) stateEngine.add("TypeF", new TypeF(value)); } @Test public void testListenerSnapshot() throws IOException { TestTypeDeserializationStateListener listener = new TestTypeDeserializationStateListener(); stateEngine.setTypeDeserializationStateListener("TypeF", listener); FastBlobReader reader = new FastBlobReader(stateEngine); reader.readSnapshot(new ByteArrayInputStream(snapshot1)); Assert.assertEquals(0, listener.getRemovedValuesSize()); Assert.assertEquals(10, listener.getAddedValuesSize()); Assert.assertEquals(3, listener.getAddedValueOrdinal(4)); } @Test public void testListenerDelta() throws IOException { FastBlobReader reader = new FastBlobReader(stateEngine); reader.readSnapshot(new ByteArrayInputStream(snapshot1)); TestTypeDeserializationStateListener listener = new TestTypeDeserializationStateListener(); stateEngine.setTypeDeserializationStateListener("TypeF", listener); reader.readDelta(new ByteArrayInputStream(delta)); Assert.assertEquals(3, listener.getRemovedValuesSize()); Assert.assertEquals(2, listener.getRemovedValueOrdinal(3)); Assert.assertEquals(2, listener.getAddedValuesSize()); Assert.assertEquals(10, listener.getAddedValueOrdinal(11)); } @Test public void testListenerDoubleSnapshot() throws IOException { FastBlobReader reader = new FastBlobReader(stateEngine); reader.readSnapshot(new ByteArrayInputStream(snapshot1)); TestTypeDeserializationStateListener listener = new TestTypeDeserializationStateListener(); stateEngine.setTypeDeserializationStateListener("TypeF", listener); reader.readSnapshot(new ByteArrayInputStream(snapshot2)); Assert.assertEquals(3, listener.getRemovedValuesSize()); Assert.assertEquals(2, listener.getRemovedValueOrdinal(3)); Assert.assertEquals(2, listener.getAddedValuesSize()); Assert.assertEquals(10, listener.getAddedValueOrdinal(11)); Assert.assertEquals(7, listener.getReassignedValuesSize()); Assert.assertEquals(new OrdinalReassignment(3, 3), listener.getOrdinalReassignment(4)); } @Test public void testListenerDoubleSnapshotDiscontinuousState() throws IOException { FastBlobReader reader = new FastBlobReader(stateEngine); reader.readSnapshot(new ByteArrayInputStream(snapshot1)); TestTypeDeserializationStateListener listener = new TestTypeDeserializationStateListener(); stateEngine.setTypeDeserializationStateListener("TypeF", listener); reader.readSnapshot(new ByteArrayInputStream(brokenDeltaChainSnapshot2)); Assert.assertEquals(3, listener.getRemovedValuesSize()); Assert.assertEquals(2, listener.getRemovedValueOrdinal(3)); Assert.assertEquals(2, listener.getAddedValuesSize()); Assert.assertEquals(7, listener.getAddedValueOrdinal(11)); Assert.assertEquals(7, listener.getReassignedValuesSize()); Assert.assertEquals(new OrdinalReassignment(3, 2), listener.getOrdinalReassignment(4)); Assert.assertEquals(new OrdinalReassignment(8, 6), listener.getOrdinalReassignment(9)); } private static class TestTypeDeserializationStateListener extends TypeDeserializationStateListener<TypeF> { Map<Integer, Integer> removedValuesAndOrdinals = new HashMap<Integer, Integer>(); Map<Integer, Integer> addedValuesAndOrdinals = new HashMap<Integer, Integer>(); Map<Integer, OrdinalReassignment> reassignedValues = new HashMap<Integer, OrdinalReassignment>(); @Override public void removedObject(TypeF obj, int ordinal) { removedValuesAndOrdinals.put(obj.getValue(), ordinal); } @Override public void addedObject(TypeF obj, int ordinal) { addedValuesAndOrdinals.put(obj.getValue(), ordinal); } @Override public void reassignedObject(TypeF obj, int oldOrdinal, int newOrdinal) { OrdinalReassignment reassignment = new OrdinalReassignment(oldOrdinal, newOrdinal); reassignment.oldOrdinal = oldOrdinal; reassignment.newOrdinal = newOrdinal; reassignedValues.put(obj.getValue(), reassignment); } public int getRemovedValuesSize() { return removedValuesAndOrdinals.size(); } public int getRemovedValueOrdinal(Integer value) { return removedValuesAndOrdinals.get(value); } public int getAddedValuesSize() { return addedValuesAndOrdinals.size(); } public int getAddedValueOrdinal(Integer value) { return addedValuesAndOrdinals.get(value); } public int getReassignedValuesSize() { return reassignedValues.size(); } public OrdinalReassignment getOrdinalReassignment(Integer value) { return reassignedValues.get(value); } } static class OrdinalReassignment { private int oldOrdinal; private int newOrdinal; public OrdinalReassignment(int oldOrdinal, int newOrdinal) { this.oldOrdinal = oldOrdinal; this.newOrdinal = newOrdinal; } public boolean equals(Object other) { if(other instanceof OrdinalReassignment) { OrdinalReassignment otherOR = (OrdinalReassignment)other; return oldOrdinal == otherOR.oldOrdinal && newOrdinal == otherOR.newOrdinal; } return false; } } }
8,191
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/FastBlobSingleRecordSerializationTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.FastBlobStateEngine; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType; import com.netflix.zeno.fastblob.record.FastBlobSerializationRecord; import com.netflix.zeno.serializer.NFDeserializationRecord; import com.netflix.zeno.serializer.NFSerializationRecord; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FastBlobSingleRecordSerializationTest { private FastBlobStateEngine stateEngine; private FastBlobSerializationRecord rec; private FastBlobSchema schema; @Before public void setUp() { stateEngine = new FastBlobStateEngine(new SerializerFactory() { public NFTypeSerializer<?>[] createSerializers() { return new NFTypeSerializer<?>[] { new TestSchemaSerializer() }; } }); schema = stateEngine.getSerializer("TestType").getFastBlobSchema(); rec = new FastBlobSerializationRecord(schema); } @Test public void testSerializationAndDeserialization() { PojoWithAllTypes testType = new PojoWithAllTypes(); testType.boolField = true; testType.bytesField = new byte[] {7, 8 }; testType.doubleField = 3.14159265359d; testType.floatField = 2.71828182845f; testType.intField = 324515; testType.longField = 23523452345624634L; testType.stringField = "Hello world!"; NFTypeSerializer<PojoWithAllTypes> serializer = stateEngine.getSerializer("TestType"); serializer.serialize(testType, rec); ByteDataBuffer buf = new ByteDataBuffer(); rec.writeDataTo(buf); FastBlobDeserializationRecord deserializationRecord = new FastBlobDeserializationRecord(schema, buf.getUnderlyingArray()); deserializationRecord.position(0); PojoWithAllTypes deserialized = serializer.deserialize(deserializationRecord); Assert.assertTrue(deserialized.boolField); Assert.assertTrue(Arrays.equals(new byte[] {7, 8}, deserialized.bytesField)); Assert.assertEquals(testType.floatField, deserialized.floatField); Assert.assertEquals(testType.longField, deserialized.longField); Assert.assertEquals(testType.intField, deserialized.intField); Assert.assertEquals(testType.stringField, deserialized.stringField); } public class TestSchemaSerializer extends NFTypeSerializer<PojoWithAllTypes> { public TestSchemaSerializer() { super("TestType"); } @Override public void doSerialize(PojoWithAllTypes value, NFSerializationRecord rec) { serializePrimitive(rec, "bool", value.boolField); serializePrimitive(rec, "bool", value.boolField); serializePrimitive(rec, "int", value.intField); serializePrimitive(rec, "long", value.longField); serializePrimitive(rec, "float", value.floatField); serializePrimitive(rec, "float", value.floatField); serializePrimitive(rec, "double", value.doubleField); serializePrimitive(rec, "string", value.stringField); serializePrimitive(rec, "bytes", value.bytesField); } @Override protected PojoWithAllTypes doDeserialize(NFDeserializationRecord rec) { PojoWithAllTypes type = new PojoWithAllTypes(); type.boolField = deserializeBoolean(rec, "bool"); type.intField = deserializeInteger(rec, "int"); type.longField = deserializeLong(rec, "long"); type.floatField = deserializeFloat(rec, "float"); type.stringField = deserializePrimitiveString(rec, "string"); type.bytesField = deserializeBytes(rec, "bytes"); return type; } @Override protected FastBlobSchema createSchema() { return schema( field("bool", FieldType.BOOLEAN), field("int", FieldType.INT), field("long", FieldType.LONG), field("float", FieldType.FLOAT), field("double", FieldType.DOUBLE), field("string", FieldType.STRING), field("bytes", FieldType.BYTES) ); } @Override public Collection<NFTypeSerializer<?>> requiredSubSerializers() { return Collections.emptyList(); } } }
8,192
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/PojoWithAllTypes.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; public class PojoWithAllTypes { Integer intField; Long longField; Float floatField; Double doubleField; Boolean boolField; String stringField; byte[] bytesField; }
8,193
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/StreamingByteDataTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.record.StreamingByteData; import java.io.ByteArrayInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class StreamingByteDataTest { private StreamingByteData data; @Before public void setUp() { byte arr[] = new byte[100]; for(int i=0;i<arr.length;i++) { arr[i] = (byte)i; } ByteArrayInputStream bais = new ByteArrayInputStream(arr); data = new StreamingByteData(bais, 4); } @Test public void canBeUsedAsAStream() throws IOException { for(int i=0;i<100;i++) { Assert.assertEquals((int)i, data.read()); } Assert.assertEquals(-1, data.read()); } @Test public void canBeUsedAsASegmentedByteArray() { for(int i=0;i<100;i++) { Assert.assertEquals((int)i, data.get(i)); if(i > 16) Assert.assertEquals((int)i-16, data.get(i-16)); if(i < 84) Assert.assertEquals((int)i+16, data.get(i+16)); } } @Test public void canBeUsedAsSegmentedByteArrayAndStream() throws IOException { for(int i=0;i<100;i++) { if(i % 2 == 0) { Assert.assertEquals((int)i, data.get(i)); data.incrementStreamPosition(1); } else { Assert.assertEquals((int)i, data.read()); } } Assert.assertEquals(-1, data.read()); } }
8,194
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/FastBlobSchemaTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType; import com.netflix.zeno.fastblob.record.schema.FieldDefinition; import com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition; public class FastBlobSchemaTest { private FastBlobSchema schema; @Before public void setUp() { schema = new FastBlobSchema("test", 3); schema.addField("field1", new FieldDefinition(FieldType.INT)); schema.addField("field2", new TypedFieldDefinition(FieldType.OBJECT, "Field2")); schema.addField("field3", new FieldDefinition(FieldType.FLOAT)); } @Test public void retainsFieldDescriptions() { Assert.assertEquals(FieldType.INT, schema.getFieldType("field1")); Assert.assertEquals(FieldType.OBJECT, schema.getFieldType("field2")); Assert.assertEquals(FieldType.FLOAT, schema.getFieldType("field3")); } @Test public void serializesAndDeserializes() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); schema.writeTo(new DataOutputStream(os)); FastBlobSchema deserialized = FastBlobSchema.readFrom(new DataInputStream(new ByteArrayInputStream(os.toByteArray()))); Assert.assertEquals(3, deserialized.numFields()); Assert.assertEquals(FieldType.INT, deserialized.getFieldType("field1")); Assert.assertEquals(FieldType.OBJECT, deserialized.getFieldType("field2")); Assert.assertEquals(FieldType.FLOAT, deserialized.getFieldType("field3")); } @Test public void testEquals() throws IOException { FastBlobSchema otherSchema = new FastBlobSchema("test", 3); otherSchema.addField("field1", new FieldDefinition(FieldType.INT)); otherSchema.addField("field2", new TypedFieldDefinition(FieldType.OBJECT, "Field2")); otherSchema.addField("field3", new FieldDefinition(FieldType.FLOAT)); Assert.assertTrue(otherSchema.equals(schema)); FastBlobSchema anotherSchema = new FastBlobSchema("test", 3); anotherSchema.addField("field1", new FieldDefinition(FieldType.INT)); anotherSchema.addField("field2", new TypedFieldDefinition(FieldType.OBJECT, "Field2")); anotherSchema.addField("field3", new FieldDefinition(FieldType.INT)); Assert.assertFalse(anotherSchema.equals(schema)); } }
8,195
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/TypeDeserializationStateIteratorTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.state.TypeDeserializationStateIterator; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; public class TypeDeserializationStateIteratorTest { @Test public void skipsOverNullValues() { List<Integer> list = new ArrayList<Integer>(); list.add(null); list.add(1); list.add(2); list.add(null); list.add(4); list.add(null); TypeDeserializationStateIterator<Integer> iter = new TypeDeserializationStateIterator<Integer>(list); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(iter.next(), Integer.valueOf(1)); Assert.assertTrue(iter.hasNext()); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(iter.next(), Integer.valueOf(2)); Assert.assertEquals(iter.next(), Integer.valueOf(4)); Assert.assertFalse(iter.hasNext()); } }
8,196
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/FastBlobTypeSerializationStateTest.java
package com.netflix.zeno.fastblob.state; import com.netflix.zeno.fastblob.FastBlobImageUtils; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import com.netflix.zeno.serializer.common.IntegerSerializer; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FastBlobTypeSerializationStateTest { FastBlobTypeSerializationState<Integer> srcState; FastBlobTypeSerializationState<Integer> destState; @Before public void setUp() { srcState = new FastBlobTypeSerializationState<Integer>(new IntegerSerializer(), 2); destState = new FastBlobTypeSerializationState<Integer>(new IntegerSerializer(), 2); } @Test public void serializeAndDeserialize() throws Exception{ /// initialize data in "from" state addData(srcState, new byte[] { 1, 2 }, true, true); addData(srcState, new byte[] { 3, 4, 5 }, true, false); addData(srcState, new byte[] { 6, 7, 8, 9 }, false, true); final File f = File.createTempFile("pre", "suf"); DataOutputStream dos = new DataOutputStream(new FileOutputStream(f)); srcState.serializeTo(dos); dos.close(); DataInputStream dis = new DataInputStream(new FileInputStream(f)); destState.deserializeFrom(dis, 2); dis.close(); /// assert data was copied assertData(destState, new byte[] { 1, 2 }, true, true); assertData(destState, new byte[] { 3, 4, 5 }, true, false); assertData(destState, new byte[] { 6, 7, 8, 9 }, false, true); f.delete(); } private void addData(FastBlobTypeSerializationState<Integer> srcState, byte data[], boolean... images) { ByteDataBuffer buf = createBuffer(data); srcState.addData(buf, FastBlobImageUtils.toLong(images)); } private void assertData(FastBlobTypeSerializationState<Integer> destState, byte data[], boolean... images) { /// get the ordinal for the data, but don't add it to any images int ordinal = destState.addData(createBuffer(data), FastBlobImageUtils.toLong(false, false)); /// see which images this data was added to Assert.assertEquals(images[0], destState.getImageMembershipBitSet(0).get(ordinal)); Assert.assertEquals(images[1], destState.getImageMembershipBitSet(1).get(ordinal)); } private ByteDataBuffer createBuffer(byte[] data) { ByteDataBuffer buf = new ByteDataBuffer(); for(int i=0;i<data.length;i++) buf.write(data[i]); return buf; } }
8,197
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/ByteDataBufferTest.java
/* * * Copyright 2013 Netflix, 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.netflix.zeno.fastblob.state; import static org.junit.Assert.assertEquals; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import org.junit.Test; public class ByteDataBufferTest { @Test public void recordsData() { ByteDataBuffer buf = new ByteDataBuffer(256); for(int i=0;i<1000;i++) { buf.write((byte)i); } for(int i=0;i<1000;i++) { assertEquals((byte)i, buf.get(i)); } } @Test public void canBeReset() { ByteDataBuffer buf = new ByteDataBuffer(256); for(int i=0;i<1000;i++) { buf.write((byte)10); } buf.reset(); for(int i=0;i<1000;i++) { buf.write((byte)i); } for(int i=0;i<1000;i++) { assertEquals((byte)i, buf.get(i)); } } }
8,198
0
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state
Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/state/compressed/ByteSequenceRetainerTest.java
package com.netflix.zeno.fastblob.state.compressed; import com.netflix.zeno.fastblob.record.ByteDataBuffer; import org.junit.Assert; import org.junit.Test; public class ByteSequenceRetainerTest { @Test public void retainsByteSequences() { ByteSequenceRetainer retainer = new ByteSequenceRetainer(); ByteDataBuffer buf = new ByteDataBuffer(); buf.write((byte)1); buf.write((byte)2); buf.write((byte)3); retainer.addByteSequence(10, buf.getUnderlyingArray(), 0, 3); ByteDataBuffer retrieved = new ByteDataBuffer(); int retrievedLength = retainer.retrieveSequence(10, retrieved); Assert.assertEquals(3, retrievedLength); Assert.assertEquals(1, retrieved.get(0)); Assert.assertEquals(2, retrieved.get(1)); Assert.assertEquals(3, retrieved.get(2)); } }
8,199