Unnamed: 0
int64
0
6.45k
func
stringlengths
37
161k
target
class label
2 classes
project
stringlengths
33
167
1,488
@SuppressWarnings("unchecked") public class OObjectDatabaseTxPooled extends OObjectDatabaseTx implements ODatabasePooled { private OObjectDatabasePool ownerPool; public OObjectDatabaseTxPooled(final OObjectDatabasePool iOwnerPool, final String iURL, final String iUserName, final String iUserPassword) { super(iURL); ownerPool = iOwnerPool; super.open(iUserName, iUserPassword); } public void reuse(final Object iOwner, final Object[] iAdditionalArgs) { ownerPool = (OObjectDatabasePool) iOwner; if (isClosed()) open((String) iAdditionalArgs[0], (String) iAdditionalArgs[1]); init(); // getMetadata().reload(); ODatabaseRecordThreadLocal.INSTANCE.set(getUnderlying()); try { ODatabase current = underlying; while (!(current instanceof ODatabaseRaw) && ((ODatabaseComplex<?>) current).getUnderlying() != null) current = ((ODatabaseComplex<?>) current).getUnderlying(); ((ODatabaseRaw) current).callOnOpenListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on reusing database '%s' in pool", e, getName()); } } @Override public OObjectDatabaseTxPooled open(String iUserName, String iUserPassword) { throw new UnsupportedOperationException( "Database instance was retrieved from a pool. You cannot open the database in this way. Use directly a OObjectDatabaseTx instance if you want to manually open the connection"); } @Override public OObjectDatabaseTxPooled create() { throw new UnsupportedOperationException( "Database instance was retrieved from a pool. You cannot open the database in this way. Use directly a OObjectDatabaseTx instance if you want to manually open the connection"); } @Override public boolean isClosed() { return ownerPool == null || super.isClosed(); } /** * Avoid to close it but rather release itself to the owner pool. */ @Override public void close() { if (isClosed()) return; objects2Records.clear(); records2Objects.clear(); rid2Records.clear(); checkOpeness(); try { rollback(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } try { ODatabase current = underlying; while (!(current instanceof ODatabaseRaw) && ((ODatabaseComplex<?>) current).getUnderlying() != null) current = ((ODatabaseComplex<?>) current).getUnderlying(); ((ODatabaseRaw) current).callOnCloseListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } getLevel1Cache().clear(); if (ownerPool != null) { final OObjectDatabasePool localCopy = ownerPool; ownerPool = null; localCopy.release(this); } } public void forceClose() { super.close(); } @Override protected void checkOpeness() { if (ownerPool == null) throw new ODatabaseException( "Database instance has been released to the pool. Get another database instance from the pool with the right username and password"); super.checkOpeness(); } public boolean isUnderlyingOpen() { return !super.isClosed(); } }
1no label
object_src_main_java_com_orientechnologies_orient_object_db_OObjectDatabaseTxPooled.java
395
public final class BankersRounding { public static final int DEFAULT_SCALE = 2; public static final BigDecimal ZERO = setScale(0); public static int getScaleForCurrency(Currency currency) { if (currency != null) { return currency.getDefaultFractionDigits(); } else { return DEFAULT_SCALE; } } public static BigDecimal setScale(int scale, BigDecimal amount) { return amount.setScale(scale, BigDecimal.ROUND_HALF_EVEN); } public static BigDecimal setScale(int scale, double amount) { return setScale(scale, new BigDecimal(amount)); } public static double multiply(int scale, double multiplicand, double multiplier) { return setScale(scale, multiplicand).multiply(setScale(scale, multiplier)).doubleValue(); } public static BigDecimal divide(int scale, BigDecimal dividend, BigDecimal divisor) { return dividend.divide(divisor, scale, BigDecimal.ROUND_HALF_EVEN); } public static double divide(int scale, double dividend, double divisor) { return divide(setScale(scale, dividend), setScale(scale, divisor)).doubleValue(); } public static BigDecimal setScale(BigDecimal amount) { return setScale(DEFAULT_SCALE, amount); } public static BigDecimal setScale(BigDecimal amount, int scale) { return setScale(scale, amount); } public static BigDecimal setScale(double amount) { return setScale(DEFAULT_SCALE, new BigDecimal(amount)); } public static BigDecimal divide(BigDecimal dividend, BigDecimal divisor) { return divide(DEFAULT_SCALE, dividend, divisor); } public static BigDecimal zeroAmount() { return ZERO; } }
0true
common_src_main_java_org_broadleafcommerce_common_money_BankersRounding.java
385
public class DocumentationHover implements ITextHover, ITextHoverExtension, ITextHoverExtension2 { private CeylonEditor editor; public DocumentationHover(CeylonEditor editor) { this.editor = editor; } public IRegion getHoverRegion(ITextViewer textViewer, int offset) { IDocument document = textViewer.getDocument(); int start= -2; int end= -1; try { int pos= offset; char c; while (pos >= 0) { c= document.getChar(pos); if (!Character.isJavaIdentifierPart(c)) { break; } --pos; } start= pos; pos= offset; int length= document.getLength(); while (pos < length) { c= document.getChar(pos); if (!Character.isJavaIdentifierPart(c)) { break; } ++pos; } end= pos; } catch (BadLocationException x) { } if (start >= -1 && end > -1) { if (start == offset && end == offset) return new Region(offset, 0); else if (start == offset) return new Region(start, end - start); else return new Region(start + 1, end - start - 1); } return null; } final class CeylonLocationListener implements LocationListener { private final BrowserInformationControl control; CeylonLocationListener(BrowserInformationControl control) { this.control = control; } @Override public void changing(LocationEvent event) { String location = event.location; //necessary for windows environment (fix for blank page) //somehow related to this: https://bugs.eclipse.org/bugs/show_bug.cgi?id=129236 if (!"about:blank".equals(location)) { event.doit= false; } handleLink(location); /*else if (location.startsWith("javadoc:")) { final DocBrowserInformationControlInput input = (DocBrowserInformationControlInput) control.getInput(); int beginIndex = input.getHtml().indexOf("javadoc:")+8; final String handle = input.getHtml().substring(beginIndex, input.getHtml().indexOf("\"",beginIndex)); new Job("Fetching Javadoc") { @Override protected IStatus run(IProgressMonitor monitor) { final IJavaElement elem = JavaCore.create(handle); try { final String javadoc = JavadocContentAccess2.getHTMLContent((IMember) elem, true); if (javadoc!=null) { PlatformUI.getWorkbench().getProgressService() .runInUI(editor.getSite().getWorkbenchWindow(), new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { StringBuilder sb = new StringBuilder(); HTMLPrinter.insertPageProlog(sb, 0, getStyleSheet()); appendJavadoc(elem, javadoc, sb); HTMLPrinter.addPageEpilog(sb); control.setInput(new DocBrowserInformationControlInput(input, null, sb.toString(), 0)); } }, null); } } catch (Exception e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); }*/ } private void handleLink(String location) { if (location.startsWith("dec:")) { Referenceable target = getLinkedModel(editor, location); if (target!=null) { close(control); //FIXME: should have protocol to hide, rather than dispose gotoDeclaration(target, editor); } } else if (location.startsWith("doc:")) { Referenceable target = getLinkedModel(editor, location); if (target!=null) { control.setInput(getHoverInfo(target, control.getInput(), editor, null)); } } else if (location.startsWith("ref:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindReferencesAction(editor, (Declaration) target).run(); } else if (location.startsWith("sub:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindSubtypesAction(editor, (Declaration) target).run(); } else if (location.startsWith("act:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindRefinementsAction(editor, (Declaration) target).run(); } else if (location.startsWith("ass:")) { Referenceable target = getLinkedModel(editor, location); close(control); new FindAssignmentsAction(editor, (Declaration) target).run(); } else if (location.startsWith("stp:")) { close(control); CompilationUnit rn = editor.getParseController().getRootNode(); Node node = Nodes.findNode(rn, Integer.parseInt(location.substring(4))); for (SpecifyTypeProposal stp: SpecifyTypeProposal.createProposals(rn, node, editor)) { stp.apply(editor.getParseController().getDocument()); break; } } else if (location.startsWith("exv:")) { close(control); new ExtractValueProposal(editor).apply(editor.getParseController().getDocument()); } else if (location.startsWith("exf:")) { close(control); new ExtractFunctionProposal(editor).apply(editor.getParseController().getDocument()); } } @Override public void changed(LocationEvent event) {} } /** * Action to go back to the previous input in the hover control. */ static final class BackAction extends Action { private final BrowserInformationControl fInfoControl; public BackAction(BrowserInformationControl infoControl) { fInfoControl= infoControl; setText("Back"); ISharedImages images= getWorkbench().getSharedImages(); setImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK)); setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK_DISABLED)); update(); } @Override public void run() { BrowserInput previous= (BrowserInput) fInfoControl.getInput().getPrevious(); if (previous != null) { fInfoControl.setInput(previous); } } public void update() { BrowserInput current= fInfoControl.getInput(); if (current != null && current.getPrevious() != null) { BrowserInput previous= current.getPrevious(); setToolTipText("Back to " + previous.getInputName()); setEnabled(true); } else { setToolTipText("Back"); setEnabled(false); } } } /** * Action to go forward to the next input in the hover control. */ static final class ForwardAction extends Action { private final BrowserInformationControl fInfoControl; public ForwardAction(BrowserInformationControl infoControl) { fInfoControl= infoControl; setText("Forward"); ISharedImages images= getWorkbench().getSharedImages(); setImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD)); setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD_DISABLED)); update(); } @Override public void run() { BrowserInput next= (BrowserInput) fInfoControl.getInput().getNext(); if (next != null) { fInfoControl.setInput(next); } } public void update() { BrowserInput current= fInfoControl.getInput(); if (current != null && current.getNext() != null) { setToolTipText("Forward to " + current.getNext().getInputName()); setEnabled(true); } else { setToolTipText("Forward"); setEnabled(false); } } } /** * Action that shows the current hover contents in the Javadoc view. */ /*private static final class ShowInDocViewAction extends Action { private final BrowserInformationControl fInfoControl; public ShowInJavadocViewAction(BrowserInformationControl infoControl) { fInfoControl= infoControl; setText("Show in Ceylondoc View"); setImageDescriptor(JavaPluginImages.DESC_OBJS_JAVADOCTAG); //TODO: better image } @Override public void run() { DocBrowserInformationControlInput infoInput= (DocBrowserInformationControlInput) fInfoControl.getInput(); //TODO: check cast fInfoControl.notifyDelayedInputChange(null); fInfoControl.dispose(); //FIXME: should have protocol to hide, rather than dispose try { JavadocView view= (JavadocView) JavaPlugin.getActivePage().showView(JavaUI.ID_JAVADOC_VIEW); view.setInput(infoInput); } catch (PartInitException e) { JavaPlugin.log(e); } } }*/ /** * Action that opens the current hover input element. */ final class OpenDeclarationAction extends Action { private final BrowserInformationControl fInfoControl; public OpenDeclarationAction(BrowserInformationControl infoControl) { fInfoControl = infoControl; setText("Open Declaration"); setLocalImageDescriptors(this, "goto_input.gif"); } @Override public void run() { close(fInfoControl); //FIXME: should have protocol to hide, rather than dispose CeylonBrowserInput input = (CeylonBrowserInput) fInfoControl.getInput(); gotoDeclaration(getLinkedModel(editor, input.getAddress()), editor); } } private static void close(BrowserInformationControl control) { control.notifyDelayedInputChange(null); control.dispose(); } /** * The hover control creator. */ private IInformationControlCreator fHoverControlCreator; /** * The presentation control creator. */ private IInformationControlCreator fPresenterControlCreator; private IInformationControlCreator getInformationPresenterControlCreator() { if (fPresenterControlCreator == null) fPresenterControlCreator= new PresenterControlCreator(this); return fPresenterControlCreator; } @Override public IInformationControlCreator getHoverControlCreator() { return getHoverControlCreator("F2 for focus"); } public IInformationControlCreator getHoverControlCreator( String statusLineMessage) { if (fHoverControlCreator == null) { fHoverControlCreator= new HoverControlCreator(this, getInformationPresenterControlCreator(), statusLineMessage); } return fHoverControlCreator; } void addLinkListener(final BrowserInformationControl control) { control.addLocationListener(new CeylonLocationListener(control)); } public static Referenceable getLinkedModel(CeylonEditor editor, String location) { if (location==null) { return null; } else if (location.equals("doc:ceylon.language:ceylon.language:Nothing")) { return editor.getParseController().getRootNode().getUnit().getNothingDeclaration(); } TypeChecker tc = editor.getParseController().getTypeChecker(); String[] bits = location.split(":"); JDTModelLoader modelLoader = getModelLoader(tc); String moduleName = bits[1]; Module module = modelLoader.getLoadedModule(moduleName); if (module==null || bits.length==2) { return module; } Referenceable target = module.getPackage(bits[2]); for (int i=3; i<bits.length; i++) { Scope scope; if (target instanceof Scope) { scope = (Scope) target; } else if (target instanceof TypedDeclaration) { scope = ((TypedDeclaration) target).getType().getDeclaration(); } else { return null; } if (scope instanceof Value) { TypeDeclaration val = ((Value) scope).getTypeDeclaration(); if (val.isAnonymous()) { scope = val; } } target = scope.getDirectMember(bits[i], null, false); } return target; } public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { CeylonBrowserInput info = (CeylonBrowserInput) getHoverInfo2(textViewer, hoverRegion); return info!=null ? info.getHtml() : null; } @Override public CeylonBrowserInput getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { return internalGetHoverInfo(editor, hoverRegion); } static CeylonBrowserInput internalGetHoverInfo(CeylonEditor editor, IRegion hoverRegion) { if (editor==null || editor.getSelectionProvider()==null) { return null; } CeylonBrowserInput result = getExpressionHover(editor, hoverRegion); if (result==null) { result = getDeclarationHover(editor, hoverRegion); } return result; } static CeylonBrowserInput getExpressionHover(CeylonEditor editor, IRegion hoverRegion) { CeylonParseController parseController = editor.getParseController(); if (parseController==null) { return null; } Tree.CompilationUnit rn = parseController.getRootNode(); if (rn!=null) { int hoffset = hoverRegion.getOffset(); ITextSelection selection = editor.getSelectionFromThread(); if (selection!=null && selection.getOffset()<=hoffset && selection.getOffset()+selection.getLength()>=hoffset) { Node node = findNode(rn, selection.getOffset(), selection.getOffset()+selection.getLength()-1); if (node instanceof Tree.Type) { return getTypeHoverInfo(node, selection.getText(), editor.getCeylonSourceViewer().getDocument(), editor.getParseController().getProject()); } if (node instanceof Tree.Expression) { node = ((Tree.Expression) node).getTerm(); } if (node instanceof Tree.Term) { return getTermTypeHoverInfo(node, selection.getText(), editor.getCeylonSourceViewer().getDocument(), editor.getParseController().getProject()); } else { return null; } } else { return null; } } else { return null; } } static CeylonBrowserInput getDeclarationHover(CeylonEditor editor, IRegion hoverRegion) { CeylonParseController parseController = editor.getParseController(); if (parseController==null) { return null; } Tree.CompilationUnit rootNode = parseController.getRootNode(); if (rootNode!=null) { Node node = findNode(rootNode, hoverRegion.getOffset()); if (node instanceof Tree.ImportPath) { Referenceable r = ((Tree.ImportPath) node).getModel(); if (r!=null) { return getHoverInfo(r, null, editor, node); } else { return null; } } else if (node instanceof Tree.LocalModifier) { return getInferredTypeHoverInfo(node, parseController.getProject()); } else if (node instanceof Tree.Literal) { return getTermTypeHoverInfo(node, null, editor.getCeylonSourceViewer().getDocument(), parseController.getProject()); } else { return getHoverInfo(getReferencedDeclaration(node), null, editor, node); } } else { return null; } } private static CeylonBrowserInput getInferredTypeHoverInfo(Node node, IProject project) { ProducedType t = ((Tree.LocalModifier) node).getTypeModel(); if (t==null) return null; StringBuilder buffer = new StringBuilder(); HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet()); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("types.gif").toExternalForm(), 16, 16, "<tt>" + producedTypeLink(t, node.getUnit()) + "</tt>", 20, 4); buffer.append("<br/>"); if (!t.containsUnknowns()) { buffer.append("One quick assist available:<br/>"); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("correction_change.gif").toExternalForm(), 16, 16, "<a href=\"stp:" + node.getStartIndex() + "\">Specify explicit type</a>", 20, 4); } //buffer.append(getDocumentationFor(editor.getParseController(), t.getDeclaration())); HTMLPrinter.addPageEpilog(buffer); return new CeylonBrowserInput(null, null, buffer.toString()); } private static CeylonBrowserInput getTypeHoverInfo(Node node, String selectedText, IDocument doc, IProject project) { ProducedType t = ((Tree.Type) node).getTypeModel(); if (t==null) return null; // String expr = ""; // try { // expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1); // } // catch (BadLocationException e) { // e.printStackTrace(); // } String abbreviated = PRINTER.getProducedTypeName(t, node.getUnit()); String unabbreviated = VERBOSE_PRINTER.getProducedTypeName(t, node.getUnit()); StringBuilder buffer = new StringBuilder(); HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet()); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("types.gif").toExternalForm(), 16, 16, "<tt>" + producedTypeLink(t, node.getUnit()) + "</tt> ", 20, 4); if (!abbreviated.equals(unabbreviated)) { buffer.append("<br/>") .append("Abbreviation&nbsp;of:&nbsp;&nbsp;") .append(unabbreviated); } HTMLPrinter.addPageEpilog(buffer); return new CeylonBrowserInput(null, null, buffer.toString()); } private static CeylonBrowserInput getTermTypeHoverInfo(Node node, String selectedText, IDocument doc, IProject project) { ProducedType t = ((Tree.Term) node).getTypeModel(); if (t==null) return null; // String expr = ""; // try { // expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1); // } // catch (BadLocationException e) { // e.printStackTrace(); // } StringBuilder buffer = new StringBuilder(); HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet()); String desc = node instanceof Tree.Literal ? "literal" : "expression"; HTML.addImageAndLabel(buffer, null, HTML.fileUrl("types.gif").toExternalForm(), 16, 16, "<tt>" + producedTypeLink(t, node.getUnit()) + "</tt> " + desc, 20, 4); if (node instanceof Tree.StringLiteral) { buffer.append( "<br/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(STRINGS))) .append("'><pre>") .append('\"') .append(convertToHTMLContent(node.getText())) .append('\"') .append("</pre></code>"); // If a single char selection, then append info on that character too if (selectedText != null && codePointCount(selectedText, 0, selectedText.length()) == 1) { appendCharacterHoverInfo(buffer, selectedText); } } else if (node instanceof Tree.CharLiteral) { String character = node.getText(); if (character.length()>2) { appendCharacterHoverInfo(buffer, character.substring(1, character.length()-1)); } } else if (node instanceof Tree.NaturalLiteral) { buffer.append("<br/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(NUMBERS))) .append("'>"); String text = node.getText().replace("_", ""); switch (text.charAt(0)) { case '#': buffer.append(parseInt(text.substring(1),16)); break; case '$': buffer.append(parseInt(text.substring(1),2)); break; default: buffer.append(parseInt(text)); } buffer.append("</code>"); } else if (node instanceof Tree.FloatLiteral) { buffer.append("<br/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(NUMBERS))) .append("'>") .append(parseFloat(node.getText().replace("_", ""))) .append("</code>"); } if (selectedText!=null) { buffer.append("<br/>") .append("Two quick assists available:<br/>"); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("change.png").toExternalForm(), 16, 16, "<a href=\"exv:\">Extract value</a>", 20, 4); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("change.png").toExternalForm(), 16, 16, "<a href=\"exf:\">Extract function</a>", 20, 4); buffer.append("<br/>"); } HTMLPrinter.addPageEpilog(buffer); return new CeylonBrowserInput(null, null, buffer.toString()); } private static void appendCharacterHoverInfo(StringBuilder buffer, String character) { buffer.append( "<br/>") .append("<code style='color:") .append(toHex(getCurrentThemeColor(CHARS))) .append("'>") .append('\'') .append(convertToHTMLContent(character)) .append('\'') .append("</code>"); int codepoint = Character.codePointAt(character, 0); String name = Character.getName(codepoint); buffer.append("<br/>Unicode Name: <code>").append(name).append("</code>"); String hex = Integer.toHexString(codepoint).toUpperCase(); while (hex.length() < 4) { hex = "0" + hex; } buffer.append("<br/>Codepoint: <code>").append("U+").append(hex).append("</code>"); buffer.append("<br/>General Category: <code>").append(getCodepointGeneralCategoryName(codepoint)).append("</code>"); Character.UnicodeScript script = Character.UnicodeScript.of(codepoint); buffer.append("<br/>Script: <code>").append(script.name()).append("</code>"); Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint); buffer.append("<br/>Block: <code>").append(block).append("</code><br/>"); } private static String getCodepointGeneralCategoryName(int codepoint) { String gc; switch (Character.getType(codepoint)) { case Character.COMBINING_SPACING_MARK: gc = "Mark, combining spacing"; break; case Character.CONNECTOR_PUNCTUATION: gc = "Punctuation, connector"; break; case Character.CONTROL: gc = "Other, control"; break; case Character.CURRENCY_SYMBOL: gc = "Symbol, currency"; break; case Character.DASH_PUNCTUATION: gc = "Punctuation, dash"; break; case Character.DECIMAL_DIGIT_NUMBER: gc = "Number, decimal digit"; break; case Character.ENCLOSING_MARK: gc = "Mark, enclosing"; break; case Character.END_PUNCTUATION: gc = "Punctuation, close"; break; case Character.FINAL_QUOTE_PUNCTUATION: gc = "Punctuation, final quote"; break; case Character.FORMAT: gc = "Other, format"; break; case Character.INITIAL_QUOTE_PUNCTUATION: gc = "Punctuation, initial quote"; break; case Character.LETTER_NUMBER: gc = "Number, letter"; break; case Character.LINE_SEPARATOR: gc = "Separator, line"; break; case Character.LOWERCASE_LETTER: gc = "Letter, lowercase"; break; case Character.MATH_SYMBOL: gc = "Symbol, math"; break; case Character.MODIFIER_LETTER: gc = "Letter, modifier"; break; case Character.MODIFIER_SYMBOL: gc = "Symbol, modifier"; break; case Character.NON_SPACING_MARK: gc = "Mark, nonspacing"; break; case Character.OTHER_LETTER: gc = "Letter, other"; break; case Character.OTHER_NUMBER: gc = "Number, other"; break; case Character.OTHER_PUNCTUATION: gc = "Punctuation, other"; break; case Character.OTHER_SYMBOL: gc = "Symbol, other"; break; case Character.PARAGRAPH_SEPARATOR: gc = "Separator, paragraph"; break; case Character.PRIVATE_USE: gc = "Other, private use"; break; case Character.SPACE_SEPARATOR: gc = "Separator, space"; break; case Character.START_PUNCTUATION: gc = "Punctuation, open"; break; case Character.SURROGATE: gc = "Other, surrogate"; break; case Character.TITLECASE_LETTER: gc = "Letter, titlecase"; break; case Character.UNASSIGNED: gc = "Other, unassigned"; break; case Character.UPPERCASE_LETTER: gc = "Letter, uppercase"; break; default: gc = "&lt;Unknown&gt;"; } return gc; } private static String getIcon(Object obj) { if (obj instanceof Module) { return "jar_l_obj.gif"; } else if (obj instanceof Package) { return "package_obj.gif"; } else if (obj instanceof Declaration) { Declaration dec = (Declaration) obj; if (dec instanceof Class) { String icon = dec.isShared() ? "class_obj.gif" : "innerclass_private_obj.gif"; return decorateTypeIcon(dec, icon); } else if (dec instanceof Interface) { String icon = dec.isShared() ? "int_obj.gif" : "innerinterface_private_obj.gif"; return decorateTypeIcon(dec, icon); } else if (dec instanceof TypeAlias|| dec instanceof NothingType) { return "type_alias.gif"; } else if (dec.isParameter()) { if (dec instanceof Method) { return "methpro_obj.gif"; } else { return "field_protected_obj.gif"; } } else if (dec instanceof Method) { String icon = dec.isShared() ? "public_co.gif" : "private_co.gif"; return decorateFunctionIcon(dec, icon); } else if (dec instanceof MethodOrValue) { return dec.isShared() ? "field_public_obj.gif" : "field_private_obj.gif"; } else if (dec instanceof TypeParameter) { return "typevariable_obj.gif"; } } return null; } private static String decorateFunctionIcon(Declaration dec, String icon) { if (dec.isAnnotation()) { return icon.replace("co", "ann"); } else { return icon; } } private static String decorateTypeIcon(Declaration dec, String icon) { if (((TypeDeclaration) dec).getCaseTypes()!=null) { return icon.replace("obj", "enum"); } else if (dec.isAnnotation()) { return icon.replace("obj", "ann"); } else if (((TypeDeclaration) dec).isAlias()) { return icon.replace("obj", "alias"); } else { return icon; } } /** * Computes the hover info. * @param previousInput the previous input, or <code>null</code> * @param node * @param elements the resolved elements * @param editorInputElement the editor input, or <code>null</code> * * @return the HTML hover info for the given element(s) or <code>null</code> * if no information is available * @since 3.4 */ static CeylonBrowserInput getHoverInfo(Referenceable model, BrowserInput previousInput, CeylonEditor editor, Node node) { if (model instanceof Declaration) { Declaration dec = (Declaration) model; return new CeylonBrowserInput(previousInput, dec, getDocumentationFor(editor.getParseController(), dec, node, null)); } else if (model instanceof Package) { Package dec = (Package) model; return new CeylonBrowserInput(previousInput, dec, getDocumentationFor(editor.getParseController(), dec)); } else if (model instanceof Module) { Module dec = (Module) model; return new CeylonBrowserInput(previousInput, dec, getDocumentationFor(editor.getParseController(), dec)); } else { return null; } } private static void appendJavadoc(IJavaElement elem, StringBuilder sb) { if (elem instanceof IMember) { try { //TODO: Javadoc @ icon? IMember mem = (IMember) elem; String jd = JavadocContentAccess2.getHTMLContent(mem, true); if (jd!=null) { sb.append("<br/>").append(jd); String base = getBaseURL(mem, mem.isBinary()); int endHeadIdx= sb.indexOf("</head>"); sb.insert(endHeadIdx, "\n<base href='" + base + "'>\n"); } } catch (JavaModelException e) { e.printStackTrace(); } } } private static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException { if (isBinary) { // Source attachment usually does not include Javadoc resources // => Always use the Javadoc location as base: URL baseURL = JavaUI.getJavadocLocation(element, false); if (baseURL != null) { if (baseURL.getProtocol().equals("jar")) { // It's a JarURLConnection, which is not known to the browser widget. // Let's start the help web server: URL baseURL2 = PlatformUI.getWorkbench().getHelpSystem() .resolve(baseURL.toExternalForm(), true); if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available baseURL = baseURL2; } } return baseURL.toExternalForm(); } } else { IResource resource = element.getResource(); if (resource != null) { /* * Too bad: Browser widget knows nothing about EFS and custom URL handlers, * so IResource#getLocationURI() does not work in all cases. * We only support the local file system for now. * A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 . */ IPath location = resource.getLocation(); if (location != null) { return location.toFile().toURI().toString(); } } } return null; } public static String getDocumentationFor(CeylonParseController cpc, Package pack) { StringBuilder buffer= new StringBuilder(); addMainPackageDescription(pack, buffer); addPackageDocumentation(cpc, pack, buffer); addAdditionalPackageInfo(buffer, pack); addPackageMembers(buffer, pack); addPackageModuleInfo(pack, buffer); insertPageProlog(buffer, 0, HTML.getStyleSheet()); addPageEpilog(buffer); return buffer.toString(); } private static void addPackageMembers(StringBuilder buffer, Package pack) { boolean first = true; for (Declaration dec: pack.getMembers()) { if (dec instanceof Class && ((Class)dec).isOverloaded()) { continue; } if (dec.isShared() && !dec.isAnonymous()) { if (first) { buffer.append("<p>Contains:&nbsp;&nbsp;"); first = false; } else { buffer.append(", "); } /*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/ appendLink(buffer, dec); } } if (!first) { buffer.append(".</p>"); } } private static void appendLink(StringBuilder buffer, Referenceable dec) { buffer.append("<tt><a ").append(HTML.link(dec)).append(">"); if (dec instanceof Declaration) { buffer.append(((Declaration) dec).getName()); } else if (dec instanceof Package) { buffer.append(getLabel((Package)dec)); } else if (dec instanceof Module) { buffer.append(getLabel((Module)dec)); } buffer.append("</a></tt>"); } private static String link(Referenceable dec) { StringBuilder builder = new StringBuilder(); appendLink(builder, dec); return builder.toString(); } private static void addAdditionalPackageInfo(StringBuilder buffer, Package pack) { Module mod = pack.getModule(); if (mod.isJava()) { buffer.append("<p>This package is implemented in Java.</p>"); } if (JDKUtils.isJDKModule(mod.getNameAsString())) { buffer.append("<p>This package forms part of the Java SDK.</p>"); } } private static void addMainPackageDescription(Package pack, StringBuilder buffer) { if (pack.isShared()) { String ann = toHex(getCurrentThemeColor(ANNOTATIONS)); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("annotation_obj.gif").toExternalForm(), 16, 16, "<tt style='font-size:90%;color:" + ann + "'>shared</tt>" , 20, 4); } HTML.addImageAndLabel(buffer, pack, HTML.fileUrl(getIcon(pack)).toExternalForm(), 16, 16, "<tt style='font-size:102%'>" + HTML.highlightLine(description(pack)) + "</tt>", 20, 4); } private static void addPackageModuleInfo(Package pack, StringBuilder buffer) { Module mod = pack.getModule(); HTML.addImageAndLabel(buffer, mod, HTML.fileUrl(getIcon(mod)).toExternalForm(), 16, 16, "<span style='font-size:96%'>in module&nbsp;&nbsp;" + link(mod) + "</span>", 20, 2); } private static String description(Package pack) { return "package " + getLabel(pack); } public static String getDocumentationFor(ModuleDetails mod, String version, Scope scope, Unit unit) { return getDocumentationForModule(mod.getName(), version, mod.getDoc(), scope, unit); } public static String getDocumentationForModule(String name, String version, String doc, Scope scope, Unit unit) { StringBuilder buffer = new StringBuilder(); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("jar_l_obj.gif").toExternalForm(), 16, 16, "<tt style='font-size:102%'>" + HTML.highlightLine(description(name, version)) + "</tt></b>", 20, 4); if (doc!=null) { buffer.append(markdown(doc, scope, unit)); } insertPageProlog(buffer, 0, HTML.getStyleSheet()); addPageEpilog(buffer); return buffer.toString(); } private static String description(String name, String version) { return "module " + name + " \"" + version + "\""; } private static String getDocumentationFor(CeylonParseController cpc, Module mod) { StringBuilder buffer = new StringBuilder(); addMainModuleDescription(mod, buffer); addAdditionalModuleInfo(buffer, mod); addModuleDocumentation(cpc, mod, buffer); addModuleMembers(buffer, mod); insertPageProlog(buffer, 0, HTML.getStyleSheet()); addPageEpilog(buffer); return buffer.toString(); } private static void addAdditionalModuleInfo(StringBuilder buffer, Module mod) { if (mod.isJava()) { buffer.append("<p>This module is implemented in Java.</p>"); } if (mod.isDefault()) { buffer.append("<p>The default module for packages which do not belong to explicit module.</p>"); } if (JDKUtils.isJDKModule(mod.getNameAsString())) { buffer.append("<p>This module forms part of the Java SDK.</p>"); } } private static void addMainModuleDescription(Module mod, StringBuilder buffer) { HTML.addImageAndLabel(buffer, mod, HTML.fileUrl(getIcon(mod)).toExternalForm(), 16, 16, "<tt style='font-size:102%'>" + HTML.highlightLine(description(mod)) + "</tt>", 20, 4); } private static void addModuleDocumentation(CeylonParseController cpc, Module mod, StringBuilder buffer) { Unit unit = mod.getUnit(); PhasedUnit pu = null; if (unit instanceof CeylonUnit) { pu = ((CeylonUnit)unit).getPhasedUnit(); } if (pu!=null) { List<Tree.ModuleDescriptor> moduleDescriptors = pu.getCompilationUnit().getModuleDescriptors(); if (!moduleDescriptors.isEmpty()) { Tree.ModuleDescriptor refnode = moduleDescriptors.get(0); if (refnode!=null) { Scope linkScope = mod.getPackage(mod.getNameAsString()); appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope); appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope); appendSeeAnnotationContent(refnode.getAnnotationList(), buffer); } } } } private static void addPackageDocumentation(CeylonParseController cpc, Package pack, StringBuilder buffer) { Unit unit = pack.getUnit(); PhasedUnit pu = null; if (unit instanceof CeylonUnit) { pu = ((CeylonUnit)unit).getPhasedUnit(); } if (pu!=null) { List<Tree.PackageDescriptor> packageDescriptors = pu.getCompilationUnit().getPackageDescriptors(); if (!packageDescriptors.isEmpty()) { Tree.PackageDescriptor refnode = packageDescriptors.get(0); if (refnode!=null) { Scope linkScope = pack; appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope); appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope); appendSeeAnnotationContent(refnode.getAnnotationList(), buffer); } } } } private static void addModuleMembers(StringBuilder buffer, Module mod) { boolean first = true; for (Package pack: mod.getPackages()) { if (pack.isShared()) { if (first) { buffer.append("<p>Contains:&nbsp;&nbsp;"); first = false; } else { buffer.append(", "); } /*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/ appendLink(buffer, pack); } } if (!first) { buffer.append(".</p>"); } } private static String description(Module mod) { return "module " + getLabel(mod) + " \"" + mod.getVersion() + "\""; } public static String getDocumentationFor(CeylonParseController cpc, Declaration dec) { return getDocumentationFor(cpc, dec, null, null); } public static String getDocumentationFor(CeylonParseController cpc, Declaration dec, ProducedReference pr) { return getDocumentationFor(cpc, dec, null, pr); } private static String getDocumentationFor(CeylonParseController cpc, Declaration dec, Node node, ProducedReference pr) { if (dec==null) return null; if (dec instanceof Value) { TypeDeclaration val = ((Value) dec).getTypeDeclaration(); if (val!=null && val.isAnonymous()) { dec = val; } } Unit unit = cpc.getRootNode().getUnit(); StringBuilder buffer = new StringBuilder(); insertPageProlog(buffer, 0, HTML.getStyleSheet()); addMainDescription(buffer, dec, node, pr, cpc, unit); boolean obj = addInheritanceInfo(dec, node, pr, buffer, unit); addContainerInfo(dec, node, buffer); //TODO: use the pr to get the qualifying type?? boolean hasDoc = addDoc(cpc, dec, node, buffer); addRefinementInfo(cpc, dec, node, buffer, hasDoc, unit); //TODO: use the pr to get the qualifying type?? addReturnType(dec, buffer, node, pr, obj, unit); addParameters(cpc, dec, node, pr, buffer, unit); addClassMembersInfo(dec, buffer); addUnitInfo(dec, buffer); addPackageInfo(dec, buffer); if (dec instanceof NothingType) { addNothingTypeInfo(buffer); } else { appendExtraActions(dec, buffer); } addPageEpilog(buffer); return buffer.toString(); } private static void addMainDescription(StringBuilder buffer, Declaration dec, Node node, ProducedReference pr, CeylonParseController cpc, Unit unit) { StringBuilder buf = new StringBuilder(); if (dec.isShared()) buf.append("shared&nbsp;"); if (dec.isActual()) buf.append("actual&nbsp;"); if (dec.isDefault()) buf.append("default&nbsp;"); if (dec.isFormal()) buf.append("formal&nbsp;"); if (dec instanceof Value && ((Value) dec).isLate()) buf.append("late&nbsp;"); if (isVariable(dec)) buf.append("variable&nbsp;"); if (dec.isNative()) buf.append("native&nbsp;"); if (dec instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration) dec; if (td.isSealed()) buf.append("sealed&nbsp;"); if (td.isFinal()) buf.append("final&nbsp;"); if (td instanceof Class && ((Class)td).isAbstract()) buf.append("abstract&nbsp;"); } if (dec.isAnnotation()) buf.append("annotation&nbsp;"); if (buf.length()!=0) { String ann = toHex(getCurrentThemeColor(ANNOTATIONS)); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("annotation_obj.gif").toExternalForm(), 16, 16, "<tt style='font-size:91%;color:" + ann + "'>" + buf + "</tt>", 20, 4); } HTML.addImageAndLabel(buffer, dec, HTML.fileUrl(getIcon(dec)).toExternalForm(), 16, 16, "<tt style='font-size:105%'>" + (dec.isDeprecated() ? "<s>":"") + description(dec, node, pr, cpc, unit) + (dec.isDeprecated() ? "</s>":"") + "</tt>", 20, 4); } private static void addClassMembersInfo(Declaration dec, StringBuilder buffer) { if (dec instanceof ClassOrInterface) { if (!dec.getMembers().isEmpty()) { boolean first = true; for (Declaration mem: dec.getMembers()) { if (mem instanceof Method && ((Method) mem).isOverloaded()) { continue; } if (mem.isShared()) { if (first) { buffer.append("<p>Members:&nbsp;&nbsp;"); first = false; } else { buffer.append(", "); } appendLink(buffer, mem); } } if (!first) { buffer.append(".</p>"); //extraBreak = true; } } } } private static void addNothingTypeInfo(StringBuilder buffer) { buffer.append("Special bottom type defined by the language. " + "<code>Nothing</code> is assignable to all types, but has no value. " + "A function or value of type <code>Nothing</code> either throws " + "an exception, or never returns."); } private static boolean addInheritanceInfo(Declaration dec, Node node, ProducedReference pr, StringBuilder buffer, Unit unit) { buffer.append("<p><div style='padding-left:20px'>"); boolean obj=false; if (dec instanceof TypedDeclaration) { TypeDeclaration td = ((TypedDeclaration) dec).getTypeDeclaration(); if (td!=null && td.isAnonymous()) { obj=true; documentInheritance(td, node, pr, buffer, unit); } } else if (dec instanceof TypeDeclaration) { documentInheritance((TypeDeclaration) dec, node, pr, buffer, unit); } buffer.append("</div></p>"); documentTypeParameters(dec, node, pr, buffer, unit); buffer.append("</p>"); return obj; } private static void addRefinementInfo(CeylonParseController cpc, Declaration dec, Node node, StringBuilder buffer, boolean hasDoc, Unit unit) { Declaration rd = dec.getRefinedDeclaration(); if (dec!=rd && rd!=null) { buffer.append("<p>"); TypeDeclaration superclass = (TypeDeclaration) rd.getContainer(); ClassOrInterface outer = (ClassOrInterface) dec.getContainer(); ProducedType sup = getQualifyingType(node, outer).getSupertype(superclass); HTML.addImageAndLabel(buffer, rd, HTML.fileUrl(rd.isFormal() ? "implm_co.gif" : "over_co.gif").toExternalForm(), 16, 16, "refines&nbsp;&nbsp;" + link(rd) + "&nbsp;&nbsp;declared by&nbsp;&nbsp;<tt>" + producedTypeLink(sup, unit) + "</tt>", 20, 2); buffer.append("</p>"); if (!hasDoc) { Tree.Declaration refnode2 = (Tree.Declaration) getReferencedNode(rd, cpc); if (refnode2!=null) { appendDocAnnotationContent(refnode2.getAnnotationList(), buffer, resolveScope(rd)); } } } } private static void appendParameters(Declaration d, ProducedReference pr, Unit unit, StringBuilder result/*, CeylonParseController cpc*/) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params.getParameters()) { appendParameter(result, pr, p, unit); // if (cpc!=null) { // result.append(getDefaultValueDescription(p, cpc)); // } result.append(", "); } result.setLength(result.length()-2); result.append(")"); } } } } } private static void appendParameter(StringBuilder result, ProducedReference pr, Parameter p, Unit unit) { if (p.getModel() == null) { result.append(p.getName()); } else { ProducedTypedReference ppr = pr==null ? null : pr.getTypedParameter(p); if (p.isDeclaredVoid()) { result.append(HTML.keyword("void")); } else { if (ppr!=null) { ProducedType pt = ppr.getType(); if (p.isSequenced() && pt!=null) { pt = p.getDeclaration().getUnit() .getSequentialElementType(pt); } result.append(producedTypeLink(pt, unit)); if (p.isSequenced()) { result.append(p.isAtLeastOne()?'+':'*'); } } else if (p.getModel() instanceof Method) { result.append(HTML.keyword("function")); } else { result.append(HTML.keyword("value")); } } result.append("&nbsp;"); appendLink(result, p.getModel()); appendParameters(p.getModel(), ppr, unit, result); } } private static void addParameters(CeylonParseController cpc, Declaration dec, Node node, ProducedReference pr, StringBuilder buffer, Unit unit) { if (dec instanceof Functional) { if (pr==null) { pr = getProducedReference(dec, node); } if (pr==null) return; for (ParameterList pl: ((Functional) dec).getParameterLists()) { if (!pl.getParameters().isEmpty()) { buffer.append("<p>"); for (Parameter p: pl.getParameters()) { MethodOrValue model = p.getModel(); if (model!=null) { StringBuilder param = new StringBuilder(); param.append("<span style='font-size:96%'>accepts&nbsp;&nbsp;<tt>"); appendParameter(param, pr, p, unit); param.append(HTML.highlightLine(getInitialValueDescription(model, cpc))) .append("</tt>"); Tree.Declaration refNode = (Tree.Declaration) getReferencedNode(model, cpc); if (refNode!=null) { appendDocAnnotationContent(refNode.getAnnotationList(), param, resolveScope(dec)); } param.append("</span>"); HTML.addImageAndLabel(buffer, model, HTML.fileUrl("methpro_obj.gif").toExternalForm(), 16, 16, param.toString(), 20, 2); } } buffer.append("</p>"); } } } } private static void addReturnType(Declaration dec, StringBuilder buffer, Node node, ProducedReference pr, boolean obj, Unit unit) { if (dec instanceof TypedDeclaration && !obj) { if (pr==null) { pr = getProducedReference(dec, node); } if (pr==null) return; ProducedType ret = pr.getType(); if (ret!=null) { buffer.append("<p>"); StringBuilder buf = new StringBuilder("returns&nbsp;&nbsp;<tt>"); buf.append(producedTypeLink(ret, unit)).append("|"); buf.setLength(buf.length()-1); buf.append("</tt>"); HTML.addImageAndLabel(buffer, ret.getDeclaration(), HTML.fileUrl("stepreturn_co.gif").toExternalForm(), 16, 16, buf.toString(), 20, 2); buffer.append("</p>"); } } } private static ProducedTypeNamePrinter printer(boolean abbreviate) { return new ProducedTypeNamePrinter(abbreviate, true, false, true) { @Override protected String getSimpleDeclarationName(Declaration declaration, Unit unit) { return "<a " + HTML.link(declaration) + ">" + super.getSimpleDeclarationName(declaration, unit) + "</a>"; } @Override protected String amp() { return "&amp;"; } @Override protected String lt() { return "&lt;"; } @Override protected String gt() { return "&gt;"; } }; } private static ProducedTypeNamePrinter PRINTER = printer(true); private static ProducedTypeNamePrinter VERBOSE_PRINTER = printer(false); private static String producedTypeLink(ProducedType pt, Unit unit) { return PRINTER.getProducedTypeName(pt, unit); } private static ProducedReference getProducedReference(Declaration dec, Node node) { if (node instanceof Tree.MemberOrTypeExpression) { return ((Tree.MemberOrTypeExpression) node).getTarget(); } else if (node instanceof Tree.Type) { return ((Tree.Type) node).getTypeModel(); } ClassOrInterface outer = dec.isClassOrInterfaceMember() ? (ClassOrInterface) dec.getContainer() : null; return dec.getProducedReference(getQualifyingType(node, outer), Collections.<ProducedType>emptyList()); } private static boolean addDoc(CeylonParseController cpc, Declaration dec, Node node, StringBuilder buffer) { boolean hasDoc = false; Node rn = getReferencedNode(dec, cpc); if (rn instanceof Tree.Declaration) { Tree.Declaration refnode = (Tree.Declaration) rn; appendDeprecatedAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec)); int len = buffer.length(); appendDocAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec)); hasDoc = buffer.length()!=len; appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec)); appendSeeAnnotationContent(refnode.getAnnotationList(), buffer); } else { appendJavadoc(dec, cpc.getProject(), buffer, node); } return hasDoc; } private static void addContainerInfo(Declaration dec, Node node, StringBuilder buffer) { buffer.append("<p>"); if (dec.isParameter()) { Declaration pd = ((MethodOrValue) dec).getInitializerParameter() .getDeclaration(); if (pd.getName().startsWith("anonymous#")) { buffer.append("Parameter of anonymous function."); } else { buffer.append("Parameter of&nbsp;&nbsp;"); appendLink(buffer, pd); buffer.append("."); } // HTML.addImageAndLabel(buffer, pd, // HTML.fileUrl(getIcon(pd)).toExternalForm(), // 16, 16, // "<span style='font-size:96%'>parameter of&nbsp;&nbsp;<tt><a " + HTML.link(pd) + ">" + // pd.getName() +"</a></tt><span>", 20, 2); } else if (dec instanceof TypeParameter) { Declaration pd = ((TypeParameter) dec).getDeclaration(); buffer.append("Type parameter of&nbsp;&nbsp;"); appendLink(buffer, pd); buffer.append("."); // HTML.addImageAndLabel(buffer, pd, // HTML.fileUrl(getIcon(pd)).toExternalForm(), // 16, 16, // "<span style='font-size:96%'>type parameter of&nbsp;&nbsp;<tt><a " + HTML.link(pd) + ">" + // pd.getName() +"</a></tt></span>", // 20, 2); } else { if (dec.isClassOrInterfaceMember()) { ClassOrInterface outer = (ClassOrInterface) dec.getContainer(); ProducedType qt = getQualifyingType(node, outer); if (qt!=null) { Unit unit = node==null ? null : node.getUnit(); buffer.append("Member of&nbsp;&nbsp;<tt>" + producedTypeLink(qt, unit) + "</tt>."); // HTML.addImageAndLabel(buffer, outer, // HTML.fileUrl(getIcon(outer)).toExternalForm(), // 16, 16, // "<span style='font-size:96%'>member of&nbsp;&nbsp;<tt>" + // producedTypeLink(qt, unit) + "</tt></span>", // 20, 2); } } } buffer.append("</p>"); } private static void addPackageInfo(Declaration dec, StringBuilder buffer) { buffer.append("<p>"); Package pack = dec.getUnit().getPackage(); if ((dec.isShared() || dec.isToplevel()) && !(dec instanceof NothingType)) { String label; if (pack.getNameAsString().isEmpty()) { label = "<span style='font-size:96%'>in default package</span>"; } else { label = "<span style='font-size:96%'>in package&nbsp;&nbsp;" + link(pack) + "</span>"; } HTML.addImageAndLabel(buffer, pack, HTML.fileUrl(getIcon(pack)).toExternalForm(), 16, 16, label, 20, 2); Module mod = pack.getModule(); HTML.addImageAndLabel(buffer, mod, HTML.fileUrl(getIcon(mod)).toExternalForm(), 16, 16, "<span style='font-size:96%'>in module&nbsp;&nbsp;" + link(mod) + "</span>", 20, 2); } buffer.append("</p>"); } private static ProducedType getQualifyingType(Node node, ClassOrInterface outer) { if (outer == null) { return null; } if (node instanceof Tree.MemberOrTypeExpression) { ProducedReference pr = ((Tree.MemberOrTypeExpression) node).getTarget(); if (pr!=null) { return pr.getQualifyingType(); } } if (node instanceof Tree.QualifiedType) { return ((Tree.QualifiedType) node).getOuterType().getTypeModel(); } return outer.getType(); } private static void addUnitInfo(Declaration dec, StringBuilder buffer) { buffer.append("<p>"); String unitName = null; if (dec.getUnit() instanceof CeylonUnit) { // Manage the case of CeylonBinaryUnit : getFileName() would return the class file name. // but getCeylonFileName() will return the ceylon source file name if any. unitName = ((CeylonUnit)dec.getUnit()).getCeylonFileName(); } if (unitName == null) { unitName = dec.getUnit().getFilename(); } HTML.addImageAndLabel(buffer, null, HTML.fileUrl("unit.gif").toExternalForm(), 16, 16, "<span style='font-size:96%'>declared in&nbsp;&nbsp;<tt><a href='dec:" + HTML.declink(dec) + "'>"+ unitName + "</a></tt></span>", 20, 2); //} buffer.append("</p>"); } private static void appendExtraActions(Declaration dec, StringBuilder buffer) { buffer.append("<p>"); HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_ref_obj.png").toExternalForm(), 16, 16, "<span style='font-size:96%'><a href='ref:" + HTML.declink(dec) + "'>find references</a> to&nbsp;&nbsp;<tt>" + dec.getName() + "</tt></span>", 20, 2); if (dec instanceof ClassOrInterface) { HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_decl_obj.png").toExternalForm(), 16, 16, "<span style='font-size:96%'><a href='sub:" + HTML.declink(dec) + "'>find subtypes</a> of&nbsp;&nbsp;<tt>" + dec.getName() + "</tt></span>", 20, 2); } if (dec instanceof MethodOrValue || dec instanceof TypeParameter) { HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_ref_obj.png").toExternalForm(), 16, 16, "<span style='font-size:96%'><a href='ass:" + HTML.declink(dec) + "'>find assignments</a> to&nbsp;&nbsp;<tt>" + dec.getName() + "</tt></span>", 20, 2); } if (dec.isFormal() || dec.isDefault()) { HTML.addImageAndLabel(buffer, null, HTML.fileUrl("search_decl_obj.png").toExternalForm(), 16, 16, "<span style='font-size:96%'><a href='act:" + HTML.declink(dec) + "'>find refinements</a> of&nbsp;&nbsp;<tt>" + dec.getName() + "</tt></span>", 20, 2); } buffer.append("</p>"); } private static void documentInheritance(TypeDeclaration dec, Node node, ProducedReference pr, StringBuilder buffer, Unit unit) { if (pr==null) { pr = getProducedReference(dec, node); } ProducedType type; if (pr instanceof ProducedType) { type = (ProducedType) pr; } else { type = dec.getType(); } List<ProducedType> cts = type.getCaseTypes(); if (cts!=null) { StringBuilder cases = new StringBuilder(); for (ProducedType ct: cts) { if (cases.length()>0) { cases.append(" | "); } cases.append(producedTypeLink(ct, unit)); } if (dec.getSelfType()!=null) { cases.append(" (self type)"); } HTML.addImageAndLabel(buffer, null, HTML.fileUrl("sub.gif").toExternalForm(), 16, 16, " <tt style='font-size:96%'>of&nbsp;" + cases +"</tt>", 20, 2); } if (dec instanceof Class) { ProducedType sup = type.getExtendedType(); if (sup!=null) { HTML.addImageAndLabel(buffer, sup.getDeclaration(), HTML.fileUrl("superclass.gif").toExternalForm(), 16, 16, "<tt style='font-size:96%'>extends&nbsp;" + producedTypeLink(sup, unit) +"</tt>", 20, 2); } } List<ProducedType> sts = type.getSatisfiedTypes(); if (!sts.isEmpty()) { StringBuilder satisfies = new StringBuilder(); for (ProducedType st: sts) { if (satisfies.length()>0) { satisfies.append(" &amp; "); } satisfies.append(producedTypeLink(st, unit)); } HTML.addImageAndLabel(buffer, null, HTML.fileUrl("super.gif").toExternalForm(), 16, 16, "<tt style='font-size:96%'>satisfies&nbsp;" + satisfies +"</tt>", 20, 2); } } private static void documentTypeParameters(Declaration dec, Node node, ProducedReference pr, StringBuilder buffer, Unit unit) { if (pr==null) { pr = getProducedReference(dec, node); } List<TypeParameter> typeParameters; if (dec instanceof Functional) { typeParameters = ((Functional) dec).getTypeParameters(); } else if (dec instanceof Interface) { typeParameters = ((Interface) dec).getTypeParameters(); } else { typeParameters = Collections.emptyList(); } for (TypeParameter tp: typeParameters) { StringBuilder bounds = new StringBuilder(); for (ProducedType st: tp.getSatisfiedTypes()) { if (bounds.length() == 0) { bounds.append(" satisfies "); } else { bounds.append(" &amp; "); } bounds.append(producedTypeLink(st, dec.getUnit())); } String arg; ProducedType typeArg = pr==null ? null : pr.getTypeArguments().get(tp); if (typeArg!=null && !tp.getType().isExactly(typeArg)) { arg = "&nbsp;=&nbsp;" + producedTypeLink(typeArg, unit); } else { arg = ""; } HTML.addImageAndLabel(buffer, tp, HTML.fileUrl(getIcon(tp)).toExternalForm(), 16, 16, "<tt style='font-size:96%'>given&nbsp;<a " + HTML.link(tp) + ">" + tp.getName() + "</a>" + bounds + arg + "</tt>", 20, 4); } } private static String description(Declaration dec, Node node, ProducedReference pr, CeylonParseController cpc, Unit unit) { if (pr==null) { pr = getProducedReference(dec, node); } String description = getDocDescriptionFor(dec, pr, unit); if (dec instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration) dec; if (td.isAlias() && td.getExtendedType()!=null) { description += " => " + td.getExtendedType().getProducedTypeName(); } } if (dec instanceof Value && !isVariable(dec) || dec instanceof Method) { description += getInitialValueDescription(dec, cpc); } return HTML.highlightLine(description); } private static void appendJavadoc(Declaration model, IProject project, StringBuilder buffer, Node node) { try { appendJavadoc(getJavaElement(model), buffer); } catch (JavaModelException jme) { jme.printStackTrace(); } } private static void appendDocAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation, Scope linkScope) { if (annotationList!=null) { AnonymousAnnotation aa = annotationList.getAnonymousAnnotation(); if (aa!=null) { documentation.append(markdown(aa.getStringLiteral().getText(), linkScope, annotationList.getUnit())); // HTML.addImageAndLabel(documentation, null, // HTML.fileUrl("toc_obj.gif").toExternalForm(), // 16, 16, // markdown(aa.getStringLiteral().getText(), // linkScope, annotationList.getUnit()), // 20, 0); } for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("doc".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (!args.isEmpty()) { Tree.PositionalArgument a = args.get(0); if (a instanceof Tree.ListedArgument) { String text = ((Tree.ListedArgument) a).getExpression() .getTerm().getText(); if (text!=null) { documentation.append(markdown(text, linkScope, annotationList.getUnit())); } } } } } } } } } private static void appendDeprecatedAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation, Scope linkScope) { if (annotationList!=null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("deprecated".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (!args.isEmpty()) { Tree.PositionalArgument a = args.get(0); if (a instanceof Tree.ListedArgument) { String text = ((Tree.ListedArgument) a).getExpression() .getTerm().getText(); if (text!=null) { documentation.append(markdown("_(This is a deprecated program element.)_\n\n" + text, linkScope, annotationList.getUnit())); } } } } } } } } } private static void appendSeeAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation) { if (annotationList!=null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("see".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { StringBuilder sb = new StringBuilder(); List<Tree.PositionalArgument> args = argList.getPositionalArguments(); for (Tree.PositionalArgument arg: args) { if (arg instanceof Tree.ListedArgument) { Tree.Term term = ((Tree.ListedArgument) arg).getExpression().getTerm(); if (term instanceof Tree.MetaLiteral) { Declaration dec = ((Tree.MetaLiteral) term).getDeclaration(); if (dec!=null) { String dn = dec.getName(); if (dec.isClassOrInterfaceMember()) { dn = ((ClassOrInterface) dec.getContainer()).getName() + "." + dn; } if (sb.length()!=0) sb.append(", "); sb.append("<tt><a "+HTML.link(dec)+">"+dn+"</a></tt>"); } } } } if (sb.length()!=0) { HTML.addImageAndLabel(documentation, null, HTML.fileUrl("link_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16, "see " + sb + ".", 20, 2); } } } } } } } private static void appendThrowAnnotationContent(Tree.AnnotationList annotationList, StringBuilder documentation, Scope linkScope) { if (annotationList!=null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof Tree.BaseMemberExpression) { String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("throws".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); if (argList!=null) { List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (args.isEmpty()) continue; Tree.PositionalArgument typeArg = args.get(0); Tree.PositionalArgument textArg = args.size()>1 ? args.get(1) : null; if (typeArg instanceof Tree.ListedArgument && (textArg==null || textArg instanceof Tree.ListedArgument)) { Tree.Term typeArgTerm = ((Tree.ListedArgument) typeArg).getExpression().getTerm(); Tree.Term textArgTerm = textArg==null ? null : ((Tree.ListedArgument) textArg).getExpression().getTerm(); String text = textArgTerm instanceof Tree.StringLiteral ? textArgTerm.getText() : ""; if (typeArgTerm instanceof Tree.MetaLiteral) { Declaration dec = ((Tree.MetaLiteral) typeArgTerm).getDeclaration(); if (dec!=null) { String dn = dec.getName(); if (typeArgTerm instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) typeArgTerm).getPrimary(); if (p instanceof Tree.MemberOrTypeExpression) { dn = ((Tree.MemberOrTypeExpression) p).getDeclaration().getName() + "." + dn; } } HTML.addImageAndLabel(documentation, dec, HTML.fileUrl("ihigh_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16, "throws <tt><a "+HTML.link(dec)+">"+dn+"</a></tt>" + markdown(text, linkScope, annotationList.getUnit()), 20, 2); } } } } } } } } } private static String markdown(String text, final Scope linkScope, final Unit unit) { if (text == null || text.isEmpty()) { return text; } Builder builder = Configuration.builder().forceExtentedProfile(); builder.setCodeBlockEmitter(new CeylonBlockEmitter()); if (linkScope!=null && unit!=null) { builder.setSpecialLinkEmitter(new CeylonSpanEmitter(linkScope, unit)); } else { builder.setSpecialLinkEmitter(new UnlinkedSpanEmitter()); } return Processor.process(text, builder.build()); } private static Scope resolveScope(Declaration decl) { if (decl == null) { return null; } else if (decl instanceof Scope) { return (Scope) decl; } else { return decl.getContainer(); } } static Module resolveModule(Scope scope) { if (scope == null) { return null; } else if (scope instanceof Package) { return ((Package) scope).getModule(); } else { return resolveModule(scope.getContainer()); } } /** * Creates the "enriched" control. */ private final class PresenterControlCreator extends AbstractReusableInformationControlCreator { private final DocumentationHover docHover; PresenterControlCreator(DocumentationHover docHover) { this.docHover = docHover; } @Override public IInformationControl doCreateInformationControl(Shell parent) { if (isAvailable(parent)) { ToolBarManager tbm = new ToolBarManager(SWT.FLAT); BrowserInformationControl control = new BrowserInformationControl(parent, APPEARANCE_JAVADOC_FONT, tbm); final BackAction backAction = new BackAction(control); backAction.setEnabled(false); tbm.add(backAction); final ForwardAction forwardAction = new ForwardAction(control); tbm.add(forwardAction); forwardAction.setEnabled(false); //final ShowInJavadocViewAction showInJavadocViewAction= new ShowInJavadocViewAction(iControl); //tbm.add(showInJavadocViewAction); final OpenDeclarationAction openDeclarationAction = new OpenDeclarationAction(control); tbm.add(openDeclarationAction); // final SimpleSelectionProvider selectionProvider = new SimpleSelectionProvider(); //TODO: an action to open the generated ceylondoc // from the doc archive, in a browser window /*if (fSite != null) { OpenAttachedJavadocAction openAttachedJavadocAction= new OpenAttachedJavadocAction(fSite); openAttachedJavadocAction.setSpecialSelectionProvider(selectionProvider); openAttachedJavadocAction.setImageDescriptor(DESC_ELCL_OPEN_BROWSER); openAttachedJavadocAction.setDisabledImageDescriptor(DESC_DLCL_OPEN_BROWSER); selectionProvider.addSelectionChangedListener(openAttachedJavadocAction); selectionProvider.setSelection(new StructuredSelection()); tbm.add(openAttachedJavadocAction); }*/ IInputChangedListener inputChangeListener = new IInputChangedListener() { public void inputChanged(Object newInput) { backAction.update(); forwardAction.update(); // if (newInput == null) { // selectionProvider.setSelection(new StructuredSelection()); // } // else boolean isDeclaration = false; if (newInput instanceof CeylonBrowserInput) { // Object inputElement = ((CeylonBrowserInput) newInput).getInputElement(); // selectionProvider.setSelection(new StructuredSelection(inputElement)); //showInJavadocViewAction.setEnabled(isJavaElementInput); isDeclaration = ((CeylonBrowserInput) newInput).getAddress()!=null; } openDeclarationAction.setEnabled(isDeclaration); } }; control.addInputChangeListener(inputChangeListener); tbm.update(true); docHover.addLinkListener(control); return control; } else { return new DefaultInformationControl(parent, true); } } } private final class HoverControlCreator extends AbstractReusableInformationControlCreator { private final DocumentationHover docHover; private String statusLineMessage; private final IInformationControlCreator enrichedControlCreator; HoverControlCreator(DocumentationHover docHover, IInformationControlCreator enrichedControlCreator, String statusLineMessage) { this.docHover = docHover; this.enrichedControlCreator = enrichedControlCreator; this.statusLineMessage = statusLineMessage; } @Override public IInformationControl doCreateInformationControl(Shell parent) { if (enrichedControlCreator!=null && isAvailable(parent)) { BrowserInformationControl control = new BrowserInformationControl(parent, APPEARANCE_JAVADOC_FONT, statusLineMessage) { @Override public IInformationControlCreator getInformationPresenterControlCreator() { return enrichedControlCreator; } }; if (docHover!=null) { docHover.addLinkListener(control); } return control; } else { return new DefaultInformationControl(parent, statusLineMessage); } } } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_hover_DocumentationHover.java
33
@Service("blProductFieldService") public class ProductFieldServiceImpl extends AbstractRuleBuilderFieldService { @Override public void init() { fields.add(new FieldData.Builder() .label("rule_productUrl") .name("url") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productUrlKey") .name("urlKey") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productIsFeatured") .name("isFeaturedProduct") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); fields.add(new FieldData.Builder() .label("rule_productManufacturer") .name("manufacturer") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productModel") .name("model") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuName") .name("defaultSku.name") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuFulfillmentType") .name("defaultSku.fulfillmentType") .operators("blcOperators_Enumeration") .options("blcOptions_FulfillmentType") .type(SupportedFieldType.BROADLEAF_ENUMERATION) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuInventoryType") .name("defaultSku.inventoryType") .operators("blcOperators_Enumeration") .options("blcOptions_InventoryType") .type(SupportedFieldType.BROADLEAF_ENUMERATION) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuDescription") .name("defaultSku.description") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuLongDescription") .name("defaultSku.longDescription") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuTaxable") .name("defaultSku.taxable") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuAvailable") .name("defaultSku.available") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuStartDate") .name("defaultSku.activeStartDate") .operators("blcOperators_Date") .options("[]") .type(SupportedFieldType.DATE) .build()); fields.add(new FieldData.Builder() .label("rule_productSkuEndDate") .name("defaultSku.activeEndDate") .operators("blcOperators_Date") .options("[]") .type(SupportedFieldType.DATE) .build()); } @Override public String getName() { return RuleIdentifier.PRODUCT; } @Override public String getDtoClassName() { return "org.broadleafcommerce.core.catalog.domain.ProductImpl"; } }
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_ProductFieldServiceImpl.java
45
public class HeartbeatIAmAliveProcessor implements MessageProcessor { private final MessageHolder output; private final ClusterContext clusterContext; public HeartbeatIAmAliveProcessor( MessageHolder output, ClusterContext clusterContext ) { this.output = output; this.clusterContext = clusterContext; } @Override public boolean process( Message<? extends MessageType> message ) { if ( !message.isInternal() && !message.getMessageType().equals( HeartbeatMessage.i_am_alive ) ) { // We assume the FROM header always exists. String from = message.getHeader( Message.FROM ); if ( !from.equals( message.getHeader( Message.TO ) ) ) { InstanceId theId; if ( message.hasHeader( Message.INSTANCE_ID ) ) { // INSTANCE_ID is there since after 1.9.6 theId = new InstanceId( Integer.parseInt( message.getHeader( Message.INSTANCE_ID ) ) ); } else { theId = clusterContext.getConfiguration().getIdForUri( URI.create( from ) ); } if ( theId != null && clusterContext.getConfiguration().getMembers().containsKey( theId ) && !clusterContext.isMe( theId ) ) { output.offer( message.copyHeadersTo( Message.internal( HeartbeatMessage.i_am_alive, new HeartbeatMessage.IAmAliveState( theId ) ), Message.FROM, Message.INSTANCE_ID ) ); } } } return true; } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_protocol_heartbeat_HeartbeatIAmAliveProcessor.java
360
public class FilterDefinition { protected String name; protected List<FilterParameter> params; protected String entityImplementationClassName; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<FilterParameter> getParams() { return params; } public void setParams(List<FilterParameter> params) { this.params = params; } public String getEntityImplementationClassName() { return entityImplementationClassName; } public void setEntityImplementationClassName(String entityImplementationClassName) { this.entityImplementationClassName = entityImplementationClassName; } }
0true
common_src_main_java_org_broadleafcommerce_common_filter_FilterDefinition.java
2,090
public class PutAllOperation extends AbstractMapOperation implements PartitionAwareOperation, BackupAwareOperation { private MapEntrySet entrySet; private boolean initialLoad = false; private List<Map.Entry<Data, Data>> backupEntrySet; private List<RecordInfo> backupRecordInfos; public PutAllOperation(String name, MapEntrySet entrySet) { super(name); this.entrySet = entrySet; } public PutAllOperation(String name, MapEntrySet entrySet, boolean initialLoad) { super(name); this.entrySet = entrySet; this.initialLoad = initialLoad; } public PutAllOperation() { } public void run() { backupRecordInfos = new ArrayList<RecordInfo>(); backupEntrySet = new ArrayList<Map.Entry<Data, Data>>(); int partitionId = getPartitionId(); RecordStore recordStore = mapService.getRecordStore(partitionId, name); Set<Map.Entry<Data, Data>> entries = entrySet.getEntrySet(); InternalPartitionService partitionService = getNodeEngine().getPartitionService(); Set<Data> keysToInvalidate = new HashSet<Data>(); for (Map.Entry<Data, Data> entry : entries) { Data dataKey = entry.getKey(); Data dataValue = entry.getValue(); if (partitionId == partitionService.getPartitionId(dataKey)) { Data dataOldValue = null; if (initialLoad) { recordStore.putFromLoad(dataKey, dataValue, -1); } else { dataOldValue = mapService.toData(recordStore.put(dataKey, dataValue, -1)); } mapService.interceptAfterPut(name, dataValue); EntryEventType eventType = dataOldValue == null ? EntryEventType.ADDED : EntryEventType.UPDATED; mapService.publishEvent(getCallerAddress(), name, eventType, dataKey, dataOldValue, dataValue); keysToInvalidate.add(dataKey); if (mapContainer.getWanReplicationPublisher() != null && mapContainer.getWanMergePolicy() != null) { Record record = recordStore.getRecord(dataKey); final SimpleEntryView entryView = mapService.createSimpleEntryView(dataKey, mapService.toData(dataValue), record); mapService.publishWanReplicationUpdate(name, entryView); } backupEntrySet.add(entry); RecordInfo replicationInfo = mapService.createRecordInfo(recordStore.getRecord(dataKey)); backupRecordInfos.add(replicationInfo); } } invalidateNearCaches(keysToInvalidate); } protected final void invalidateNearCaches(Set<Data> keys) { if (mapService.isNearCacheAndInvalidationEnabled(name)) { mapService.invalidateAllNearCaches(name, keys); } } @Override public Object getResponse() { return true; } @Override public String toString() { return "PutAllOperation{" + '}'; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(entrySet); out.writeBoolean(initialLoad); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); entrySet = in.readObject(); initialLoad = in.readBoolean(); } @Override public boolean shouldBackup() { return !backupEntrySet.isEmpty(); } public final int getAsyncBackupCount() { return mapContainer.getAsyncBackupCount(); } public final int getSyncBackupCount() { return mapContainer.getBackupCount(); } @Override public Operation getBackupOperation() { return new PutAllBackupOperation(name, backupEntrySet, backupRecordInfos); } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_PutAllOperation.java
1,623
public class ClusterDynamicSettingsModule extends AbstractModule { private final DynamicSettings clusterDynamicSettings; public ClusterDynamicSettingsModule() { clusterDynamicSettings = new DynamicSettings(); clusterDynamicSettings.addDynamicSetting(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTES); clusterDynamicSettings.addDynamicSetting(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP + "*"); clusterDynamicSettings.addDynamicSetting(BalancedShardsAllocator.SETTING_INDEX_BALANCE_FACTOR, Validator.FLOAT); clusterDynamicSettings.addDynamicSetting(BalancedShardsAllocator.SETTING_PRIMARY_BALANCE_FACTOR, Validator.FLOAT); clusterDynamicSettings.addDynamicSetting(BalancedShardsAllocator.SETTING_SHARD_BALANCE_FACTOR, Validator.FLOAT); clusterDynamicSettings.addDynamicSetting(BalancedShardsAllocator.SETTING_THRESHOLD, Validator.NON_NEGATIVE_FLOAT); clusterDynamicSettings.addDynamicSetting(ConcurrentRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_CLUSTER_CONCURRENT_REBALANCE, Validator.INTEGER); clusterDynamicSettings.addDynamicSetting(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE); clusterDynamicSettings.addDynamicSetting(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION); clusterDynamicSettings.addDynamicSetting(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION); clusterDynamicSettings.addDynamicSetting(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_REPLICA_ALLOCATION); clusterDynamicSettings.addDynamicSetting(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, Validator.INTEGER); clusterDynamicSettings.addDynamicSetting(FilterAllocationDecider.CLUSTER_ROUTING_INCLUDE_GROUP + "*"); clusterDynamicSettings.addDynamicSetting(FilterAllocationDecider.CLUSTER_ROUTING_EXCLUDE_GROUP + "*"); clusterDynamicSettings.addDynamicSetting(FilterAllocationDecider.CLUSTER_ROUTING_REQUIRE_GROUP + "*"); clusterDynamicSettings.addDynamicSetting(IndicesFilterCache.INDICES_CACHE_FILTER_SIZE); clusterDynamicSettings.addDynamicSetting(IndicesFilterCache.INDICES_CACHE_FILTER_EXPIRE, Validator.TIME); clusterDynamicSettings.addDynamicSetting(IndicesStore.INDICES_STORE_THROTTLE_TYPE); clusterDynamicSettings.addDynamicSetting(IndicesStore.INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC, Validator.BYTES_SIZE); clusterDynamicSettings.addDynamicSetting(IndicesTTLService.INDICES_TTL_INTERVAL, Validator.TIME); clusterDynamicSettings.addDynamicSetting(MetaData.SETTING_READ_ONLY); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_FILE_CHUNK_SIZE, Validator.BYTES_SIZE); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_TRANSLOG_OPS, Validator.INTEGER); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_TRANSLOG_SIZE, Validator.BYTES_SIZE); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_COMPRESS); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_CONCURRENT_STREAMS, Validator.POSITIVE_INTEGER); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_CONCURRENT_SMALL_FILE_STREAMS, Validator.POSITIVE_INTEGER); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC, Validator.BYTES_SIZE); clusterDynamicSettings.addDynamicSetting(RecoverySettings.INDICES_RECOVERY_MAX_SIZE_PER_SEC, Validator.BYTES_SIZE); clusterDynamicSettings.addDynamicSetting(ThreadPool.THREADPOOL_GROUP + "*"); clusterDynamicSettings.addDynamicSetting(ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES, Validator.INTEGER); clusterDynamicSettings.addDynamicSetting(ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, Validator.INTEGER); clusterDynamicSettings.addDynamicSetting(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK); clusterDynamicSettings.addDynamicSetting(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK); clusterDynamicSettings.addDynamicSetting(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED); clusterDynamicSettings.addDynamicSetting(InternalClusterInfoService.INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL, Validator.TIME); clusterDynamicSettings.addDynamicSetting(SnapshotInProgressAllocationDecider.CLUSTER_ROUTING_ALLOCATION_SNAPSHOT_RELOCATION_ENABLED); clusterDynamicSettings.addDynamicSetting(InternalCircuitBreakerService.CIRCUIT_BREAKER_MAX_BYTES_SETTING, Validator.MEMORY_SIZE); clusterDynamicSettings.addDynamicSetting(InternalCircuitBreakerService.CIRCUIT_BREAKER_OVERHEAD_SETTING, Validator.NON_NEGATIVE_DOUBLE); clusterDynamicSettings.addDynamicSetting(DestructiveOperations.REQUIRES_NAME); } public void addDynamicSettings(String... settings) { clusterDynamicSettings.addDynamicSettings(settings); } public void addDynamicSetting(String setting, Validator validator) { clusterDynamicSettings.addDynamicSetting(setting, validator); } @Override protected void configure() { bind(DynamicSettings.class).annotatedWith(ClusterDynamicSettings.class).toInstance(clusterDynamicSettings); } }
1no label
src_main_java_org_elasticsearch_cluster_settings_ClusterDynamicSettingsModule.java
53
public abstract class OAbstractLock implements OLock { @Override public <V> V callInLock(final Callable<V> iCallback) throws Exception { lock(); try { return iCallback.call(); } finally { unlock(); } } }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OAbstractLock.java
515
public class SystemTimeTest extends TestCase { private TimeSource mockTimeSource; protected void setUp() throws Exception { super.setUp(); mockTimeSource = createMock(TimeSource.class); } protected void tearDown() throws Exception { SystemTime.reset(); super.tearDown(); } /** * Test method for {@link SystemTime#setGlobalTimeSource(TimeSource)}. */ public void testSetGlobalTimeSource() { expect(mockTimeSource.timeInMillis()).andReturn(100L).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); assertEquals(100L, SystemTime.asMillis()); verify(); } /** * Test method for {@link SystemTime#resetGlobalTimeSource()}. */ public void testResetGlobalTimeSource() { expect(mockTimeSource.timeInMillis()).andReturn(200L).anyTimes(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); SystemTime.resetGlobalTimeSource(); assertTrue(200L != SystemTime.asMillis()); verify(); } /** * Test method for {@link SystemTime#setLocalTimeSource(TimeSource)}. */ public void testSetLocalTimeSource() { expect(mockTimeSource.timeInMillis()).andReturn(300L).atLeastOnce(); replay(mockTimeSource); SystemTime.setLocalTimeSource(mockTimeSource); assertEquals(300L, SystemTime.asMillis()); verify(); } /** * Test method for {@link SystemTime#resetLocalTimeSource()}. */ public void testResetLocalTimeSource() { expect(mockTimeSource.timeInMillis()).andReturn(400L).anyTimes(); replay(mockTimeSource); SystemTime.setLocalTimeSource(mockTimeSource); SystemTime.resetLocalTimeSource(); assertTrue(400L != SystemTime.asMillis()); verify(); } /** * Test method for {@link SystemTime#resetLocalTimeSource()}. */ public void testLocalOverridesGlobal() { TimeSource mockLocalTimeSource = createMock(TimeSource.class); expect(mockTimeSource.timeInMillis()).andReturn(500L).anyTimes(); expect(mockLocalTimeSource.timeInMillis()).andReturn(600L).atLeastOnce(); replay(mockTimeSource, mockLocalTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); SystemTime.setLocalTimeSource(mockLocalTimeSource); assertEquals(600L, SystemTime.asMillis()); SystemTime.resetLocalTimeSource(); assertEquals(500L, SystemTime.asMillis()); verify(); } /** * Test method for {@link SystemTime#reset()}. */ public void testReset() { TimeSource mockLocalTimeSource = createMock(TimeSource.class); expect(mockTimeSource.timeInMillis()).andReturn(700L).anyTimes(); expect(mockLocalTimeSource.timeInMillis()).andReturn(800L).anyTimes(); replay(mockTimeSource, mockLocalTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); SystemTime.setLocalTimeSource(mockLocalTimeSource); SystemTime.reset(); assertTrue(SystemTime.asMillis() > 800L); verify(); } /** * Test method for {@link SystemTime#asMillis()}. */ public void testAsMillis() { expect(mockTimeSource.timeInMillis()).andReturn(1000L).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); assertEquals(1000L, SystemTime.asMillis()); verify(); } /** * Test method for {@link SystemTime#asDate()}. */ public void testAsDate() { expect(mockTimeSource.timeInMillis()).andReturn(1100L).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); assertEquals(1100L, SystemTime.asDate().getTime()); verify(); } /** * Test method for {@link SystemTime#asCalendar()}. */ public void testAsCalendar() { expect(mockTimeSource.timeInMillis()).andReturn(1200L).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); assertEquals(1200L, SystemTime.asCalendar().getTimeInMillis()); verify(); } /** * Test method for {@link SystemTime#asMillis(boolean)}. */ public void testAsMillisBoolean() { Calendar cal = new GregorianCalendar(2010, 1, 2, 3, 4, 5); long timeInMillis = cal.getTimeInMillis() + 3; // Add a few milliseconds for good measure expect(mockTimeSource.timeInMillis()).andReturn(timeInMillis).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); Calendar calMidnight = new GregorianCalendar(2010, 1, 2, 0, 0, 0); calMidnight.set(Calendar.MILLISECOND, 0); assertEquals(calMidnight.getTimeInMillis(), SystemTime.asMillis(false)); assertEquals(timeInMillis, SystemTime.asMillis(true)); verify(); } /** * Test method for {@link SystemTime#asCalendar(boolean)}. */ public void testAsCalendarBoolean() { Calendar cal = new GregorianCalendar(2010, 1, 2, 3, 4, 5); cal.set(Calendar.MILLISECOND, 3); // Add a few milliseconds for good measure expect(mockTimeSource.timeInMillis()).andReturn(cal.getTimeInMillis()).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); Calendar calMidnight = new GregorianCalendar(2010, 1, 2, 0, 0, 0); calMidnight.set(Calendar.MILLISECOND, 0); assertEquals(calMidnight, SystemTime.asCalendar(false)); assertEquals(cal, SystemTime.asCalendar(true)); verify(); } /** * Test method for {@link SystemTime#asDate(boolean)}. */ public void testAsDateBoolean() { Calendar cal = new GregorianCalendar(2010, 1, 2, 3, 4, 5); cal.set(Calendar.MILLISECOND, 3); // Add a few milliseconds for good measure expect(mockTimeSource.timeInMillis()).andReturn(cal.getTimeInMillis()).atLeastOnce(); replay(mockTimeSource); SystemTime.setGlobalTimeSource(mockTimeSource); Calendar calMidnight = new GregorianCalendar(2010, 1, 2, 0, 0, 0); calMidnight.set(Calendar.MILLISECOND, 0); assertEquals(calMidnight.getTimeInMillis(), SystemTime.asDate(false).getTime()); assertEquals(cal.getTimeInMillis(), SystemTime.asDate(true).getTime()); verify(); } }
0true
common_src_test_java_org_broadleafcommerce_common_time_SystemTimeTest.java
326
public interface OStoragePhysicalClusterConfiguration extends OStorageClusterConfiguration { public OStorageFileConfiguration[] getInfoFiles(); public String getMaxSize(); }
0true
core_src_main_java_com_orientechnologies_orient_core_config_OStoragePhysicalClusterConfiguration.java
198
public class OJNADirectMemory implements ODirectMemory { private static final CLibrary C_LIBRARY = OCLibraryFactory.INSTANCE.library(); public static final OJNADirectMemory INSTANCE = new OJNADirectMemory(); @Override public long allocate(byte[] bytes) { final long pointer = allocate(bytes.length); set(pointer, bytes, 0, bytes.length); return pointer; } @Override public long allocate(long size) { return Native.malloc(size); } @Override public void free(long pointer) { Native.free(pointer); } @Override public byte[] get(long pointer, int length) { return new Pointer(pointer).getByteArray(0, length); } @Override public void get(long pointer, byte[] array, int arrayOffset, int length) { new Pointer(pointer).read(0, array, arrayOffset, length); } @Override public void set(long pointer, byte[] content, int arrayOffset, int length) { new Pointer(pointer).write(0, content, arrayOffset, length); } @Override public int getInt(long pointer) { return new Pointer(pointer).getInt(0); } @Override public void setInt(long pointer, int value) { new Pointer(pointer).setInt(0, value); } @Override public void setShort(long pointer, short value) { new Pointer(pointer).setShort(0, value); } @Override public short getShort(long pointer) { return new Pointer(pointer).getShort(0); } @Override public long getLong(long pointer) { return new Pointer(pointer).getLong(0); } @Override public void setLong(long pointer, long value) { new Pointer(pointer).setLong(0, value); } @Override public byte getByte(long pointer) { return new Pointer(pointer).getByte(0); } @Override public void setByte(long pointer, byte value) { new Pointer(pointer).setByte(0, value); } @Override public void setChar(long pointer, char value) { final short short_char = (short) value; new Pointer(pointer).setShort(0, short_char); } @Override public char getChar(long pointer) { final short short_char = new Pointer(pointer).getShort(0); return (char) short_char; } @Override public void moveData(long srcPointer, long destPointer, long len) { C_LIBRARY.memoryMove(srcPointer, destPointer, len); } }
0true
nativeos_src_main_java_com_orientechnologies_nio_OJNADirectMemory.java
78
@SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V> extends BulkTask<K,V,Double> { final ObjectByObjectToDouble<? super K, ? super V> transformer; final DoubleByDoubleToDouble reducer; final double basis; double result; MapReduceMappingsToDoubleTask<K,V> rights, nextRight; MapReduceMappingsToDoubleTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceMappingsToDoubleTask<K,V> nextRight, ObjectByObjectToDouble<? super K, ? super V> transformer, double basis, DoubleByDoubleToDouble reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; } public final Double getRawResult() { return result; } public final void compute() { final ObjectByObjectToDouble<? super K, ? super V> transformer; final DoubleByDoubleToDouble reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { double r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceMappingsToDoubleTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.apply(r, transformer.apply(p.key, p.val)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V> t = (MapReduceMappingsToDoubleTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.apply(t.result, s.result); s = t.rights = s.nextRight; } } } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
454
executor.execute(new Runnable() { @Override public void run() { for (int i = 0; i < operations; i++) { map1.put("foo-" + i, "bar"); } } }, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
0true
hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java
76
public class OSharedResourceExternal extends OSharedResourceAbstract implements OSharedResource { @Override public void acquireExclusiveLock() { super.acquireExclusiveLock(); } @Override public void acquireSharedLock() { super.acquireSharedLock(); } @Override public void releaseExclusiveLock() { super.releaseExclusiveLock(); } @Override public void releaseSharedLock() { super.releaseSharedLock(); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceExternal.java
463
new Thread(){ public void run() { try { semaphore.acquire(); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_semaphore_ClientSemaphoreTest.java
3,673
public class ParentFieldMapper extends AbstractFieldMapper<Uid> implements InternalMapper, RootMapper { public static final String NAME = "_parent"; public static final String CONTENT_TYPE = "_parent"; public static class Defaults extends AbstractFieldMapper.Defaults { public static final String NAME = ParentFieldMapper.NAME; public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(true); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(true); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY); FIELD_TYPE.freeze(); } } public static class Builder extends Mapper.Builder<Builder, ParentFieldMapper> { protected String indexName; private String type; protected PostingsFormatProvider postingsFormat; public Builder() { super(Defaults.NAME); this.indexName = name; } public Builder type(String type) { this.type = type; return builder; } protected Builder postingsFormat(PostingsFormatProvider postingsFormat) { this.postingsFormat = postingsFormat; return builder; } @Override public ParentFieldMapper build(BuilderContext context) { if (type == null) { throw new MapperParsingException("Parent mapping must contain the parent type"); } return new ParentFieldMapper(name, indexName, type, postingsFormat, null, context.indexSettings()); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { ParentFieldMapper.Builder builder = parent(); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("type")) { builder.type(fieldNode.toString()); } else if (fieldName.equals("postings_format")) { String postingFormatName = fieldNode.toString(); builder.postingsFormat(parserContext.postingFormatService().get(postingFormatName)); } } return builder; } } private final String type; private final BytesRef typeAsBytes; protected ParentFieldMapper(String name, String indexName, String type, PostingsFormatProvider postingsFormat, @Nullable Settings fieldDataSettings, Settings indexSettings) { super(new Names(name, indexName, indexName, name), Defaults.BOOST, new FieldType(Defaults.FIELD_TYPE), null, Lucene.KEYWORD_ANALYZER, Lucene.KEYWORD_ANALYZER, postingsFormat, null, null, null, fieldDataSettings, indexSettings); this.type = type; this.typeAsBytes = type == null ? null : new BytesRef(type); } public ParentFieldMapper() { this(Defaults.NAME, Defaults.NAME, null, null, null, null); } public String type() { return type; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("string"); } @Override public boolean hasDocValues() { return false; } @Override public void preParse(ParseContext context) throws IOException { } @Override public void postParse(ParseContext context) throws IOException { parse(context); } @Override public void validate(ParseContext context) throws MapperParsingException { } @Override public boolean includeInObject() { return true; } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { if (!active()) { return; } if (context.parser().currentName() != null && context.parser().currentName().equals(Defaults.NAME)) { // we are in the parsing of _parent phase String parentId = context.parser().text(); context.sourceToParse().parent(parentId); fields.add(new Field(names.indexName(), Uid.createUid(context.stringBuilder(), type, parentId), fieldType)); } else { // otherwise, we are running it post processing of the xcontent String parsedParentId = context.doc().get(Defaults.NAME); if (context.sourceToParse().parent() != null) { String parentId = context.sourceToParse().parent(); if (parsedParentId == null) { if (parentId == null) { throw new MapperParsingException("No parent id provided, not within the document, and not externally"); } // we did not add it in the parsing phase, add it now fields.add(new Field(names.indexName(), Uid.createUid(context.stringBuilder(), type, parentId), fieldType)); } else if (parentId != null && !parsedParentId.equals(Uid.createUid(context.stringBuilder(), type, parentId))) { throw new MapperParsingException("Parent id mismatch, document value is [" + Uid.createUid(parsedParentId).id() + "], while external value is [" + parentId + "]"); } } } // we have parent mapping, yet no value was set, ignore it... } @Override public Uid value(Object value) { if (value == null) { return null; } return Uid.createUid(value.toString()); } @Override public Object valueForSearch(Object value) { if (value == null) { return null; } String sValue = value.toString(); if (sValue == null) { return null; } int index = sValue.indexOf(Uid.DELIMITER); if (index == -1) { return sValue; } return sValue.substring(index + 1); } @Override public BytesRef indexedValueForSearch(Object value) { if (value instanceof BytesRef) { BytesRef bytesRef = (BytesRef) value; if (Uid.hasDelimiter(bytesRef)) { return bytesRef; } return Uid.createUidAsBytes(typeAsBytes, bytesRef); } String sValue = value.toString(); if (sValue.indexOf(Uid.DELIMITER) == -1) { return Uid.createUidAsBytes(type, sValue); } return super.indexedValueForSearch(value); } @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { if (context == null) { return super.termQuery(value, context); } return new ConstantScoreQuery(termFilter(value, context)); } @Override public Filter termFilter(Object value, @Nullable QueryParseContext context) { if (context == null) { return super.termFilter(value, context); } BytesRef bValue = BytesRefs.toBytesRef(value); if (Uid.hasDelimiter(bValue)) { return new TermFilter(new Term(names.indexName(), bValue)); } List<String> types = new ArrayList<String>(context.mapperService().types().size()); for (DocumentMapper documentMapper : context.mapperService()) { if (!documentMapper.parentFieldMapper().active()) { types.add(documentMapper.type()); } } if (types.isEmpty()) { return Queries.MATCH_NO_FILTER; } else if (types.size() == 1) { return new TermFilter(new Term(names.indexName(), Uid.createUidAsBytes(types.get(0), bValue))); } else { // we use all non child types, cause we don't know if its exact or not... List<BytesRef> typesValues = new ArrayList<BytesRef>(types.size()); for (String type : context.mapperService().types()) { typesValues.add(Uid.createUidAsBytes(type, bValue)); } return new TermsFilter(names.indexName(), typesValues); } } @Override public Filter termsFilter(List values, @Nullable QueryParseContext context) { if (context == null) { return super.termsFilter(values, context); } // This will not be invoked if values is empty, so don't check for empty if (values.size() == 1) { return termFilter(values.get(0), context); } List<String> types = new ArrayList<String>(context.mapperService().types().size()); for (DocumentMapper documentMapper : context.mapperService()) { if (!documentMapper.parentFieldMapper().active()) { types.add(documentMapper.type()); } } List<BytesRef> bValues = new ArrayList<BytesRef>(values.size()); for (Object value : values) { BytesRef bValue = BytesRefs.toBytesRef(value); if (Uid.hasDelimiter(bValue)) { bValues.add(bValue); } else { // we use all non child types, cause we don't know if its exact or not... for (String type : types) { bValues.add(Uid.createUidAsBytes(type, bValue)); } } } return new TermsFilter(names.indexName(), bValues); } /** * We don't need to analyzer the text, and we need to convert it to UID... */ @Override public boolean useTermQueryWithQueryString() { return true; } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (!active()) { return builder; } builder.startObject(CONTENT_TYPE); builder.field("type", type); builder.endObject(); return builder; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { ParentFieldMapper other = (ParentFieldMapper) mergeWith; if (active() == other.active()) { return; } if (active() != other.active() || !type.equals(other.type)) { mergeContext.addConflict("The _parent field can't be added or updated"); } } /** * @return Whether the _parent field is actually used. */ public boolean active() { return type != null; } }
1no label
src_main_java_org_elasticsearch_index_mapper_internal_ParentFieldMapper.java
733
public class CollectionCompareAndRemoveRequest extends CollectionRequest { private Set<Data> valueSet; private boolean retain; public CollectionCompareAndRemoveRequest() { } public CollectionCompareAndRemoveRequest(String name, Set<Data> valueSet, boolean retain) { super(name); this.valueSet = valueSet; this.retain = retain; } @Override protected Operation prepareOperation() { return new CollectionCompareAndRemoveOperation(name, retain, valueSet); } @Override public int getClassId() { return CollectionPortableHook.COLLECTION_COMPARE_AND_REMOVE; } public void write(PortableWriter writer) throws IOException { super.write(writer); writer.writeBoolean("r", retain); final ObjectDataOutput out = writer.getRawDataOutput(); out.writeInt(valueSet.size()); for (Data value : valueSet) { value.writeData(out); } } public void read(PortableReader reader) throws IOException { super.read(reader); retain = reader.readBoolean("r"); final ObjectDataInput in = reader.getRawDataInput(); final int size = in.readInt(); valueSet = new HashSet<Data>(size); for (int i = 0; i < size; i++) { final Data value = new Data(); value.readData(in); valueSet.add(value); } } @Override public String getRequiredAction() { return ActionConstants.ACTION_REMOVE; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionCompareAndRemoveRequest.java
872
public class TransportSearchQueryAndFetchAction extends TransportSearchTypeAction { @Inject public TransportSearchQueryAndFetchAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) { super(settings, threadPool, clusterService, searchService, searchPhaseController); } @Override protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) { new AsyncAction(searchRequest, listener).start(); } private class AsyncAction extends BaseAsyncAction<QueryFetchSearchResult> { private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) { super(request, listener); } @Override protected String firstPhaseName() { return "query_fetch"; } @Override protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<QueryFetchSearchResult> listener) { searchService.sendExecuteFetch(node, request, listener); } @Override protected void moveToSecondPhase() throws Exception { try { innerFinishHim(); } catch (Throwable e) { ReduceSearchPhaseException failure = new ReduceSearchPhaseException("merge", "", e, buildShardFailures()); if (logger.isDebugEnabled()) { logger.debug("failed to reduce search", failure); } listener.onFailure(failure); } } private void innerFinishHim() throws IOException { sortedShardList = searchPhaseController.sortDocs(firstResults); final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, firstResults, firstResults); String scrollId = null; if (request.scroll() != null) { scrollId = buildScrollId(request.searchType(), firstResults, null); } listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successulOps.get(), buildTookInMillis(), buildShardFailures())); } } }
0true
src_main_java_org_elasticsearch_action_search_type_TransportSearchQueryAndFetchAction.java
780
searchAction.execute(searchRequest, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse response) { listener.onResponse(response); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } });
0true
src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java
760
public class ListRemoveOperation extends CollectionBackupAwareOperation { private int index; private long itemId; public ListRemoveOperation() { } public ListRemoveOperation(String name, int index) { super(name); this.index = index; } @Override public boolean shouldBackup() { return true; } @Override public Operation getBackupOperation() { return new CollectionRemoveBackupOperation(name, itemId); } @Override public int getId() { return CollectionDataSerializerHook.LIST_REMOVE; } @Override public void beforeRun() throws Exception { publishEvent(ItemEventType.ADDED, (Data) response); } @Override public void run() throws Exception { final CollectionItem item = getOrCreateListContainer().remove(index); itemId = item.getItemId(); response = item.getValue(); } @Override public void afterRun() throws Exception { } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeInt(index); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); index = in.readInt(); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_list_ListRemoveOperation.java
310
public enum ResourceType { FILESYSTEM,CLASSPATH }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_MergeFileSystemAndClassPathXMLApplicationContext.java
99
@SuppressWarnings("restriction") public class OUnsafeMemory implements ODirectMemory { public static final OUnsafeMemory INSTANCE; protected static final Unsafe unsafe; private static final boolean unaligned; private static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L; static { OUnsafeMemory futureInstance; unsafe = (Unsafe) AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return f.get(null); } catch (NoSuchFieldException e) { throw new Error(); } catch (IllegalAccessException e) { throw new Error(); } } }); try { unsafe.getClass().getDeclaredMethod("copyMemory", Object.class, long.class, Object.class, long.class, long.class); Class<?> unsafeMemoryJava7 = OUnsafeMemory.class.getClassLoader().loadClass( "com.orientechnologies.common.directmemory.OUnsafeMemoryJava7"); futureInstance = (OUnsafeMemory) unsafeMemoryJava7.newInstance(); } catch (Exception e) { futureInstance = new OUnsafeMemory(); } INSTANCE = futureInstance; String arch = System.getProperty("os.arch"); unaligned = arch.equals("i386") || arch.equals("x86") || arch.equals("amd64") || arch.equals("x86_64"); } @Override public long allocate(byte[] bytes) { final long pointer = unsafe.allocateMemory(bytes.length); set(pointer, bytes, 0, bytes.length); return pointer; } @Override public long allocate(long size) { return unsafe.allocateMemory(size); } @Override public void free(long pointer) { unsafe.freeMemory(pointer); } @Override public byte[] get(long pointer, final int length) { final byte[] result = new byte[length]; for (int i = 0; i < length; i++) result[i] = unsafe.getByte(pointer++); return result; } @Override public void get(long pointer, byte[] array, int arrayOffset, int length) { pointer += arrayOffset; for (int i = arrayOffset; i < length + arrayOffset; i++) array[i] = unsafe.getByte(pointer++); } @Override public void set(long pointer, byte[] content, int arrayOffset, int length) { for (int i = arrayOffset; i < length + arrayOffset; i++) unsafe.putByte(pointer++, content[i]); } @Override public int getInt(long pointer) { if (unaligned) return unsafe.getInt(pointer); return (0xFF & unsafe.getByte(pointer++)) << 24 | (0xFF & unsafe.getByte(pointer++)) << 16 | (0xFF & unsafe.getByte(pointer++)) << 8 | (0xFF & unsafe.getByte(pointer)); } @Override public void setInt(long pointer, int value) { if (unaligned) unsafe.putInt(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 24)); unsafe.putByte(pointer++, (byte) (value >>> 16)); unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) (value)); } } @Override public void setShort(long pointer, short value) { if (unaligned) unsafe.putShort(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) value); } } @Override public short getShort(long pointer) { if (unaligned) return unsafe.getShort(pointer); return (short) (unsafe.getByte(pointer++) << 8 | (unsafe.getByte(pointer) & 0xff)); } @Override public void setChar(long pointer, char value) { if (unaligned) unsafe.putChar(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) (value)); } } @Override public char getChar(long pointer) { if (unaligned) return unsafe.getChar(pointer); return (char) ((unsafe.getByte(pointer++) << 8) | (unsafe.getByte(pointer) & 0xff)); } @Override public long getLong(long pointer) { if (unaligned) return unsafe.getLong(pointer); return (0xFFL & unsafe.getByte(pointer++)) << 56 | (0xFFL & unsafe.getByte(pointer++)) << 48 | (0xFFL & unsafe.getByte(pointer++)) << 40 | (0xFFL & unsafe.getByte(pointer++)) << 32 | (0xFFL & unsafe.getByte(pointer++)) << 24 | (0xFFL & unsafe.getByte(pointer++)) << 16 | (0xFFL & unsafe.getByte(pointer++)) << 8 | (0xFFL & unsafe.getByte(pointer)); } @Override public void setLong(long pointer, long value) { if (unaligned) unsafe.putLong(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 56)); unsafe.putByte(pointer++, (byte) (value >>> 48)); unsafe.putByte(pointer++, (byte) (value >>> 40)); unsafe.putByte(pointer++, (byte) (value >>> 32)); unsafe.putByte(pointer++, (byte) (value >>> 24)); unsafe.putByte(pointer++, (byte) (value >>> 16)); unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) (value)); } } @Override public byte getByte(long pointer) { return unsafe.getByte(pointer); } @Override public void setByte(long pointer, byte value) { unsafe.putByte(pointer, value); } @Override public void moveData(long srcPointer, long destPointer, long len) { while (len > 0) { long size = (len > UNSAFE_COPY_THRESHOLD) ? UNSAFE_COPY_THRESHOLD : len; unsafe.copyMemory(srcPointer, destPointer, size); len -= size; srcPointer += size; destPointer += size; } } }
0true
commons_src_main_java_com_orientechnologies_common_directmemory_OUnsafeMemory.java
388
new Thread(){ public void run() { try { if(mm.tryLock(key, 10, TimeUnit.SECONDS)){ tryLockReturnsTrue.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapLockTest.java
4,836
public class RestGetFieldMappingAction extends BaseRestHandler { @Inject public RestGetFieldMappingAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(GET, "/_mapping/field/{fields}", this); controller.registerHandler(GET, "/_mapping/{type}/field/{fields}", this); controller.registerHandler(GET, "/{index}/_mapping/field/{fields}", this); controller.registerHandler(GET, "/{index}/{type}/_mapping/field/{fields}", this); controller.registerHandler(GET, "/{index}/_mapping/{type}/field/{fields}", this); } @Override public void handleRequest(final RestRequest request, final RestChannel channel) { final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); final String[] types = request.paramAsStringArrayOrEmptyIfAll("type"); final String[] fields = Strings.splitStringByCommaToArray(request.param("fields")); GetFieldMappingsRequest getMappingsRequest = new GetFieldMappingsRequest(); getMappingsRequest.indices(indices).types(types).fields(fields).includeDefaults(request.paramAsBoolean("include_defaults", false)); getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions())); getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local())); client.admin().indices().getFieldMappings(getMappingsRequest, new ActionListener<GetFieldMappingsResponse>() { @SuppressWarnings("unchecked") @Override public void onResponse(GetFieldMappingsResponse response) { try { ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex = response.mappings(); boolean isPossibleSingleFieldRequest = indices.length == 1 && types.length == 1 && fields.length == 1; if (isPossibleSingleFieldRequest && isFieldMappingMissingField(mappingsByIndex)) { channel.sendResponse(new XContentRestResponse(request, OK, emptyBuilder(request))); return; } RestStatus status = OK; if (mappingsByIndex.isEmpty() && fields.length > 0) { status = NOT_FOUND; } XContentBuilder builder = RestXContentBuilder.restContentBuilder(request); builder.startObject(); response.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); channel.sendResponse(new XContentRestResponse(request, status, builder)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } /** * * Helper method to find out if the only included fieldmapping metadata is typed NULL, which means * that type and index exist, but the field did not */ private boolean isFieldMappingMissingField(ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex) throws IOException { if (mappingsByIndex.size() != 1) { return false; } for (ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>> value : mappingsByIndex.values()) { for (ImmutableMap<String, FieldMappingMetaData> fieldValue : value.values()) { for (Map.Entry<String, FieldMappingMetaData> fieldMappingMetaDataEntry : fieldValue.entrySet()) { if (fieldMappingMetaDataEntry.getValue().isNull()) { return true; } } } } return false; } }
1no label
src_main_java_org_elasticsearch_rest_action_admin_indices_mapping_get_RestGetFieldMappingAction.java
3,426
nodeEngine.getExecutionService().execute(ExecutionService.SYSTEM_EXECUTOR, new Runnable() { public void run() { try { ((InitializingObject) object).initialize(); } catch (Exception e) { getLogger().warning("Error while initializing proxy: " + object, e); } } });
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_ProxyServiceImpl.java
512
public class TransportDeleteIndexAction extends TransportMasterNodeOperationAction<DeleteIndexRequest, DeleteIndexResponse> { private final MetaDataDeleteIndexService deleteIndexService; private final DestructiveOperations destructiveOperations; @Inject public TransportDeleteIndexAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, MetaDataDeleteIndexService deleteIndexService, NodeSettingsService nodeSettingsService) { super(settings, transportService, clusterService, threadPool); this.deleteIndexService = deleteIndexService; this.destructiveOperations = new DestructiveOperations(logger, settings, nodeSettingsService); } @Override protected String executor() { return ThreadPool.Names.SAME; } @Override protected String transportAction() { return DeleteIndexAction.NAME; } @Override protected DeleteIndexRequest newRequest() { return new DeleteIndexRequest(); } @Override protected DeleteIndexResponse newResponse() { return new DeleteIndexResponse(); } @Override protected void doExecute(DeleteIndexRequest request, ActionListener<DeleteIndexResponse> listener) { destructiveOperations.failDestructive(request.indices()); super.doExecute(request, listener); } @Override protected ClusterBlockException checkBlock(DeleteIndexRequest request, ClusterState state) { return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices()); } @Override protected void masterOperation(final DeleteIndexRequest request, final ClusterState state, final ActionListener<DeleteIndexResponse> listener) throws ElasticsearchException { request.indices(state.metaData().concreteIndices(request.indices(), request.indicesOptions())); if (request.indices().length == 0) { listener.onResponse(new DeleteIndexResponse(true)); return; } // TODO: this API should be improved, currently, if one delete index failed, we send a failure, we should send a response array that includes all the indices that were deleted final CountDown count = new CountDown(request.indices().length); for (final String index : request.indices()) { deleteIndexService.deleteIndex(new MetaDataDeleteIndexService.Request(index).timeout(request.timeout()).masterTimeout(request.masterNodeTimeout()), new MetaDataDeleteIndexService.Listener() { private volatile Throwable lastFailure; private volatile boolean ack = true; @Override public void onResponse(MetaDataDeleteIndexService.Response response) { if (!response.acknowledged()) { ack = false; } if (count.countDown()) { if (lastFailure != null) { listener.onFailure(lastFailure); } else { listener.onResponse(new DeleteIndexResponse(ack)); } } } @Override public void onFailure(Throwable t) { logger.debug("[{}] failed to delete index", t, index); lastFailure = t; if (count.countDown()) { listener.onFailure(t); } } }); } } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_delete_TransportDeleteIndexAction.java
1,653
public abstract class Names { public static String randomNodeName(URL nodeNames) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(nodeNames.openStream(), Charsets.UTF_8)); int numberOfNames = 0; while (reader.readLine() != null) { numberOfNames++; } reader.close(); reader = new BufferedReader(new InputStreamReader(nodeNames.openStream(), Charsets.UTF_8)); int number = ((ThreadLocalRandom.current().nextInt(numberOfNames)) % numberOfNames); for (int i = 0; i < number; i++) { reader.readLine(); } return reader.readLine(); } catch (IOException e) { return null; } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { // ignore this exception } } } public static String randomNodeName(InputStream nodeNames) { if (nodeNames == null) { return null; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(nodeNames, Charsets.UTF_8)); int numberOfNames = Integer.parseInt(reader.readLine()); int number = ((new Random().nextInt(numberOfNames)) % numberOfNames) - 2; // remove 2 for last line and first line for (int i = 0; i < number; i++) { reader.readLine(); } return reader.readLine(); } catch (Exception e) { return null; } finally { try { nodeNames.close(); } catch (IOException e) { // ignore } } } private Names() { } }
1no label
src_main_java_org_elasticsearch_common_Names.java
3,722
private static final Comparator<ScheduledEntry> SCHEDULED_ENTRIES_COMPARATOR = new Comparator<ScheduledEntry>() { @Override public int compare(ScheduledEntry o1, ScheduledEntry o2) { if (o1.getScheduleStartTimeInNanos() > o2.getScheduleStartTimeInNanos()) { return 1; } else if (o1.getScheduleStartTimeInNanos() < o2.getScheduleStartTimeInNanos()) { return -1; } return 0; } };
1no label
hazelcast_src_main_java_com_hazelcast_util_scheduler_SecondsBasedEntryTaskScheduler.java
261
public interface OCommandContext { public enum TIMEOUT_STRATEGY { RETURN, EXCEPTION } public Object getVariable(String iName); public Object getVariable(String iName, Object iDefaultValue); public OCommandContext setVariable(final String iName, final Object iValue); public Map<String, Object> getVariables(); public OCommandContext getParent(); public OCommandContext setParent(OCommandContext iParentContext); public OCommandContext setChild(OCommandContext context); /** * Updates a counter. Used to record metrics. * * @param iName * Metric's name * @param iValue * delta to add or subtract * @return */ public long updateMetric(String iName, long iValue); public boolean isRecordingMetrics(); public OCommandContext setRecordingMetrics(boolean recordMetrics); public void beginExecution(long timeoutMs, TIMEOUT_STRATEGY iStrategy); public boolean checkTimeout(); }
0true
core_src_main_java_com_orientechnologies_orient_core_command_OCommandContext.java
377
public class TransportPutRepositoryAction extends TransportMasterNodeOperationAction<PutRepositoryRequest, PutRepositoryResponse> { private final RepositoriesService repositoriesService; @Inject public TransportPutRepositoryAction(Settings settings, TransportService transportService, ClusterService clusterService, RepositoriesService repositoriesService, ThreadPool threadPool) { super(settings, transportService, clusterService, threadPool); this.repositoriesService = repositoriesService; } @Override protected String executor() { return ThreadPool.Names.SAME; } @Override protected String transportAction() { return PutRepositoryAction.NAME; } @Override protected PutRepositoryRequest newRequest() { return new PutRepositoryRequest(); } @Override protected PutRepositoryResponse newResponse() { return new PutRepositoryResponse(); } @Override protected ClusterBlockException checkBlock(PutRepositoryRequest request, ClusterState state) { return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, ""); } @Override protected void masterOperation(final PutRepositoryRequest request, ClusterState state, final ActionListener<PutRepositoryResponse> listener) throws ElasticsearchException { repositoriesService.registerRepository(new RepositoriesService.RegisterRepositoryRequest("put_repository [" + request.name() + "]", request.name(), request.type()) .settings(request.settings()) .masterNodeTimeout(request.masterNodeTimeout()) .ackTimeout(request.timeout()), new ActionListener<RepositoriesService.RegisterRepositoryResponse>() { @Override public void onResponse(RepositoriesService.RegisterRepositoryResponse response) { listener.onResponse(new PutRepositoryResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } }); } }
1no label
src_main_java_org_elasticsearch_action_admin_cluster_repositories_put_TransportPutRepositoryAction.java
56
public interface OLock { public void lock(); public void unlock(); public <V> V callInLock(Callable<V> iCallback) throws Exception; }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OLock.java
1,364
public class OStorageMemory extends OStorageEmbedded { private final List<ODataSegmentMemory> dataSegments = new ArrayList<ODataSegmentMemory>(); private final List<OClusterMemory> clusters = new ArrayList<OClusterMemory>(); private final Map<String, OClusterMemory> clusterMap = new HashMap<String, OClusterMemory>(); private int defaultClusterId = 0; private long positionGenerator = 0; public OStorageMemory(final String iURL) { super(iURL, iURL, "rw"); configuration = new OStorageConfiguration(this); } public void create(final Map<String, Object> iOptions) { addUser(); lock.acquireExclusiveLock(); try { addDataSegment(OStorage.DATA_DEFAULT_NAME); addDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME); // ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF addCluster(CLUSTER_TYPE.PHYSICAL.toString(), OMetadataDefault.CLUSTER_INTERNAL_NAME, null, null, true); // ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF INDEXING IN THE INDEX DATA SEGMENT addCluster(CLUSTER_TYPE.PHYSICAL.toString(), OMetadataDefault.CLUSTER_INDEX_NAME, null, OMetadataDefault.DATASEGMENT_INDEX_NAME, true); // ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF INDEXING addCluster(CLUSTER_TYPE.PHYSICAL.toString(), OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME, null, null, true); // ADD THE DEFAULT CLUSTER defaultClusterId = addCluster(CLUSTER_TYPE.PHYSICAL.toString(), CLUSTER_DEFAULT_NAME, null, null, false); configuration.create(); status = STATUS.OPEN; } catch (OStorageException e) { close(); throw e; } catch (IOException e) { close(); throw new OStorageException("Error on creation of storage: " + name, e); } finally { lock.releaseExclusiveLock(); } } public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iOptions) { addUser(); if (status == STATUS.OPEN) // ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS // REUSED return; lock.acquireExclusiveLock(); try { if (!exists()) throw new OStorageException("Cannot open the storage '" + name + "' because it does not exist in path: " + url); status = STATUS.OPEN; } finally { lock.releaseExclusiveLock(); } } public void close(final boolean iForce) { lock.acquireExclusiveLock(); try { if (!checkForClose(iForce)) return; status = STATUS.CLOSING; // CLOSE ALL THE CLUSTERS for (OClusterMemory c : clusters) if (c != null) c.close(); clusters.clear(); clusterMap.clear(); // CLOSE THE DATA SEGMENTS for (ODataSegmentMemory d : dataSegments) if (d != null) d.close(); dataSegments.clear(); level2Cache.shutdown(); super.close(iForce); Orient.instance().unregisterStorage(this); status = STATUS.CLOSED; } finally { lock.releaseExclusiveLock(); } } public void delete() { close(true); } @Override public void backup(OutputStream out, Map<String, Object> options, Callable<Object> callable) throws IOException { throw new UnsupportedOperationException("backup"); } @Override public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable) throws IOException { throw new UnsupportedOperationException("restore"); } public void reload() { } public int addCluster(final String iClusterType, String iClusterName, final String iLocation, final String iDataSegmentName, boolean forceListBased, final Object... iParameters) { iClusterName = iClusterName.toLowerCase(); lock.acquireExclusiveLock(); try { int clusterId = clusters.size(); for (int i = 0; i < clusters.size(); ++i) { if (clusters.get(i) == null) { clusterId = i; break; } } final OClusterMemory cluster = (OClusterMemory) Orient.instance().getClusterFactory().createCluster(OClusterMemory.TYPE); cluster.configure(this, clusterId, iClusterName, iLocation, getDataSegmentIdByName(iDataSegmentName), iParameters); if (clusterId == clusters.size()) // APPEND IT clusters.add(cluster); else // RECYCLE THE FREE POSITION clusters.set(clusterId, cluster); clusterMap.put(iClusterName, cluster); return clusterId; } finally { lock.releaseExclusiveLock(); } } public int addCluster(String iClusterType, String iClusterName, int iRequestedId, String iLocation, String iDataSegmentName, boolean forceListBased, Object... iParameters) { throw new UnsupportedOperationException("This operation is unsupported for " + getType() + " storage. If you are doing import please use parameter -preserveClusterIDs=false ."); } public boolean dropCluster(final int iClusterId, final boolean iTruncate) { lock.acquireExclusiveLock(); try { final OCluster c = clusters.get(iClusterId); if (c != null) { if (iTruncate) c.truncate(); c.delete(); clusters.set(iClusterId, null); getLevel2Cache().freeCluster(iClusterId); clusterMap.remove(c.getName()); } } catch (IOException e) { } finally { lock.releaseExclusiveLock(); } return false; } public boolean dropDataSegment(final String iName) { lock.acquireExclusiveLock(); try { final int id = getDataSegmentIdByName(iName); final ODataSegment data = dataSegments.get(id); if (data == null) return false; data.drop(); dataSegments.set(id, null); // UPDATE CONFIGURATION configuration.dropCluster(id); return true; } catch (Exception e) { OLogManager.instance().exception("Error while removing data segment '" + iName + '\'', e, OStorageException.class); } finally { lock.releaseExclusiveLock(); } return false; } public int addDataSegment(final String iDataSegmentName) { lock.acquireExclusiveLock(); try { int pos = -1; for (int i = 0; i < dataSegments.size(); ++i) { if (dataSegments.get(i) == null) { pos = i; break; } } if (pos == -1) pos = dataSegments.size(); final ODataSegmentMemory dataSegment = new ODataSegmentMemory(iDataSegmentName, pos); if (pos == dataSegments.size()) dataSegments.add(dataSegment); else dataSegments.set(pos, dataSegment); return pos; } finally { lock.releaseExclusiveLock(); } } public int addDataSegment(final String iSegmentName, final String iLocation) { return addDataSegment(iSegmentName); } public OStorageOperationResult<OPhysicalPosition> createRecord(final int iDataSegmentId, final ORecordId iRid, final byte[] iContent, ORecordVersion iRecordVersion, final byte iRecordType, final int iMode, ORecordCallback<OClusterPosition> iCallback) { final long timer = Orient.instance().getProfiler().startChrono(); lock.acquireSharedLock(); try { final ODataSegmentMemory data = getDataSegmentById(iDataSegmentId); final long offset = data.createRecord(iContent); final OCluster cluster = getClusterById(iRid.clusterId); // ASSIGN THE POSITION IN THE CLUSTER final OPhysicalPosition ppos = new OPhysicalPosition(iDataSegmentId, offset, iRecordType); if (cluster.isHashBased()) { if (iRid.isNew()) { if (OGlobalConfiguration.USE_NODE_ID_CLUSTER_POSITION.getValueAsBoolean()) { ppos.clusterPosition = OClusterPositionFactory.INSTANCE.generateUniqueClusterPosition(); } else { ppos.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(positionGenerator++); } } else { ppos.clusterPosition = iRid.clusterPosition; } } if (!cluster.addPhysicalPosition(ppos)) { data.readRecord(ppos.dataSegmentPos); throw new OStorageException("Record with given id " + iRid + " has already exists."); } iRid.clusterPosition = ppos.clusterPosition; if (iCallback != null) iCallback.call(iRid, iRid.clusterPosition); if (iRecordVersion.getCounter() > 0 && iRecordVersion.compareTo(ppos.recordVersion) != 0) { // OVERWRITE THE VERSION cluster.updateVersion(iRid.clusterPosition, iRecordVersion); ppos.recordVersion = iRecordVersion; } return new OStorageOperationResult<OPhysicalPosition>(ppos); } catch (IOException e) { throw new OStorageException("Error on create record in cluster: " + iRid.clusterId, e); } finally { lock.releaseSharedLock(); Orient.instance().getProfiler() .stopChrono(PROFILER_CREATE_RECORD, "Create a record in database", timer, "db.*.data.updateHole"); } } public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, String iFetchPlan, boolean iIgnoreCache, ORecordCallback<ORawBuffer> iCallback, boolean loadTombstones) { return new OStorageOperationResult<ORawBuffer>(readRecord(getClusterById(iRid.clusterId), iRid, true, loadTombstones)); } @Override protected ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, final boolean iAtomicLock, boolean loadTombstones) { final long timer = Orient.instance().getProfiler().startChrono(); lock.acquireSharedLock(); try { lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.SHARED); try { final OClusterPosition lastPos = iClusterSegment.getLastPosition(); if (!iClusterSegment.isHashBased()) { if (iRid.clusterPosition.compareTo(lastPos) > 0) return null; } final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(new OPhysicalPosition(iRid.clusterPosition)); if (ppos != null && loadTombstones && ppos.recordVersion.isTombstone()) return new ORawBuffer(null, ppos.recordVersion, ppos.recordType); if (ppos == null || ppos.recordVersion.isTombstone()) return null; final ODataSegmentMemory dataSegment = getDataSegmentById(ppos.dataSegmentId); return new ORawBuffer(dataSegment.readRecord(ppos.dataSegmentPos), ppos.recordVersion, ppos.recordType); } finally { lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.SHARED); } } catch (IOException e) { throw new OStorageException("Error on read record in cluster: " + iClusterSegment.getId(), e); } finally { lock.releaseSharedLock(); Orient.instance().getProfiler().stopChrono(PROFILER_READ_RECORD, "Read a record from database", timer, "db.*.readRecord"); } } public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType, final int iMode, ORecordCallback<ORecordVersion> iCallback) { final long timer = Orient.instance().getProfiler().startChrono(); final OCluster cluster = getClusterById(iRid.clusterId); lock.acquireSharedLock(); try { lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE); try { final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(iRid.clusterPosition)); if (ppos == null || ppos.recordVersion.isTombstone()) { final ORecordVersion v = OVersionFactory.instance().createUntrackedVersion(); if (iCallback != null) { iCallback.call(iRid, v); } return new OStorageOperationResult<ORecordVersion>(v); } // VERSION CONTROL CHECK switch (iVersion.getCounter()) { // DOCUMENT UPDATE, NO VERSION CONTROL case -1: ppos.recordVersion.increment(); cluster.updateVersion(iRid.clusterPosition, ppos.recordVersion); break; // DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION UPDATE case -2: break; default: // MVCC CONTROL AND RECORD UPDATE OR WRONG VERSION VALUE if (iVersion.getCounter() > -1) { // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME if (!iVersion.equals(ppos.recordVersion)) if (OFastConcurrentModificationException.enabled()) throw OFastConcurrentModificationException.instance(); else throw new OConcurrentModificationException(iRid, ppos.recordVersion, iVersion, ORecordOperation.UPDATED); ppos.recordVersion.increment(); cluster.updateVersion(iRid.clusterPosition, ppos.recordVersion); } else { // DOCUMENT ROLLBACKED iVersion.clearRollbackMode(); ppos.recordVersion.copyFrom(iVersion); cluster.updateVersion(iRid.clusterPosition, ppos.recordVersion); } } if (ppos.recordType != iRecordType) cluster.updateRecordType(iRid.clusterPosition, iRecordType); final ODataSegmentMemory dataSegment = getDataSegmentById(ppos.dataSegmentId); dataSegment.updateRecord(ppos.dataSegmentPos, iContent); if (iCallback != null) iCallback.call(null, ppos.recordVersion); return new OStorageOperationResult<ORecordVersion>(ppos.recordVersion); } finally { lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE); } } catch (IOException e) { throw new OStorageException("Error on update record " + iRid, e); } finally { lock.releaseSharedLock(); Orient.instance().getProfiler().stopChrono(PROFILER_UPDATE_RECORD, "Update a record to database", timer, "db.*.updateRecord"); } } @Override public boolean updateReplica(int dataSegmentId, ORecordId rid, byte[] content, ORecordVersion recordVersion, byte recordType) throws IOException { if (rid.isNew()) throw new OStorageException("Passed record with id " + rid + " is new and can not be treated as replica."); checkOpeness(); final OCluster cluster = getClusterById(rid.clusterId); final ODataSegmentMemory data = getDataSegmentById(dataSegmentId); lock.acquireSharedLock(); try { lockManager.acquireLock(Thread.currentThread(), rid, LOCK.EXCLUSIVE); try { OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.clusterPosition)); if (ppos == null) { if (!cluster.isHashBased()) throw new OStorageException("Cluster with LH support is required."); ppos = new OPhysicalPosition(rid.clusterPosition, recordVersion); ppos.recordType = recordType; ppos.dataSegmentId = data.getId(); if (!recordVersion.isTombstone()) { ppos.dataSegmentPos = data.createRecord(content); } cluster.addPhysicalPosition(ppos); return true; } else { if (ppos.recordType != recordType) throw new OStorageException("Record types of provided and stored replicas are different " + recordType + ":" + ppos.recordType + "."); if (ppos.recordVersion.compareTo(recordVersion) < 0) { if (!recordVersion.isTombstone() && !ppos.recordVersion.isTombstone()) { data.updateRecord(ppos.dataSegmentPos, content); } else if (recordVersion.isTombstone() && !ppos.recordVersion.isTombstone()) { data.deleteRecord(ppos.dataSegmentPos); } else if (!recordVersion.isTombstone() && ppos.recordVersion.isTombstone()) { ppos.dataSegmentPos = data.createRecord(content); cluster.updateDataSegmentPosition(ppos.clusterPosition, dataSegmentId, ppos.dataSegmentPos); } cluster.updateVersion(ppos.clusterPosition, recordVersion); return true; } } } finally { lockManager.releaseLock(Thread.currentThread(), rid, LOCK.EXCLUSIVE); } } finally { lock.releaseSharedLock(); } return false; } @Override public <V> V callInRecordLock(Callable<V> callable, ORID rid, boolean exclusiveLock) { lock.acquireSharedLock(); try { lockManager.acquireLock(Thread.currentThread(), rid, exclusiveLock ? LOCK.EXCLUSIVE : LOCK.SHARED); try { return callable.call(); } finally { lockManager.releaseLock(Thread.currentThread(), rid, exclusiveLock ? LOCK.EXCLUSIVE : LOCK.SHARED); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new OException("Error on nested call in lock", e); } finally { lock.releaseSharedLock(); } } @Override public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRid, final ORecordVersion iVersion, final int iMode, ORecordCallback<Boolean> iCallback) { return new OStorageOperationResult<Boolean>(deleteRecord(iRid, iVersion, OGlobalConfiguration.STORAGE_USE_TOMBSTONES.getValueAsBoolean(), iCallback)); } @Override public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) { return deleteRecord(recordId, recordVersion, false, callback); } private boolean deleteRecord(ORecordId iRid, ORecordVersion iVersion, boolean useTombstones, ORecordCallback<Boolean> iCallback) { final long timer = Orient.instance().getProfiler().startChrono(); final OCluster cluster = getClusterById(iRid.clusterId); lock.acquireSharedLock(); try { lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE); try { final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(iRid.clusterPosition)); if (ppos == null || (ppos.recordVersion.isTombstone() && useTombstones)) { if (iCallback != null) iCallback.call(iRid, false); return false; } // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME if (iVersion.getCounter() > -1 && !ppos.recordVersion.equals(iVersion)) if (OFastConcurrentModificationException.enabled()) throw OFastConcurrentModificationException.instance(); else throw new OConcurrentModificationException(iRid, ppos.recordVersion, iVersion, ORecordOperation.DELETED); if (!ppos.recordVersion.isTombstone()) { final ODataSegmentMemory dataSegment = getDataSegmentById(ppos.dataSegmentId); dataSegment.deleteRecord(ppos.dataSegmentPos); ppos.dataSegmentPos = -1; } if (useTombstones && cluster.hasTombstonesSupport()) cluster.convertToTombstone(iRid.clusterPosition); else cluster.removePhysicalPosition(iRid.clusterPosition); if (iCallback != null) iCallback.call(null, true); return true; } finally { lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE); } } catch (IOException e) { throw new OStorageException("Error on delete record " + iRid, e); } finally { lock.releaseSharedLock(); Orient.instance().getProfiler() .stopChrono(PROFILER_DELETE_RECORD, "Delete a record from database", timer, "db.*.deleteRecord"); } } public long count(final int iClusterId) { return count(iClusterId, false); } @Override public long count(int iClusterId, boolean countTombstones) { final OCluster cluster = getClusterById(iClusterId); lock.acquireSharedLock(); try { return cluster.getEntries() - (countTombstones ? 0L : cluster.getTombstonesCount()); } finally { lock.releaseSharedLock(); } } public OClusterPosition[] getClusterDataRange(final int iClusterId) { final OCluster cluster = getClusterById(iClusterId); lock.acquireSharedLock(); try { return new OClusterPosition[] { cluster.getFirstPosition(), cluster.getLastPosition() }; } catch (IOException ioe) { throw new OStorageException("Can not retrieve information about data range", ioe); } finally { lock.releaseSharedLock(); } } public long count(final int[] iClusterIds) { return count(iClusterIds, false); } @Override public long count(int[] iClusterIds, boolean countTombstones) { lock.acquireSharedLock(); try { long tot = 0; for (int iClusterId : iClusterIds) { if (iClusterId > -1) { final OCluster cluster = clusters.get(iClusterId); if (cluster != null) tot += cluster.getEntries() - (countTombstones ? 0L : cluster.getTombstonesCount()); } } return tot; } finally { lock.releaseSharedLock(); } } public OCluster getClusterByName(final String iClusterName) { lock.acquireSharedLock(); try { return clusterMap.get(iClusterName.toLowerCase()); } finally { lock.releaseSharedLock(); } } public int getClusterIdByName(String iClusterName) { iClusterName = iClusterName.toLowerCase(); lock.acquireSharedLock(); try { final OCluster cluster = clusterMap.get(iClusterName.toLowerCase()); if (cluster == null) return -1; return cluster.getId(); } finally { lock.releaseSharedLock(); } } public String getClusterTypeByName(final String iClusterName) { return OClusterMemory.TYPE; } public String getPhysicalClusterNameById(final int iClusterId) { lock.acquireSharedLock(); try { for (OClusterMemory cluster : clusters) { if (cluster != null && cluster.getId() == iClusterId) return cluster.getName(); } return null; } finally { lock.releaseSharedLock(); } } public Set<String> getClusterNames() { lock.acquireSharedLock(); try { return new HashSet<String>(clusterMap.keySet()); } finally { lock.releaseSharedLock(); } } public void commit(final OTransaction iTx, Runnable callback) { lock.acquireExclusiveLock(); try { final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>(); while (iTx.getCurrentRecordEntries().iterator().hasNext()) { for (ORecordOperation txEntry : iTx.getCurrentRecordEntries()) tmpEntries.add(txEntry); iTx.clearRecordEntries(); for (ORecordOperation txEntry : tmpEntries) // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE commitEntry(iTx, txEntry); tmpEntries.clear(); } // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT OTransactionAbstract.updateCacheFromEntries(iTx, iTx.getAllRecordEntries(), true); } catch (IOException e) { rollback(iTx); } finally { lock.releaseExclusiveLock(); } } public void rollback(final OTransaction iTx) { } public void synch() { } public boolean exists() { lock.acquireSharedLock(); try { return !clusters.isEmpty(); } finally { lock.releaseSharedLock(); } } public ODataSegmentMemory getDataSegmentById(int iDataId) { lock.acquireSharedLock(); try { if (iDataId < 0 || iDataId > dataSegments.size() - 1) throw new IllegalArgumentException("Invalid data segment id " + iDataId + ". Range is 0-" + (dataSegments.size() - 1)); return dataSegments.get(iDataId); } finally { lock.releaseSharedLock(); } } public int getDataSegmentIdByName(final String iDataSegmentName) { if (iDataSegmentName == null) return 0; lock.acquireSharedLock(); try { for (ODataSegmentMemory d : dataSegments) if (d != null && d.getName().equalsIgnoreCase(iDataSegmentName)) return d.getId(); throw new IllegalArgumentException("Data segment '" + iDataSegmentName + "' does not exist in storage '" + name + "'"); } finally { lock.releaseSharedLock(); } } public OCluster getClusterById(int iClusterId) { lock.acquireSharedLock(); try { if (iClusterId == ORID.CLUSTER_ID_INVALID) // GET THE DEFAULT CLUSTER iClusterId = defaultClusterId; checkClusterSegmentIndexRange(iClusterId); return clusters.get(iClusterId); } finally { lock.releaseSharedLock(); } } public int getClusters() { lock.acquireSharedLock(); try { return clusterMap.size(); } finally { lock.releaseSharedLock(); } } public Collection<? extends OCluster> getClusterInstances() { lock.acquireSharedLock(); try { return Collections.unmodifiableCollection(clusters); } finally { lock.releaseSharedLock(); } } public int getDefaultClusterId() { return defaultClusterId; } public long getSize() { long size = 0; lock.acquireSharedLock(); try { for (ODataSegmentMemory d : dataSegments) if (d != null) size += d.getSize(); } finally { lock.releaseSharedLock(); } return size; } @Override public boolean checkForRecordValidity(final OPhysicalPosition ppos) { if (ppos.dataSegmentId > 0) return false; lock.acquireSharedLock(); try { final ODataSegmentMemory dataSegment = getDataSegmentById(ppos.dataSegmentId); if (ppos.dataSegmentPos >= dataSegment.count()) return false; } finally { lock.releaseSharedLock(); } return true; } private void commitEntry(final OTransaction iTx, final ORecordOperation txEntry) throws IOException { final ORecordId rid = (ORecordId) txEntry.getRecord().getIdentity(); final OCluster cluster = getClusterById(rid.clusterId); rid.clusterId = cluster.getId(); if (txEntry.getRecord() instanceof OTxListener) ((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.BEFORE_COMMIT); switch (txEntry.type) { case ORecordOperation.LOADED: break; case ORecordOperation.CREATED: if (rid.isNew()) { // CHECK 2 TIMES TO ASSURE THAT IT'S A CREATE OR AN UPDATE BASED ON RECURSIVE TO-STREAM METHOD final byte[] stream = txEntry.getRecord().toStream(); if (stream == null) { OLogManager.instance().warn(this, "Null serialization on committing new record %s in transaction", rid); break; } if (rid.isNew()) { final ORecordId oldRID = rid.copy(); final OPhysicalPosition ppos = createRecord(txEntry.dataSegmentId, rid, stream, OVersionFactory.instance().createVersion(), txEntry.getRecord().getRecordType(), 0, null).getResult(); txEntry.getRecord().getRecordVersion().copyFrom(ppos.recordVersion); iTx.updateIdentityAfterCommit(oldRID, rid); } else { txEntry .getRecord() .getRecordVersion() .copyFrom( updateRecord(rid, stream, txEntry.getRecord().getRecordVersion(), txEntry.getRecord().getRecordType(), 0, null) .getResult()); } } break; case ORecordOperation.UPDATED: final byte[] stream = txEntry.getRecord().toStream(); if (stream == null) { OLogManager.instance().warn(this, "Null serialization on committing updated record %s in transaction", rid); break; } txEntry .getRecord() .getRecordVersion() .copyFrom( updateRecord(rid, stream, txEntry.getRecord().getRecordVersion(), txEntry.getRecord().getRecordType(), 0, null) .getResult()); break; case ORecordOperation.DELETED: deleteRecord(rid, txEntry.getRecord().getRecordVersion(), 0, null); break; } txEntry.getRecord().unsetDirty(); if (txEntry.getRecord() instanceof OTxListener) ((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.AFTER_COMMIT); } @Override public String getURL() { return OEngineMemory.NAME + ":" + url; } public OStorageConfigurationSegment getConfigurationSegment() { return null; } public void renameCluster(final String iOldName, final String iNewName) { final OClusterMemory cluster = (OClusterMemory) getClusterByName(iOldName); if (cluster != null) try { cluster.set(com.orientechnologies.orient.core.storage.OCluster.ATTRIBUTES.NAME, iNewName); } catch (IOException e) { } } public void setDefaultClusterId(int defaultClusterId) { this.defaultClusterId = defaultClusterId; } @Override public String getType() { return OEngineMemory.NAME; } private void checkClusterSegmentIndexRange(final int iClusterId) { if (iClusterId > clusters.size() - 1) throw new IllegalArgumentException("Cluster segment #" + iClusterId + " does not exist in database '" + name + "'"); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_storage_impl_memory_OStorageMemory.java

Dataset Card for "java_unifiedbug_2_1"

More Information needed

Downloads last month
0
Edit dataset card